Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob889987cc7ce73a700e7a58a2823a08595f4fc953
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 <http://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-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp) ;Silence byte-compiler
189 (defsubst org-uniquify (list)
190 "Non-destructively remove duplicate elements from LIST."
191 (let ((res (copy-sequence list))) (delete-dups res)))
193 (defsubst org-get-at-bol (property)
194 "Get text property PROPERTY at the beginning of line."
195 (get-text-property (point-at-bol) property))
197 (defsubst org-trim (s &optional keep-lead)
198 "Remove whitespace at the beginning and the end of string S.
199 When optional argument KEEP-LEAD is non-nil, removing blank lines
200 at the beginning of the string does not affect leading indentation."
201 (replace-regexp-in-string
202 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
203 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
205 ;; load languages based on value of `org-babel-load-languages'
206 (defvar org-babel-load-languages)
208 ;;;###autoload
209 (defun org-babel-do-load-languages (sym value)
210 "Load the languages defined in `org-babel-load-languages'."
211 (set-default sym value)
212 (dolist (pair org-babel-load-languages)
213 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
214 (if active
215 (require (intern (concat "ob-" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-execute:" lang)))
218 (funcall 'fmakunbound
219 (intern (concat "org-babel-expand-body:" lang)))))))
221 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
222 ;;;###autoload
223 (defun org-babel-load-file (file &optional compile)
224 "Load Emacs Lisp source code blocks in the Org FILE.
225 This function exports the source code using `org-babel-tangle'
226 and then loads the resulting file using `load-file'. With prefix
227 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
228 file to byte-code before it is loaded."
229 (interactive "fFile to load: \nP")
230 (let* ((age (lambda (file)
231 (float-time
232 (time-subtract (current-time)
233 (nth 5 (or (file-attributes (file-truename file))
234 (file-attributes file)))))))
235 (base-name (file-name-sans-extension file))
236 (exported-file (concat base-name ".el")))
237 ;; tangle if the Org file is newer than the elisp file
238 (unless (and (file-exists-p exported-file)
239 (> (funcall age file) (funcall age exported-file)))
240 ;; Tangle-file traversal returns reversed list of tangled files
241 ;; and we want to evaluate the first target.
242 (setq exported-file
243 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
244 (message "%s %s"
245 (if compile
246 (progn (byte-compile-file exported-file 'load)
247 "Compiled and loaded")
248 (progn (load-file exported-file) "Loaded"))
249 exported-file)))
251 (defcustom org-babel-load-languages '((emacs-lisp . t))
252 "Languages which can be evaluated in Org buffers.
253 This list can be used to load support for any of the languages
254 below, note that each language will depend on a different set of
255 system executables and/or Emacs modes. When a language is
256 \"loaded\", then code blocks in that language can be evaluated
257 with `org-babel-execute-src-block' bound by default to C-c
258 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
259 be set to remove code block evaluation from the C-c C-c
260 keybinding. By default only Emacs Lisp (which has no
261 requirements) is loaded."
262 :group 'org-babel
263 :set 'org-babel-do-load-languages
264 :version "24.1"
265 :type '(alist :tag "Babel Languages"
266 :key-type
267 (choice
268 (const :tag "Awk" awk)
269 (const :tag "C" C)
270 (const :tag "R" R)
271 (const :tag "Asymptote" asymptote)
272 (const :tag "Calc" calc)
273 (const :tag "Clojure" clojure)
274 (const :tag "CSS" css)
275 (const :tag "Ditaa" ditaa)
276 (const :tag "Dot" dot)
277 (const :tag "Ebnf2ps" ebnf2ps)
278 (const :tag "Emacs Lisp" emacs-lisp)
279 (const :tag "Forth" forth)
280 (const :tag "Fortran" fortran)
281 (const :tag "Gnuplot" gnuplot)
282 (const :tag "Haskell" haskell)
283 (const :tag "hledger" hledger)
284 (const :tag "IO" io)
285 (const :tag "J" J)
286 (const :tag "Java" java)
287 (const :tag "Javascript" js)
288 (const :tag "LaTeX" latex)
289 (const :tag "Ledger" ledger)
290 (const :tag "Lilypond" lilypond)
291 (const :tag "Lisp" lisp)
292 (const :tag "Makefile" makefile)
293 (const :tag "Maxima" maxima)
294 (const :tag "Matlab" matlab)
295 (const :tag "Mscgen" mscgen)
296 (const :tag "Ocaml" ocaml)
297 (const :tag "Octave" octave)
298 (const :tag "Org" org)
299 (const :tag "Perl" perl)
300 (const :tag "Pico Lisp" picolisp)
301 (const :tag "PlantUML" plantuml)
302 (const :tag "Python" python)
303 (const :tag "Ruby" ruby)
304 (const :tag "Sass" sass)
305 (const :tag "Scala" scala)
306 (const :tag "Scheme" scheme)
307 (const :tag "Screen" screen)
308 (const :tag "Shell Script" shell)
309 (const :tag "Shen" shen)
310 (const :tag "Sql" sql)
311 (const :tag "Sqlite" sqlite)
312 (const :tag "Stan" stan)
313 (const :tag "Vala" vala))
314 :value-type (boolean :tag "Activate" :value t)))
316 ;;;; Customization variables
317 (defcustom org-clone-delete-id nil
318 "Remove ID property of clones of a subtree.
319 When non-nil, clones of a subtree don't inherit the ID property.
320 Otherwise they inherit the ID property with a new unique
321 identifier."
322 :type 'boolean
323 :version "24.1"
324 :group 'org-id)
326 ;;; Version
327 (org-check-version)
329 ;;;###autoload
330 (defun org-version (&optional here full message)
331 "Show the Org version.
332 Interactively, or when MESSAGE is non-nil, show it in echo area.
333 With prefix argument, or when HERE is non-nil, insert it at point.
334 In non-interactive uses, a reduced version string is output unless
335 FULL is given."
336 (interactive (list current-prefix-arg t (not current-prefix-arg)))
337 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
338 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
339 (load-suffixes (list ".el"))
340 (org-install-dir
341 (ignore-errors (org-find-library-dir "org-loaddefs"))))
342 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
343 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
344 (let* ((load-suffixes save-load-suffixes)
345 (release (org-release))
346 (git-version (org-git-version))
347 (version (format "Org mode version %s (%s @ %s)"
348 release
349 git-version
350 (if org-install-dir
351 (if (string= org-dir org-install-dir)
352 org-install-dir
353 (concat "mixed installation! "
354 org-install-dir
355 " and "
356 org-dir))
357 "org-loaddefs.el can not be found!")))
358 (version1 (if full version release)))
359 (when here (insert version1))
360 (when message (message "%s" version1))
361 version1)))
363 (defconst org-version (org-version))
366 ;;; Syntax Constants
368 ;;;; Block
370 (defconst org-block-regexp
371 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
372 "Regular expression for hiding blocks.")
374 (defconst org-dblock-start-re
375 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
376 "Matches the start line of a dynamic block, with parameters.")
378 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
379 "Matches the end of a dynamic block.")
381 ;;;; Clock and Planning
383 (defconst org-clock-string "CLOCK:"
384 "String used as prefix for timestamps clocking work hours on an item.")
386 (defvar org-closed-string "CLOSED:"
387 "String used as the prefix for timestamps logging closing a TODO entry.")
389 (defvar org-deadline-string "DEADLINE:"
390 "String to mark deadline entries.
391 \\<org-mode-map>
392 A deadline is this string, followed by a time stamp. It must be
393 a word, terminated by a colon. You can insert a schedule keyword
394 and a timestamp with `\\[org-deadline]'.")
396 (defvar org-scheduled-string "SCHEDULED:"
397 "String to mark scheduled TODO entries.
398 \\<org-mode-map>
399 A schedule is this string, followed by a time stamp. It must be
400 a word, terminated by a colon. You can insert a schedule keyword
401 and a timestamp with `\\[org-schedule]'.")
403 (defconst org-ds-keyword-length
404 (+ 2
405 (apply #'max
406 (mapcar #'length
407 (list org-deadline-string org-scheduled-string
408 org-clock-string org-closed-string))))
409 "Maximum length of the DEADLINE and SCHEDULED keywords.")
411 (defconst org-planning-line-re
412 (concat "^[ \t]*"
413 (regexp-opt
414 (list org-closed-string org-deadline-string org-scheduled-string)
416 "Matches a line with planning info.
417 Matched keyword is in group 1.")
419 (defconst org-clock-line-re
420 (concat "^[ \t]*" org-clock-string)
421 "Matches a line with clock info.")
423 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
424 "Matches the DEADLINE keyword.")
426 (defconst org-deadline-time-regexp
427 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
428 "Matches the DEADLINE keyword together with a time stamp.")
430 (defconst org-deadline-time-hour-regexp
431 (concat "\\<" org-deadline-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
435 (defconst org-deadline-line-regexp
436 (concat "\\<\\(" org-deadline-string "\\).*")
437 "Matches the DEADLINE keyword and the rest of the line.")
439 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
440 "Matches the SCHEDULED keyword.")
442 (defconst org-scheduled-time-regexp
443 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
444 "Matches the SCHEDULED keyword together with a time stamp.")
446 (defconst org-scheduled-time-hour-regexp
447 (concat "\\<" org-scheduled-string
448 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
449 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
451 (defconst org-closed-time-regexp
452 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
453 "Matches the CLOSED keyword together with a time stamp.")
455 (defconst org-keyword-time-regexp
456 (concat "\\<"
457 (regexp-opt
458 (list org-scheduled-string org-deadline-string org-closed-string
459 org-clock-string)
461 " *[[<]\\([^]>]+\\)[]>]")
462 "Matches any of the 4 keywords, together with the time stamp.")
464 (defconst org-keyword-time-not-clock-regexp
465 (concat
466 "\\<"
467 (regexp-opt
468 (list org-scheduled-string org-deadline-string org-closed-string) t)
469 " *[[<]\\([^]>]+\\)[]>]")
470 "Matches any of the 3 keywords, together with the time stamp.")
472 (defconst org-maybe-keyword-time-regexp
473 (concat "\\(\\<"
474 (regexp-opt
475 (list org-scheduled-string org-deadline-string org-closed-string
476 org-clock-string)
478 "\\)?"
479 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
480 "\\|"
481 "<%%([^\r\n>]*>\\)")
482 "Matches a timestamp, possibly preceded by a keyword.")
484 (defconst org-all-time-keywords
485 (mapcar (lambda (w) (substring w 0 -1))
486 (list org-scheduled-string org-deadline-string
487 org-clock-string org-closed-string))
488 "List of time keywords.")
490 ;;;; Drawer
492 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
493 "Matches first or last line of a hidden block.
494 Group 1 contains drawer's name or \"END\".")
496 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
497 "Regular expression matching the first line of a property drawer.")
499 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
500 "Regular expression matching the last line of a property drawer.")
502 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
503 "Regular expression matching the first line of a clock drawer.")
505 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
506 "Regular expression matching the last line of a clock drawer.")
508 (defconst org-property-drawer-re
509 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
510 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
511 "[ \t]*:END:[ \t]*$")
512 "Matches an entire property drawer.")
514 (defconst org-clock-drawer-re
515 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
516 org-clock-drawer-end-re "\\)\n?")
517 "Matches an entire clock drawer.")
519 ;;;; Headline
521 (defconst org-heading-keyword-regexp-format
522 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
523 "Printf format for a regexp matching a headline with some keyword.
524 This regexp will match the headline of any node which has the
525 exact keyword that is put into the format. The keyword isn't in
526 any group by default, but the stars and the body are.")
528 (defconst org-heading-keyword-maybe-regexp-format
529 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
530 "Printf format for a regexp matching a headline, possibly with some keyword.
531 This regexp can match any headline with the specified keyword, or
532 without a keyword. The keyword isn't in any group by default,
533 but the stars and the body are.")
535 (defconst org-archive-tag "ARCHIVE"
536 "The tag that marks a subtree as archived.
537 An archived subtree does not open during visibility cycling, and does
538 not contribute to the agenda listings.")
540 (eval-and-compile
541 (defconst org-comment-string "COMMENT"
542 "Entries starting with this keyword will never be exported.
543 \\<org-mode-map>
544 An entry can be toggled between COMMENT and normal with
545 `\\[org-toggle-comment]'."))
548 ;;;; LaTeX Environments and Fragments
550 (defconst org-latex-regexps
551 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
552 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
553 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
554 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
555 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
556 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
557 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
558 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
559 "Regular expressions for matching embedded LaTeX.")
561 ;;;; Node Property
563 (defconst org-effort-property "Effort"
564 "The property that is being used to keep track of effort estimates.
565 Effort estimates given in this property need to have the format H:MM.")
567 ;;;; Table
569 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
570 "Detect an org-type or table-type table.")
572 (defconst org-table-line-regexp "^[ \t]*|"
573 "Detect an org-type table line.")
575 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
576 "Detect an org-type table line.")
578 (defconst org-table-hline-regexp "^[ \t]*|-"
579 "Detect an org-type table hline.")
581 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
582 "Detect a table-type table hline.")
584 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
585 "Detect the first line outside a table when searching from within it.
586 This works for both table types.")
588 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
589 "Detect a #+TBLFM line.")
591 ;;;; Timestamp
593 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
594 "Regular expression for fast time stamp matching.")
596 (defconst org-ts-regexp-inactive
597 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
598 "Regular expression for fast inactive time stamp matching.")
600 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
601 "Regular expression for fast time stamp matching.")
603 (defconst org-ts-regexp0
604 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
605 "Regular expression matching time strings for analysis.
606 This one does not require the space after the date, so it can be used
607 on a string that terminates immediately after the date.")
609 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
610 "Regular expression matching time strings for analysis.")
612 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
613 "Regular expression matching time stamps, with groups.")
615 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
616 "Regular expression matching time stamps (also [..]), with groups.")
618 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tr-regexp-both
622 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
623 "Regular expression matching a time stamp range.")
625 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
626 org-ts-regexp "\\)?")
627 "Regular expression matching a time stamp or time stamp range.")
629 (defconst org-tsr-regexp-both
630 (concat org-ts-regexp-both "\\(--?-?"
631 org-ts-regexp-both "\\)?")
632 "Regular expression matching a time stamp or time stamp range.
633 The time stamps may be either active or inactive.")
635 (defconst org-repeat-re
636 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
637 "Regular expression for specifying repeated events.
638 After a match, group 1 contains the repeat expression.")
640 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
641 "Formats for `format-time-string' which are used for time stamps.")
644 ;;; The custom variables
646 (defgroup org nil
647 "Outline-based notes management and organizer."
648 :tag "Org"
649 :group 'outlines
650 :group 'calendar)
652 (defcustom org-mode-hook nil
653 "Mode hook for Org mode, run after the mode was turned on."
654 :group 'org
655 :type 'hook)
657 (defcustom org-load-hook nil
658 "Hook that is run after org.el has been loaded."
659 :group 'org
660 :type 'hook)
662 (defcustom org-log-buffer-setup-hook nil
663 "Hook that is run after an Org log buffer is created."
664 :group 'org
665 :version "24.1"
666 :type 'hook)
668 (defvar org-modules) ; defined below
669 (defvar org-modules-loaded nil
670 "Have the modules been loaded already?")
672 (defun org-load-modules-maybe (&optional force)
673 "Load all extensions listed in `org-modules'."
674 (when (or force (not org-modules-loaded))
675 (dolist (ext org-modules)
676 (condition-case nil (require ext)
677 (error (message "Problems while trying to load feature `%s'" ext))))
678 (setq org-modules-loaded t)))
680 (defun org-set-modules (var value)
681 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
682 (set var value)
683 (when (featurep 'org)
684 (org-load-modules-maybe 'force)
685 (org-element-cache-reset 'all)))
687 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
688 "Modules that should always be loaded together with org.el.
690 If a description starts with <C>, the file is not part of Emacs
691 and loading it will require that you have downloaded and properly
692 installed the Org mode distribution.
694 You can also use this system to load external packages (i.e. neither Org
695 core modules, nor modules from the CONTRIB directory). Just add symbols
696 to the end of the list. If the package is called org-xyz.el, then you need
697 to add the symbol `xyz', and the package must have a call to:
699 (provide \\='org-xyz)
701 For export specific modules, see also `org-export-backends'."
702 :group 'org
703 :set 'org-set-modules
704 :version "24.4"
705 :package-version '(Org . "8.0")
706 :type
707 '(set :greedy t
708 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
709 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
710 (const :tag " crypt: Encryption of subtrees" org-crypt)
711 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
712 (const :tag " docview: Links to doc-view buffers" org-docview)
713 (const :tag " eww: Store link to url of eww" org-eww)
714 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
715 (const :tag " habit: Track your consistency with habits" org-habit)
716 (const :tag " id: Global IDs for identifying entries" org-id)
717 (const :tag " info: Links to Info nodes" org-info)
718 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
719 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
720 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
721 (const :tag " mouse: Additional mouse support" org-mouse)
722 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
723 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
724 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
726 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
727 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
728 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
729 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
730 (const :tag "C collector: Collect properties into tables" org-collector)
731 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
732 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
733 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
734 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
735 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
736 (const :tag "C eval: Include command output as text" org-eval)
737 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
738 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
739 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
740 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
741 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
742 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
743 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
744 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
745 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
746 (const :tag "C man: Support for links to manpages in Org mode" org-man)
747 (const :tag "C mew: Links to Mew folders/messages" org-mew)
748 (const :tag "C mtags: Support for muse-like tags" org-mtags)
749 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
750 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
751 (const :tag "C registry: A registry for Org links" org-registry)
752 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
753 (const :tag "C secretary: Team management with org-mode" org-secretary)
754 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
755 (const :tag "C toc: Table of contents for Org buffer" org-toc)
756 (const :tag "C track: Keep up with Org mode development" org-track)
757 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
758 (const :tag "C vm: Links to VM folders/messages" org-vm)
759 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
760 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
761 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
763 (defvar org-export-registered-backends) ; From ox.el.
764 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
765 (declare-function org-export-backend-name "ox" (backend) t)
766 (defcustom org-export-backends '(ascii html icalendar latex odt)
767 "List of export back-ends that should be always available.
769 If a description starts with <C>, the file is not part of Emacs
770 and loading it will require that you have downloaded and properly
771 installed the Org mode distribution.
773 Unlike to `org-modules', libraries in this list will not be
774 loaded along with Org, but only once the export framework is
775 needed.
777 This variable needs to be set before org.el is loaded. If you
778 need to make a change while Emacs is running, use the customize
779 interface or run the following code, where VAL stands for the new
780 value of the variable, after updating it:
782 (progn
783 (setq org-export-registered-backends
784 (cl-remove-if-not
785 (lambda (backend)
786 (let ((name (org-export-backend-name backend)))
787 (or (memq name val)
788 (catch \\='parentp
789 (dolist (b val)
790 (and (org-export-derived-backend-p b name)
791 (throw \\='parentp t)))))))
792 org-export-registered-backends))
793 (let ((new-list (mapcar #\\='org-export-backend-name
794 org-export-registered-backends)))
795 (dolist (backend val)
796 (cond
797 ((not (load (format \"ox-%s\" backend) t t))
798 (message \"Problems while trying to load export back-end \\=`%s\\='\"
799 backend))
800 ((not (memq backend new-list)) (push backend new-list))))
801 (set-default \\='org-export-backends new-list)))
803 Adding a back-end to this list will also pull the back-end it
804 depends on, if any."
805 :group 'org
806 :group 'org-export
807 :version "26.1"
808 :package-version '(Org . "9.0")
809 :initialize 'custom-initialize-set
810 :set (lambda (var val)
811 (if (not (featurep 'ox)) (set-default var val)
812 ;; Any back-end not required anymore (not present in VAL and not
813 ;; a parent of any back-end in the new value) is removed from the
814 ;; list of registered back-ends.
815 (setq org-export-registered-backends
816 (cl-remove-if-not
817 (lambda (backend)
818 (let ((name (org-export-backend-name backend)))
819 (or (memq name val)
820 (catch 'parentp
821 (dolist (b val)
822 (and (org-export-derived-backend-p b name)
823 (throw 'parentp t)))))))
824 org-export-registered-backends))
825 ;; Now build NEW-LIST of both new back-ends and required
826 ;; parents.
827 (let ((new-list (mapcar #'org-export-backend-name
828 org-export-registered-backends)))
829 (dolist (backend val)
830 (cond
831 ((not (load (format "ox-%s" backend) t t))
832 (message "Problems while trying to load export back-end `%s'"
833 backend))
834 ((not (memq backend new-list)) (push backend new-list))))
835 ;; Set VAR to that list with fixed dependencies.
836 (set-default var new-list))))
837 :type '(set :greedy t
838 (const :tag " ascii Export buffer to ASCII format" ascii)
839 (const :tag " beamer Export buffer to Beamer presentation" beamer)
840 (const :tag " html Export buffer to HTML format" html)
841 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
842 (const :tag " latex Export buffer to LaTeX format" latex)
843 (const :tag " man Export buffer to MAN format" man)
844 (const :tag " md Export buffer to Markdown format" md)
845 (const :tag " odt Export buffer to ODT format" odt)
846 (const :tag " org Export buffer to Org format" org)
847 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
848 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
849 (const :tag "C deck Export buffer to deck.js presentations" deck)
850 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
851 (const :tag "C groff Export buffer to Groff format" groff)
852 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
853 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
854 (const :tag "C s5 Export buffer to s5 presentations" s5)
855 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
857 (eval-after-load 'ox
858 '(dolist (backend org-export-backends)
859 (condition-case nil (require (intern (format "ox-%s" backend)))
860 (error (message "Problems while trying to load export back-end `%s'"
861 backend)))))
863 (defcustom org-support-shift-select nil
864 "Non-nil means make shift-cursor commands select text when possible.
865 \\<org-mode-map>\
867 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
868 start selecting a region, or enlarge regions started in this way.
869 In Org mode, in special contexts, these same keys are used for
870 other purposes, important enough to compete with shift selection.
871 Org tries to balance these needs by supporting `shift-select-mode'
872 outside these special contexts, under control of this variable.
874 The default of this variable is nil, to avoid confusing behavior. Shifted
875 cursor keys will then execute Org commands in the following contexts:
876 - on a headline, changing TODO state (left/right) and priority (up/down)
877 - on a time stamp, changing the time
878 - in a plain list item, changing the bullet type
879 - in a property definition line, switching between allowed values
880 - in the BEGIN line of a clock table (changing the time block).
881 Outside these contexts, the commands will throw an error.
883 When this variable is t and the cursor is not in a special
884 context, Org mode will support shift-selection for making and
885 enlarging regions. To make this more effective, the bullet
886 cycling will no longer happen anywhere in an item line, but only
887 if the cursor is exactly on the bullet.
889 If you set this variable to the symbol `always', then the keys
890 will not be special in headlines, property lines, and item lines,
891 to make shift selection work there as well. If this is what you
892 want, you can use the following alternative commands:
893 `\\[org-todo]' and `\\[org-priority]' \
894 to change TODO state and priority,
895 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
896 can be used to switch TODO sets,
897 `\\[org-ctrl-c-minus]' to cycle item bullet types,
898 and properties can be edited by hand or in column view.
900 However, when the cursor is on a timestamp, shift-cursor commands
901 will still edit the time stamp - this is just too good to give up."
902 :group 'org
903 :type '(choice
904 (const :tag "Never" nil)
905 (const :tag "When outside special context" t)
906 (const :tag "Everywhere except timestamps" always)))
908 (defcustom org-loop-over-headlines-in-active-region nil
909 "Shall some commands act upon headlines in the active region?
911 When set to t, some commands will be performed in all headlines
912 within the active region.
914 When set to `start-level', some commands will be performed in all
915 headlines within the active region, provided that these headlines
916 are of the same level than the first one.
918 When set to a string, those commands will be performed on the
919 matching headlines within the active region. Such string must be
920 a tags/property/todo match as it is used in the agenda tags view.
922 The list of commands is: `org-schedule', `org-deadline',
923 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
924 `org-archive-to-archive-sibling'. The archiving commands skip
925 already archived entries."
926 :type '(choice (const :tag "Don't loop" nil)
927 (const :tag "All headlines in active region" t)
928 (const :tag "In active region, headlines at the same level than the first one" start-level)
929 (string :tag "Tags/Property/Todo matcher"))
930 :version "24.1"
931 :group 'org-todo
932 :group 'org-archive)
934 (defgroup org-startup nil
935 "Options concerning startup of Org mode."
936 :tag "Org Startup"
937 :group 'org)
939 (defcustom org-startup-folded t
940 "Non-nil means entering Org mode will switch to OVERVIEW.
942 This can also be configured on a per-file basis by adding one of
943 the following lines anywhere in the buffer:
945 #+STARTUP: fold (or `overview', this is equivalent)
946 #+STARTUP: nofold (or `showall', this is equivalent)
947 #+STARTUP: content
948 #+STARTUP: showeverything
950 Set `org-agenda-inhibit-startup' to a non-nil value if you want
951 to ignore this option when Org opens agenda files for the first
952 time."
953 :group 'org-startup
954 :type '(choice
955 (const :tag "nofold: show all" nil)
956 (const :tag "fold: overview" t)
957 (const :tag "content: all headlines" content)
958 (const :tag "show everything, even drawers" showeverything)))
960 (defcustom org-startup-truncated t
961 "Non-nil means entering Org mode will set `truncate-lines'.
962 This is useful since some lines containing links can be very long and
963 uninteresting. Also tables look terrible when wrapped.
965 The variable `org-startup-truncated' allows to configure
966 truncation for Org mode different to the other modes that use the
967 variable `truncate-lines' and as a shortcut instead of putting
968 the variable `truncate-lines' into the `org-mode-hook'. If one
969 wants to configure truncation for Org mode not statically but
970 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
971 the variable `truncate-lines' has to be used because in such a
972 case it is too late to set the variable `org-startup-truncated'."
973 :group 'org-startup
974 :type 'boolean)
976 (defcustom org-startup-indented nil
977 "Non-nil means turn on `org-indent-mode' on startup.
978 This can also be configured on a per-file basis by adding one of
979 the following lines anywhere in the buffer:
981 #+STARTUP: indent
982 #+STARTUP: noindent"
983 :group 'org-structure
984 :type '(choice
985 (const :tag "Not" nil)
986 (const :tag "Globally (slow on startup in large files)" t)))
988 (defcustom org-use-sub-superscripts t
989 "Non-nil means interpret \"_\" and \"^\" for display.
991 If you want to control how Org exports those characters, see
992 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
993 used to be an alias for `org-export-with-sub-superscripts' in
994 Org <8.0, it is not anymore.
996 When this option is turned on, you can use TeX-like syntax for
997 sub- and superscripts within the buffer. Several characters after
998 \"_\" or \"^\" will be considered as a single item - so grouping
999 with {} is normally not needed. For example, the following things
1000 will be parsed as single sub- or superscripts:
1002 10^24 or 10^tau several digits will be considered 1 item.
1003 10^-12 or 10^-tau a leading sign with digits or a word
1004 x^2-y^3 will be read as x^2 - y^3, because items are
1005 terminated by almost any nonword/nondigit char.
1006 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1008 Still, ambiguity is possible. So when in doubt, use {} to enclose
1009 the sub/superscript. If you set this variable to the symbol `{}',
1010 the braces are *required* in order to trigger interpretations as
1011 sub/superscript. This can be helpful in documents that need \"_\"
1012 frequently in plain text."
1013 :group 'org-startup
1014 :version "24.4"
1015 :package-version '(Org . "8.0")
1016 :type '(choice
1017 (const :tag "Always interpret" t)
1018 (const :tag "Only with braces" {})
1019 (const :tag "Never interpret" nil)))
1021 (defcustom org-startup-with-beamer-mode nil
1022 "Non-nil means turn on `org-beamer-mode' on startup.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1026 #+STARTUP: beamer"
1027 :group 'org-startup
1028 :version "24.1"
1029 :type 'boolean)
1031 (defcustom org-startup-align-all-tables nil
1032 "Non-nil means align all tables when visiting a file.
1033 This 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-shrink-all-tables nil
1041 "Non-nil means shrink all table columns with a width cookie.
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: shrink"
1045 :group 'org-startup
1046 :type 'boolean
1047 :version "26.1"
1048 :package-version '(Org . "9.1")
1049 :safe #'booleanp)
1051 (defcustom org-startup-with-inline-images nil
1052 "Non-nil means show inline images 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: inlineimages
1056 #+STARTUP: noinlineimages"
1057 :group 'org-startup
1058 :version "24.1"
1059 :type 'boolean)
1061 (defcustom org-startup-with-latex-preview nil
1062 "Non-nil means preview LaTeX fragments when loading a new Org file.
1064 This can also be configured on a per-file basis by adding one of
1065 the following lines anywhere in the buffer:
1066 #+STARTUP: latexpreview
1067 #+STARTUP: nolatexpreview"
1068 :group 'org-startup
1069 :version "24.4"
1070 :package-version '(Org . "8.0")
1071 :type 'boolean)
1073 (defcustom org-insert-mode-line-in-empty-file nil
1074 "Non-nil means insert the first line setting Org mode in empty files.
1075 When the function `org-mode' is called interactively in an empty file, this
1076 normally means that the file name does not automatically trigger Org mode.
1077 To ensure that the file will always be in Org mode in the future, a
1078 line enforcing Org mode will be inserted into the buffer, if this option
1079 has been set."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (defcustom org-replace-disputed-keys nil
1084 "Non-nil means use alternative key bindings for some keys.
1085 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1086 These keys are also used by other packages like shift-selection-mode'
1087 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1088 If you want to use Org mode together with one of these other modes,
1089 or more generally if you would like to move some Org mode commands to
1090 other keys, set this variable and configure the keys with the variable
1091 `org-disputed-keys'.
1093 This option is only relevant at load-time of Org mode, and must be set
1094 *before* org.el is loaded. Changing it requires a restart of Emacs to
1095 become effective."
1096 :group 'org-startup
1097 :type 'boolean)
1099 (defcustom org-use-extra-keys nil
1100 "Non-nil means use extra key sequence definitions for certain commands.
1101 This happens automatically if `window-system' is nil. This
1102 variable lets you do the same manually. You must set it before
1103 loading Org."
1104 :group 'org-startup
1105 :type 'boolean)
1107 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1109 (defcustom org-disputed-keys
1110 '(([(shift up)] . [(meta p)])
1111 ([(shift down)] . [(meta n)])
1112 ([(shift left)] . [(meta -)])
1113 ([(shift right)] . [(meta +)])
1114 ([(control shift right)] . [(meta shift +)])
1115 ([(control shift left)] . [(meta shift -)]))
1116 "Keys for which Org mode and other modes compete.
1117 This is an alist, cars are the default keys, second element specifies
1118 the alternative to use when `org-replace-disputed-keys' is t.
1120 Keys can be specified in any syntax supported by `define-key'.
1121 The value of this option takes effect only at Org mode startup,
1122 therefore you'll have to restart Emacs to apply it after changing."
1123 :group 'org-startup
1124 :type 'alist)
1126 (defun org-key (key)
1127 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1128 Or return the original if not disputed."
1129 (when org-replace-disputed-keys
1130 (let* ((nkey (key-description key))
1131 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1132 org-disputed-keys)))
1133 (setq key (if x (cdr x) key))))
1134 key)
1136 (defun org-defkey (keymap key def)
1137 "Define a key, possibly translated, as returned by `org-key'."
1138 (define-key keymap (org-key key) def))
1140 (defcustom org-ellipsis nil
1141 "The ellipsis to use in the Org mode outline.
1143 When nil, just use the standard three dots. When a non-empty string,
1144 use that string instead.
1146 The change affects only Org mode (which will then use its own display table).
1147 Changing this requires executing `\\[org-mode]' in a buffer to become
1148 effective."
1149 :group 'org-startup
1150 :type '(choice (const :tag "Default" nil)
1151 (string :tag "String" :value "...#"))
1152 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1154 (defvar org-display-table nil
1155 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1157 (defgroup org-keywords nil
1158 "Keywords in Org mode."
1159 :tag "Org Keywords"
1160 :group 'org)
1162 (defcustom org-closed-keep-when-no-todo nil
1163 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1164 :group 'org-todo
1165 :group 'org-keywords
1166 :version "24.4"
1167 :package-version '(Org . "8.0")
1168 :type 'boolean)
1170 (defgroup org-structure nil
1171 "Options concerning the general structure of Org files."
1172 :tag "Org Structure"
1173 :group 'org)
1175 (defgroup org-reveal-location nil
1176 "Options about how to make context of a location visible."
1177 :tag "Org Reveal Location"
1178 :group 'org-structure)
1180 (defcustom org-show-context-detail '((agenda . local)
1181 (bookmark-jump . lineage)
1182 (isearch . lineage)
1183 (default . ancestors))
1184 "Alist between context and visibility span when revealing a location.
1186 \\<org-mode-map>Some actions may move point into invisible
1187 locations. As a consequence, Org always expose a neighborhood
1188 around point. How much is shown depends on the initial action,
1189 or context. Valid contexts are
1191 agenda when exposing an entry from the agenda
1192 org-goto when using the command `org-goto' (`\\[org-goto]')
1193 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1194 tags-tree when constructing a sparse tree based on tags matches
1195 link-search when exposing search matches associated with a link
1196 mark-goto when exposing the jump goal of a mark
1197 bookmark-jump when exposing a bookmark location
1198 isearch when exiting from an incremental search
1199 default default for all contexts not set explicitly
1201 Allowed visibility spans are
1203 minimal show current headline; if point is not on headline,
1204 also show entry
1206 local show current headline, entry and next headline
1208 ancestors show current headline and its direct ancestors; if
1209 point is not on headline, also show entry
1211 lineage show current headline, its direct ancestors and all
1212 their children; if point is not on headline, also show
1213 entry and first child
1215 tree show current headline, its direct ancestors and all
1216 their children; if point is not on headline, also show
1217 entry and all children
1219 canonical show current headline, its direct ancestors along with
1220 their entries and children; if point is not located on
1221 the headline, also show current entry and all children
1223 As special cases, a nil or t value means show all contexts in
1224 `minimal' or `canonical' view, respectively.
1226 Some views can make displayed information very compact, but also
1227 make it harder to edit the location of the match. In such
1228 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1229 more context."
1230 :group 'org-reveal-location
1231 :version "26.1"
1232 :package-version '(Org . "9.0")
1233 :type '(choice
1234 (const :tag "Canonical" t)
1235 (const :tag "Minimal" nil)
1236 (repeat :greedy t :tag "Individual contexts"
1237 (cons
1238 (choice :tag "Context"
1239 (const agenda)
1240 (const org-goto)
1241 (const occur-tree)
1242 (const tags-tree)
1243 (const link-search)
1244 (const mark-goto)
1245 (const bookmark-jump)
1246 (const isearch)
1247 (const default))
1248 (choice :tag "Detail level"
1249 (const minimal)
1250 (const local)
1251 (const ancestors)
1252 (const lineage)
1253 (const tree)
1254 (const canonical))))))
1256 (defcustom org-indirect-buffer-display 'other-window
1257 "How should indirect tree buffers be displayed?
1259 This applies to indirect buffers created with the commands
1260 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1262 Valid values are:
1263 current-window Display in the current window
1264 other-window Just display in another window.
1265 dedicated-frame Create one new frame, and re-use it each time.
1266 new-frame Make a new frame each time. Note that in this case
1267 previously-made indirect buffers are kept, and you need to
1268 kill these buffers yourself."
1269 :group 'org-structure
1270 :group 'org-agenda-windows
1271 :type '(choice
1272 (const :tag "In current window" current-window)
1273 (const :tag "In current frame, other window" other-window)
1274 (const :tag "Each time a new frame" new-frame)
1275 (const :tag "One dedicated frame" dedicated-frame)))
1277 (defcustom org-use-speed-commands nil
1278 "Non-nil means activate single letter commands at beginning of a headline.
1279 This may also be a function to test for appropriate locations where speed
1280 commands should be active.
1282 For example, to activate speed commands when the point is on any
1283 star at the beginning of the headline, you can do this:
1285 (setq org-use-speed-commands
1286 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1287 :group 'org-structure
1288 :type '(choice
1289 (const :tag "Never" nil)
1290 (const :tag "At beginning of headline stars" t)
1291 (function)))
1293 (defcustom org-speed-commands-user nil
1294 "Alist of additional speed commands.
1295 This list will be checked before `org-speed-commands-default'
1296 when the variable `org-use-speed-commands' is non-nil
1297 and when the cursor is at the beginning of a headline.
1298 The car if each entry is a string with a single letter, which must
1299 be assigned to `self-insert-command' in the global map.
1300 The cdr is either a command to be called interactively, a function
1301 to be called, or a form to be evaluated.
1302 An entry that is just a list with a single string will be interpreted
1303 as a descriptive headline that will be added when listing the speed
1304 commands in the Help buffer using the `?' speed command."
1305 :group 'org-structure
1306 :type '(repeat :value ("k" . ignore)
1307 (choice :value ("k" . ignore)
1308 (list :tag "Descriptive Headline" (string :tag "Headline"))
1309 (cons :tag "Letter and Command"
1310 (string :tag "Command letter")
1311 (choice
1312 (function)
1313 (sexp))))))
1315 (defcustom org-bookmark-names-plist
1316 '(:last-capture "org-capture-last-stored"
1317 :last-refile "org-refile-last-stored"
1318 :last-capture-marker "org-capture-last-stored-marker")
1319 "Names for bookmarks automatically set by some Org commands.
1320 This can provide strings as names for a number of bookmarks Org sets
1321 automatically. The following keys are currently implemented:
1322 :last-capture
1323 :last-capture-marker
1324 :last-refile
1325 When a key does not show up in the property list, the corresponding bookmark
1326 is not set."
1327 :group 'org-structure
1328 :type 'plist)
1330 (defgroup org-cycle nil
1331 "Options concerning visibility cycling in Org mode."
1332 :tag "Org Cycle"
1333 :group 'org-structure)
1335 (defcustom org-cycle-skip-children-state-if-no-children t
1336 "Non-nil means skip CHILDREN state in entries that don't have any."
1337 :group 'org-cycle
1338 :type 'boolean)
1340 (defcustom org-cycle-max-level nil
1341 "Maximum level which should still be subject to visibility cycling.
1342 Levels higher than this will, for cycling, be treated as text, not a headline.
1343 When `org-odd-levels-only' is set, a value of N in this variable actually
1344 means 2N-1 stars as the limiting headline.
1345 When nil, cycle all levels.
1346 Note that the limiting level of cycling is also influenced by
1347 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1348 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1349 than its value."
1350 :group 'org-cycle
1351 :type '(choice
1352 (const :tag "No limit" nil)
1353 (integer :tag "Maximum level")))
1355 (defcustom org-hide-block-startup nil
1356 "Non-nil means entering Org mode will fold all blocks.
1357 This can also be set in on a per-file basis with
1359 #+STARTUP: hideblocks
1360 #+STARTUP: showblocks"
1361 :group 'org-startup
1362 :group 'org-cycle
1363 :type 'boolean)
1365 (defcustom org-cycle-global-at-bob nil
1366 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1368 This makes it possible to do global cycling without having to use `S-TAB'
1369 or `\\[universal-argument] TAB'. For this special case to work, the first \
1370 line of the buffer
1371 must not be a headline -- it may be empty or some other text.
1373 When used in this way, `org-cycle-hook' is disabled temporarily to make
1374 sure the cursor stays at the beginning of the buffer.
1376 When this option is nil, don't do anything special at the beginning of
1377 the buffer."
1378 :group 'org-cycle
1379 :type 'boolean)
1381 (defcustom org-cycle-level-after-item/entry-creation t
1382 "Non-nil means cycle entry level or item indentation in new empty entries.
1384 When the cursor is at the end of an empty headline, i.e., with only stars
1385 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1386 and then all possible ancestor states, before returning to the original state.
1387 This makes data entry extremely fast: M-RET to create a new headline,
1388 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1390 When the cursor is at the end of an empty plain list item, one TAB will
1391 make it a subitem, two or more tabs will back up to make this an item
1392 higher up in the item hierarchy."
1393 :group 'org-cycle
1394 :type 'boolean)
1396 (defcustom org-cycle-emulate-tab t
1397 "Where should `org-cycle' emulate TAB.
1398 nil Never
1399 white Only in completely white lines
1400 whitestart Only at the beginning of lines, before the first non-white char
1401 t Everywhere except in headlines
1402 exc-hl-bol Everywhere except at the start of a headline
1403 If TAB is used in a place where it does not emulate TAB, the current subtree
1404 visibility is cycled."
1405 :group 'org-cycle
1406 :type '(choice (const :tag "Never" nil)
1407 (const :tag "Only in completely white lines" white)
1408 (const :tag "Before first char in a line" whitestart)
1409 (const :tag "Everywhere except in headlines" t)
1410 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1412 (defcustom org-cycle-separator-lines 2
1413 "Number of empty lines needed to keep an empty line between collapsed trees.
1414 If you leave an empty line between the end of a subtree and the following
1415 headline, this empty line is hidden when the subtree is folded.
1416 Org mode will leave (exactly) one empty line visible if the number of
1417 empty lines is equal or larger to the number given in this variable.
1418 So the default 2 means at least 2 empty lines after the end of a subtree
1419 are needed to produce free space between a collapsed subtree and the
1420 following headline.
1422 If the number is negative, and the number of empty lines is at least -N,
1423 all empty lines are shown.
1425 Special case: when 0, never leave empty lines in collapsed view."
1426 :group 'org-cycle
1427 :type 'integer)
1428 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1430 (defcustom org-pre-cycle-hook nil
1431 "Hook that is run before visibility cycling is happening.
1432 The function(s) in this hook must accept a single argument which indicates
1433 the new state that will be set right after running this hook. The
1434 argument is a symbol. Before a global state change, it can have the values
1435 `overview', `content', or `all'. Before a local state change, it can have
1436 the values `folded', `children', or `subtree'."
1437 :group 'org-cycle
1438 :type 'hook)
1440 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1441 org-cycle-hide-drawers
1442 org-cycle-show-empty-lines
1443 org-optimize-window-after-visibility-change)
1444 "Hook that is run after `org-cycle' has changed the buffer visibility.
1445 The function(s) in this hook must accept a single argument which indicates
1446 the new state that was set by the most recent `org-cycle' command. The
1447 argument is a symbol. After a global state change, it can have the values
1448 `overview', `contents', or `all'. After a local state change, it can have
1449 the values `folded', `children', or `subtree'."
1450 :group 'org-cycle
1451 :type 'hook
1452 :version "26.1"
1453 :package-version '(Org . "8.3"))
1455 (defgroup org-edit-structure nil
1456 "Options concerning structure editing in Org mode."
1457 :tag "Org Edit Structure"
1458 :group 'org-structure)
1460 (defcustom org-odd-levels-only nil
1461 "Non-nil means skip even levels and only use odd levels for the outline.
1462 This has the effect that two stars are being added/taken away in
1463 promotion/demotion commands. It also influences how levels are
1464 handled by the exporters.
1465 Changing it requires restart of `font-lock-mode' to become effective
1466 for fontification also in regions already fontified.
1467 You may also set this on a per-file basis by adding one of the following
1468 lines to the buffer:
1470 #+STARTUP: odd
1471 #+STARTUP: oddeven"
1472 :group 'org-edit-structure
1473 :group 'org-appearance
1474 :type 'boolean)
1476 (defcustom org-adapt-indentation t
1477 "Non-nil means adapt indentation to outline node level.
1479 When this variable is set, Org assumes that you write outlines by
1480 indenting text in each node to align with the headline (after the
1481 stars). The following issues are influenced by this variable:
1483 - The indentation is increased by one space in a demotion
1484 command, and decreased by one in a promotion command. However,
1485 in the latter case, if shifting some line in the entry body
1486 would alter document structure (e.g., insert a new headline),
1487 indentation is not changed at all.
1489 - Property drawers and planning information is inserted indented
1490 when this variable is set. When nil, they will not be indented.
1492 - TAB indents a line relative to current level. The lines below
1493 a headline will be indented when this variable is set.
1495 Note that this is all about true indentation, by adding and
1496 removing space characters. See also `org-indent.el' which does
1497 level-dependent indentation in a virtual way, i.e. at display
1498 time in Emacs."
1499 :group 'org-edit-structure
1500 :type 'boolean)
1502 (defcustom org-special-ctrl-a/e nil
1503 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1505 When t, `C-a' will bring back the cursor to the beginning of the
1506 headline text, i.e. after the stars and after a possible TODO
1507 keyword. In an item, this will be the position after bullet and
1508 check-box, if any. When the cursor is already at that position,
1509 another `C-a' will bring it to the beginning of the line.
1511 `C-e' will jump to the end of the headline, ignoring the presence
1512 of tags in the headline. A second `C-e' will then jump to the
1513 true end of the line, after any tags. This also means that, when
1514 this variable is non-nil, `C-e' also will never jump beyond the
1515 end of the heading of a folded section, i.e. not after the
1516 ellipses.
1518 When set to the symbol `reversed', the first `C-a' or `C-e' works
1519 normally, going to the true line boundary first. Only a directly
1520 following, identical keypress will bring the cursor to the
1521 special positions.
1523 This may also be a cons cell where the behavior for `C-a' and
1524 `C-e' is set separately."
1525 :group 'org-edit-structure
1526 :type '(choice
1527 (const :tag "off" nil)
1528 (const :tag "on: after stars/bullet and before tags first" t)
1529 (const :tag "reversed: true line boundary first" reversed)
1530 (cons :tag "Set C-a and C-e separately"
1531 (choice :tag "Special C-a"
1532 (const :tag "off" nil)
1533 (const :tag "on: after stars/bullet first" t)
1534 (const :tag "reversed: before stars/bullet first" reversed))
1535 (choice :tag "Special C-e"
1536 (const :tag "off" nil)
1537 (const :tag "on: before tags first" t)
1538 (const :tag "reversed: after tags first" reversed)))))
1539 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1541 (defcustom org-special-ctrl-k nil
1542 "Non-nil means `C-k' will behave specially in headlines.
1543 When nil, `C-k' will call the default `kill-line' command.
1544 When t, the following will happen while the cursor is in the headline:
1546 - When the cursor is at the beginning of a headline, kill the entire
1547 line and possible the folded subtree below the line.
1548 - When in the middle of the headline text, kill the headline up to the tags.
1549 - When after the headline text, kill the tags."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-ctrl-k-protect-subtree nil
1554 "Non-nil means, do not delete a hidden subtree with C-k.
1555 When set to the symbol `error', simply throw an error when C-k is
1556 used to kill (part-of) a headline that has hidden text behind it.
1557 Any other non-nil value will result in a query to the user, if it is
1558 OK to kill that hidden subtree. When nil, kill without remorse."
1559 :group 'org-edit-structure
1560 :version "24.1"
1561 :type '(choice
1562 (const :tag "Do not protect hidden subtrees" nil)
1563 (const :tag "Protect hidden subtrees with a security query" t)
1564 (const :tag "Never kill a hidden subtree with C-k" error)))
1566 (defcustom org-special-ctrl-o t
1567 "Non-nil means, make `C-o' insert a row in tables."
1568 :group 'org-edit-structure
1569 :type 'boolean)
1571 (defcustom org-catch-invisible-edits nil
1572 "Check if in invisible region before inserting or deleting a character.
1573 Valid values are:
1575 nil Do not check, so just do invisible edits.
1576 error Throw an error and do nothing.
1577 show Make point visible, and do the requested edit.
1578 show-and-error Make point visible, then throw an error and abort the edit.
1579 smart Make point visible, and do insertion/deletion if it is
1580 adjacent to visible text and the change feels predictable.
1581 Never delete a previously invisible character or add in the
1582 middle or right after an invisible region. Basically, this
1583 allows insertion and backward-delete right before ellipses.
1584 FIXME: maybe in this case we should not even show?"
1585 :group 'org-edit-structure
1586 :version "24.1"
1587 :type '(choice
1588 (const :tag "Do not check" nil)
1589 (const :tag "Throw error when trying to edit" error)
1590 (const :tag "Unhide, but do not do the edit" show-and-error)
1591 (const :tag "Show invisible part and do the edit" show)
1592 (const :tag "Be smart and do the right thing" smart)))
1594 (defcustom org-yank-folded-subtrees t
1595 "Non-nil means when yanking subtrees, fold them.
1596 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1597 it starts with a heading and all other headings in it are either children
1598 or siblings, then fold all the subtrees. However, do this only if no
1599 text after the yank would be swallowed into a folded tree by this action."
1600 :group 'org-edit-structure
1601 :type 'boolean)
1603 (defcustom org-yank-adjusted-subtrees nil
1604 "Non-nil means when yanking subtrees, adjust the level.
1605 With this setting, `org-paste-subtree' is used to insert the subtree, see
1606 this function for details."
1607 :group 'org-edit-structure
1608 :type 'boolean)
1610 (defcustom org-M-RET-may-split-line '((default . t))
1611 "Non-nil means M-RET will split the line at the cursor position.
1612 When nil, it will go to the end of the line before making a
1613 new line.
1614 You may also set this option in a different way for different
1615 contexts. Valid contexts are:
1617 headline when creating a new headline
1618 item when creating a new item
1619 table in a table field
1620 default the value to be used for all contexts not explicitly
1621 customized"
1622 :group 'org-structure
1623 :group 'org-table
1624 :type '(choice
1625 (const :tag "Always" t)
1626 (const :tag "Never" nil)
1627 (repeat :greedy t :tag "Individual contexts"
1628 (cons
1629 (choice :tag "Context"
1630 (const headline)
1631 (const item)
1632 (const table)
1633 (const default))
1634 (boolean)))))
1637 (defcustom org-insert-heading-respect-content nil
1638 "Non-nil means insert new headings after the current subtree.
1639 \\<org-mode-map>
1640 When nil, the new heading is created directly after the current line.
1641 The commands `\\[org-insert-heading-respect-content]' and \
1642 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1643 for the duration of the command."
1644 :group 'org-structure
1645 :type 'boolean)
1647 (defcustom org-blank-before-new-entry '((heading . auto)
1648 (plain-list-item . auto))
1649 "Should `org-insert-heading' leave a blank line before new heading/item?
1650 The value is an alist, with `heading' and `plain-list-item' as CAR,
1651 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1652 which case Org will look at the surrounding headings/items and try to
1653 make an intelligent decision whether to insert a blank line or not."
1654 :group 'org-edit-structure
1655 :type '(list
1656 (cons (const heading)
1657 (choice (const :tag "Never" nil)
1658 (const :tag "Always" t)
1659 (const :tag "Auto" auto)))
1660 (cons (const plain-list-item)
1661 (choice (const :tag "Never" nil)
1662 (const :tag "Always" t)
1663 (const :tag "Auto" auto)))))
1665 (defcustom org-insert-heading-hook nil
1666 "Hook being run after inserting a new heading."
1667 :group 'org-edit-structure
1668 :type 'hook)
1670 (defcustom org-enable-fixed-width-editor t
1671 "Non-nil means lines starting with \":\" are treated as fixed-width.
1672 This currently only means they are never auto-wrapped.
1673 When nil, such lines will be treated like ordinary lines."
1674 :group 'org-edit-structure
1675 :type 'boolean)
1677 (defcustom org-goto-auto-isearch t
1678 "Non-nil means typing characters in `org-goto' starts incremental search.
1679 When nil, you can use these keybindings to navigate the buffer:
1681 q Quit the org-goto interface
1682 n Go to the next visible heading
1683 p Go to the previous visible heading
1684 f Go one heading forward on same level
1685 b Go one heading backward on same level
1686 u Go one heading up"
1687 :group 'org-edit-structure
1688 :type 'boolean)
1690 (defgroup org-sparse-trees nil
1691 "Options concerning sparse trees in Org mode."
1692 :tag "Org Sparse Trees"
1693 :group 'org-structure)
1695 (defcustom org-highlight-sparse-tree-matches t
1696 "Non-nil means highlight all matches that define a sparse tree.
1697 The highlights will automatically disappear the next time the buffer is
1698 changed by an edit command."
1699 :group 'org-sparse-trees
1700 :type 'boolean)
1702 (defcustom org-remove-highlights-with-change t
1703 "Non-nil means any change to the buffer will remove temporary highlights.
1704 \\<org-mode-map>\
1705 Such highlights are created by `org-occur' and `org-clock-display'.
1706 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1707 to get rid of the highlights.
1708 The highlights created by `org-toggle-latex-fragment' always need
1709 `\\[org-toggle-latex-fragment]' to be removed."
1710 :group 'org-sparse-trees
1711 :group 'org-time
1712 :type 'boolean)
1714 (defcustom org-occur-case-fold-search t
1715 "Non-nil means `org-occur' should be case-insensitive.
1716 If set to `smart' the search will be case-insensitive only if it
1717 doesn't specify any upper case character."
1718 :group 'org-sparse-trees
1719 :version "26.1"
1720 :type '(choice
1721 (const :tag "Case-sensitive" nil)
1722 (const :tag "Case-insensitive" t)
1723 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1725 (defcustom org-occur-hook '(org-first-headline-recenter)
1726 "Hook that is run after `org-occur' has constructed a sparse tree.
1727 This can be used to recenter the window to show as much of the structure
1728 as possible."
1729 :group 'org-sparse-trees
1730 :type 'hook)
1732 (defgroup org-imenu-and-speedbar nil
1733 "Options concerning imenu and speedbar in Org mode."
1734 :tag "Org Imenu and Speedbar"
1735 :group 'org-structure)
1737 (defcustom org-imenu-depth 2
1738 "The maximum level for Imenu access to Org headlines.
1739 This also applied for speedbar access."
1740 :group 'org-imenu-and-speedbar
1741 :type 'integer)
1743 (defgroup org-table nil
1744 "Options concerning tables in Org mode."
1745 :tag "Org Table"
1746 :group 'org)
1748 (defcustom org-self-insert-cluster-for-undo nil
1749 "Non-nil means cluster self-insert commands for undo when possible.
1750 If this is set, then, like in the Emacs command loop, 20 consecutive
1751 characters will be undone together.
1752 This is configurable, because there is some impact on typing performance."
1753 :group 'org-table
1754 :type 'boolean)
1756 (defcustom org-table-tab-recognizes-table.el t
1757 "Non-nil means TAB will automatically notice a table.el table.
1758 When it sees such a table, it moves point into it and - if necessary -
1759 calls `table-recognize-table'."
1760 :group 'org-table-editing
1761 :type 'boolean)
1763 (defgroup org-link nil
1764 "Options concerning links in Org mode."
1765 :tag "Org Link"
1766 :group 'org)
1768 (defvar-local org-link-abbrev-alist-local nil
1769 "Buffer-local version of `org-link-abbrev-alist', which see.
1770 The value of this is taken from the #+LINK lines.")
1772 (defcustom org-link-parameters
1773 '(("doi" :follow org--open-doi-link)
1774 ("elisp" :follow org--open-elisp-link)
1775 ("file" :complete org-file-complete-link)
1776 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1777 ("help" :follow org--open-help-link)
1778 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1779 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1780 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1781 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1782 ("shell" :follow org--open-shell-link))
1783 "An alist of properties that defines all the links in Org mode.
1784 The key in each association is a string of the link type.
1785 Subsequent optional elements make up a p-list of link properties.
1787 :follow - A function that takes the link path as an argument.
1789 :export - A function that takes the link path, description and
1790 export-backend as arguments.
1792 :store - A function responsible for storing the link. See the
1793 function `org-store-link-functions'.
1795 :complete - A function that inserts a link with completion. The
1796 function takes one optional prefix arg.
1798 :face - A face for the link, or a function that returns a face.
1799 The function takes one argument which is the link path. The
1800 default face is `org-link'.
1802 :mouse-face - The mouse-face. The default is `highlight'.
1804 :display - `full' will not fold the link in descriptive
1805 display. Default is `org-link'.
1807 :help-echo - A string or function that takes (window object position)
1808 as arguments and returns a string.
1810 :keymap - A keymap that is active on the link. The default is
1811 `org-mouse-map'.
1813 :htmlize-link - A function for the htmlize-link. Defaults
1814 to (list :uri \"type:path\")
1816 :activate-func - A function to run at the end of font-lock
1817 activation. The function must accept (link-start link-end path bracketp)
1818 as arguments."
1819 :group 'org-link
1820 :type '(alist :tag "Link display parameters"
1821 :value-type plist)
1822 :version "26.1"
1823 :package-version '(Org . "9.1"))
1825 (defun org-link-get-parameter (type key)
1826 "Get TYPE link property for KEY.
1827 TYPE is a string and KEY is a plist keyword."
1828 (plist-get
1829 (cdr (assoc type org-link-parameters))
1830 key))
1832 (defun org-link-set-parameters (type &rest parameters)
1833 "Set link TYPE properties to PARAMETERS.
1834 PARAMETERS should be :key val pairs."
1835 (let ((data (assoc type org-link-parameters)))
1836 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1837 (push (cons type parameters) org-link-parameters)
1838 (org-make-link-regexps)
1839 (org-element-update-syntax))))
1841 (defun org-link-types ()
1842 "Return a list of known link types."
1843 (mapcar #'car org-link-parameters))
1845 (defcustom org-link-abbrev-alist nil
1846 "Alist of link abbreviations.
1847 The car of each element is a string, to be replaced at the start of a link.
1848 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1849 links in Org buffers can have an optional tag after a double colon, e.g.,
1851 [[linkkey:tag][description]]
1853 The `linkkey' must be a single word, starting with a letter, followed
1854 by letters, numbers, `-' or `_'.
1856 If REPLACE is a string, the tag will simply be appended to create the link.
1857 If the string contains \"%s\", the tag will be inserted there. If the string
1858 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1859 at that point (see the function `url-hexify-string'). If the string contains
1860 the specifier \"%(my-function)\", then the custom function `my-function' will
1861 be invoked: this function takes the tag as its only argument and must return
1862 a string.
1864 REPLACE may also be a function that will be called with the tag as the
1865 only argument to create the link, which should be returned as a string.
1867 See the manual for examples."
1868 :group 'org-link
1869 :type '(repeat
1870 (cons
1871 (string :tag "Protocol")
1872 (choice
1873 (string :tag "Format")
1874 (function)))))
1876 (defcustom org-descriptive-links t
1877 "Non-nil means Org will display descriptive links.
1878 E.g. [[http://orgmode.org][Org website]] will be displayed as
1879 \"Org Website\", hiding the link itself and just displaying its
1880 description. When set to nil, Org will display the full links
1881 literally.
1883 You can interactively set the value of this variable by calling
1884 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1885 :group 'org-link
1886 :type 'boolean)
1888 (defcustom org-link-file-path-type 'adaptive
1889 "How the path name in file links should be stored.
1890 Valid values are:
1892 relative Relative to the current directory, i.e. the directory of the file
1893 into which the link is being inserted.
1894 absolute Absolute path, if possible with ~ for home directory.
1895 noabbrev Absolute path, no abbreviation of home directory.
1896 adaptive Use relative path for files in the current directory and sub-
1897 directories of it. For other files, use an absolute path."
1898 :group 'org-link
1899 :type '(choice
1900 (const relative)
1901 (const absolute)
1902 (const noabbrev)
1903 (const adaptive)))
1905 (defvaralias 'org-activate-links 'org-highlight-links)
1906 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1907 "Types of links that should be highlighted in Org files.
1909 This is a list of symbols, each one of them leading to the
1910 highlighting of a certain link type.
1912 You can still open links that are not highlighted.
1914 In principle, it does not hurt to turn on highlighting for all
1915 link types. There may be a small gain when turning off unused
1916 link types. The types are:
1918 bracket The recommended [[link][description]] or [[link]] links with hiding.
1919 angle Links in angular brackets that may contain whitespace like
1920 <bbdb:Carsten Dominik>.
1921 plain Plain links in normal text, no whitespace, like http://google.com.
1922 radio Text that is matched by a radio target, see manual for details.
1923 tag Tag settings in a headline (link to tag search).
1924 date Time stamps (link to calendar).
1925 footnote Footnote labels.
1927 If you set this variable during an Emacs session, use `org-mode-restart'
1928 in the Org buffer so that the change takes effect."
1929 :group 'org-link
1930 :group 'org-appearance
1931 :type '(set :greedy t
1932 (const :tag "Double bracket links" bracket)
1933 (const :tag "Angular bracket links" angle)
1934 (const :tag "Plain text links" plain)
1935 (const :tag "Radio target matches" radio)
1936 (const :tag "Tags" tag)
1937 (const :tag "Timestamps" date)
1938 (const :tag "Footnotes" footnote)))
1940 (defcustom org-make-link-description-function nil
1941 "Function to use for generating link descriptions from links.
1942 When nil, the link location will be used. This function must take
1943 two parameters: the first one is the link, the second one is the
1944 description generated by `org-insert-link'. The function should
1945 return the description to use."
1946 :group 'org-link
1947 :type '(choice (const nil) (function)))
1949 (defgroup org-link-store nil
1950 "Options concerning storing links in Org mode."
1951 :tag "Org Store Link"
1952 :group 'org-link)
1954 (defcustom org-url-hexify-p t
1955 "When non-nil, hexify URL when creating a link."
1956 :type 'boolean
1957 :version "24.3"
1958 :group 'org-link-store)
1960 (defcustom org-email-link-description-format "Email %c: %.30s"
1961 "Format of the description part of a link to an email or usenet message.
1962 The following %-escapes will be replaced by corresponding information:
1964 %F full \"From\" field
1965 %f name, taken from \"From\" field, address if no name
1966 %T full \"To\" field
1967 %t first name in \"To\" field, address if no name
1968 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1969 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1970 %s subject
1971 %d date
1972 %m message-id.
1974 You may use normal field width specification between the % and the letter.
1975 This is for example useful to limit the length of the subject.
1977 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1978 :group 'org-link-store
1979 :type 'string)
1981 (defcustom org-from-is-user-regexp
1982 (let (r1 r2)
1983 (when (and user-mail-address (not (string= user-mail-address "")))
1984 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1985 (when (and user-full-name (not (string= user-full-name "")))
1986 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1987 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1988 "Regexp matched against the \"From:\" header of an email or usenet message.
1989 It should match if the message is from the user him/herself."
1990 :group 'org-link-store
1991 :type 'regexp)
1993 (defcustom org-context-in-file-links t
1994 "Non-nil means file links from `org-store-link' contain context.
1995 \\<org-mode-map>
1996 A search string will be added to the file name with :: as separator
1997 and used to find the context when the link is activated by the command
1998 `org-open-at-point'. When this option is t, the entire active region
1999 will be placed in the search string of the file link. If set to a
2000 positive integer, only the first n lines of context will be stored.
2002 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2003 \\[org-store-link]')
2004 negates this setting for the duration of the command."
2005 :group 'org-link-store
2006 :type '(choice boolean integer))
2008 (defcustom org-keep-stored-link-after-insertion nil
2009 "Non-nil means keep link in list for entire session.
2010 \\<org-mode-map>
2011 The command `org-store-link' adds a link pointing to the current
2012 location to an internal list. These links accumulate during a session.
2013 The command `org-insert-link' can be used to insert links into any
2014 Org file (offering completion for all stored links).
2016 When this option is nil, every link which has been inserted once using
2017 `\\[org-insert-link]' will be removed from the list, to make completing the \
2018 unused
2019 links more efficient."
2020 :group 'org-link-store
2021 :type 'boolean)
2023 (defgroup org-link-follow nil
2024 "Options concerning following links in Org mode."
2025 :tag "Org Follow Link"
2026 :group 'org-link)
2028 (defcustom org-link-translation-function nil
2029 "Function to translate links with different syntax to Org syntax.
2030 This can be used to translate links created for example by the Planner
2031 or emacs-wiki packages to Org syntax.
2032 The function must accept two parameters, a TYPE containing the link
2033 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2034 which is everything after the link protocol. It should return a cons
2035 with possibly modified values of type and path.
2036 Org contains a function for this, so if you set this variable to
2037 `org-translate-link-from-planner', you should be able follow many
2038 links created by planner."
2039 :group 'org-link-follow
2040 :type '(choice (const nil) (function)))
2042 (defcustom org-follow-link-hook nil
2043 "Hook that is run after a link has been followed."
2044 :group 'org-link-follow
2045 :type 'hook)
2047 (defcustom org-tab-follows-link nil
2048 "Non-nil means on links TAB will follow the link.
2049 Needs to be set before org.el is loaded.
2050 This really should not be used, it does not make sense, and the
2051 implementation is bad."
2052 :group 'org-link-follow
2053 :type 'boolean)
2055 (defcustom org-return-follows-link nil
2056 "Non-nil means on links RET will follow the link.
2057 In tables, the special behavior of RET has precedence."
2058 :group 'org-link-follow
2059 :type 'boolean)
2061 (defcustom org-mouse-1-follows-link
2062 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2063 "Non-nil means mouse-1 on a link will follow the link.
2064 A longer mouse click will still set point. Needs to be set
2065 before org.el is loaded."
2066 :group 'org-link-follow
2067 :version "26.1"
2068 :package-version '(Org . "8.3")
2069 :type '(choice
2070 (const :tag "A double click follows the link" double)
2071 (const :tag "Unconditionally follow the link with mouse-1" t)
2072 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2074 (defcustom org-mark-ring-length 4
2075 "Number of different positions to be recorded in the ring.
2076 Changing this requires a restart of Emacs to work correctly."
2077 :group 'org-link-follow
2078 :type 'integer)
2080 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2081 "Non-nil means internal fuzzy links can only match headlines.
2083 When nil, the a fuzzy link may point to a target or a named
2084 construct in the document. When set to the special value
2085 `query-to-create', offer to create a new headline when none
2086 matched.
2088 Spaces and statistics cookies are ignored during heading searches."
2089 :group 'org-link-follow
2090 :version "24.1"
2091 :type '(choice
2092 (const :tag "Use fuzzy text search" nil)
2093 (const :tag "Match only exact headline" t)
2094 (const :tag "Match exact headline or query to create it"
2095 query-to-create))
2096 :safe #'symbolp)
2098 (defcustom org-link-frame-setup
2099 '((vm . vm-visit-folder-other-frame)
2100 (vm-imap . vm-visit-imap-folder-other-frame)
2101 (gnus . org-gnus-no-new-news)
2102 (file . find-file-other-window)
2103 (wl . wl-other-frame))
2104 "Setup the frame configuration for following links.
2105 When following a link with Emacs, it may often be useful to display
2106 this link in another window or frame. This variable can be used to
2107 set this up for the different types of links.
2108 For VM, use any of
2109 `vm-visit-folder'
2110 `vm-visit-folder-other-window'
2111 `vm-visit-folder-other-frame'
2112 For Gnus, use any of
2113 `gnus'
2114 `gnus-other-frame'
2115 `org-gnus-no-new-news'
2116 For FILE, use any of
2117 `find-file'
2118 `find-file-other-window'
2119 `find-file-other-frame'
2120 For Wanderlust use any of
2121 `wl'
2122 `wl-other-frame'
2123 For the calendar, use the variable `calendar-setup'.
2124 For BBDB, it is currently only possible to display the matches in
2125 another window."
2126 :group 'org-link-follow
2127 :type '(list
2128 (cons (const vm)
2129 (choice
2130 (const vm-visit-folder)
2131 (const vm-visit-folder-other-window)
2132 (const vm-visit-folder-other-frame)))
2133 (cons (const vm-imap)
2134 (choice
2135 (const vm-visit-imap-folder)
2136 (const vm-visit-imap-folder-other-window)
2137 (const vm-visit-imap-folder-other-frame)))
2138 (cons (const gnus)
2139 (choice
2140 (const gnus)
2141 (const gnus-other-frame)
2142 (const org-gnus-no-new-news)))
2143 (cons (const file)
2144 (choice
2145 (const find-file)
2146 (const find-file-other-window)
2147 (const find-file-other-frame)))
2148 (cons (const wl)
2149 (choice
2150 (const wl)
2151 (const wl-other-frame)))))
2153 (defcustom org-display-internal-link-with-indirect-buffer nil
2154 "Non-nil means use indirect buffer to display infile links.
2155 Activating internal links (from one location in a file to another location
2156 in the same file) normally just jumps to the location. When the link is
2157 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2158 is displayed in
2159 another window. When this option is set, the other window actually displays
2160 an indirect buffer clone of the current buffer, to avoid any visibility
2161 changes to the current buffer."
2162 :group 'org-link-follow
2163 :type 'boolean)
2165 (defcustom org-open-non-existing-files nil
2166 "Non-nil means `org-open-file' will open non-existing files.
2167 When nil, an error will be generated.
2168 This variable applies only to external applications because they
2169 might choke on non-existing files. If the link is to a file that
2170 will be opened in Emacs, the variable is ignored."
2171 :group 'org-link-follow
2172 :type 'boolean)
2174 (defcustom org-open-directory-means-index-dot-org nil
2175 "Non-nil means a link to a directory really means to index.org.
2176 When nil, following a directory link will run dired or open a finder/explorer
2177 window on that directory."
2178 :group 'org-link-follow
2179 :type 'boolean)
2181 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2182 "Non-nil means ask for confirmation before executing shell links.
2183 Shell links can be dangerous: just think about a link
2185 [[shell:rm -rf ~/*][Google Search]]
2187 This link would show up in your Org document as \"Google Search\",
2188 but really it would remove your entire home directory.
2189 Therefore we advise against setting this variable to nil.
2190 Just change it to `y-or-n-p' if you want to confirm with a
2191 single keystroke rather than having to type \"yes\"."
2192 :group 'org-link-follow
2193 :type '(choice
2194 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2195 (const :tag "with y-or-n (faster)" y-or-n-p)
2196 (const :tag "no confirmation (dangerous)" nil)))
2197 (put 'org-confirm-shell-link-function
2198 'safe-local-variable
2199 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2201 (defcustom org-confirm-shell-link-not-regexp ""
2202 "A regexp to skip confirmation for shell links."
2203 :group 'org-link-follow
2204 :version "24.1"
2205 :type 'regexp)
2207 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2208 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2209 Elisp links can be dangerous: just think about a link
2211 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2213 This link would show up in your Org document as \"Google Search\",
2214 but really it would remove your entire home directory.
2215 Therefore we advise against setting this variable to nil.
2216 Just change it to `y-or-n-p' if you want to confirm with a
2217 single keystroke rather than having to type \"yes\"."
2218 :group 'org-link-follow
2219 :type '(choice
2220 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2221 (const :tag "with y-or-n (faster)" y-or-n-p)
2222 (const :tag "no confirmation (dangerous)" nil)))
2223 (put 'org-confirm-shell-link-function
2224 'safe-local-variable
2225 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2227 (defcustom org-confirm-elisp-link-not-regexp ""
2228 "A regexp to skip confirmation for Elisp links."
2229 :group 'org-link-follow
2230 :version "24.1"
2231 :type 'regexp)
2233 (defconst org-file-apps-defaults-gnu
2234 '((remote . emacs)
2235 (system . mailcap)
2236 (t . mailcap))
2237 "Default file applications on a UNIX or GNU/Linux system.
2238 See `org-file-apps'.")
2240 (defconst org-file-apps-defaults-macosx
2241 '((remote . emacs)
2242 (system . "open %s")
2243 ("ps.gz" . "gv %s")
2244 ("eps.gz" . "gv %s")
2245 ("dvi" . "xdvi %s")
2246 ("fig" . "xfig %s")
2247 (t . "open %s"))
2248 "Default file applications on a macOS system.
2249 The system \"open\" is known as a default, but we use X11 applications
2250 for some files for which the OS does not have a good default.
2251 See `org-file-apps'.")
2253 (defconst org-file-apps-defaults-windowsnt
2254 (list '(remote . emacs)
2255 (cons 'system (lambda (file _path)
2256 (with-no-warnings (w32-shell-execute "open" file))))
2257 (cons t (lambda (file _path)
2258 (with-no-warnings (w32-shell-execute "open" file)))))
2259 "Default file applications on a Windows NT system.
2260 The system \"open\" is used for most files.
2261 See `org-file-apps'.")
2263 (defcustom org-file-apps
2264 '((auto-mode . emacs)
2265 ("\\.mm\\'" . default)
2266 ("\\.x?html?\\'" . default)
2267 ("\\.pdf\\'" . default))
2268 "External applications for opening `file:path' items in a document.
2269 \\<org-mode-map>\
2271 Org mode uses system defaults for different file types, but
2272 you can use this variable to set the application for a given file
2273 extension. The entries in this list are cons cells where the car identifies
2274 files and the cdr the corresponding command.
2276 Possible values for the file identifier are:
2278 \"string\" A string as a file identifier can be interpreted in different
2279 ways, depending on its contents:
2281 - Alphanumeric characters only:
2282 Match links with this file extension.
2283 Example: (\"pdf\" . \"evince %s\")
2284 to open PDFs with evince.
2286 - Regular expression: Match links where the
2287 filename matches the regexp. If you want to
2288 use groups here, use shy groups.
2290 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2291 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2292 to open *.html and *.xhtml with firefox.
2294 - Regular expression which contains (non-shy) groups:
2295 Match links where the whole link, including \"::\", and
2296 anything after that, matches the regexp.
2297 In a custom command string, %1, %2, etc. are replaced with
2298 the parts of the link that were matched by the groups.
2299 For backwards compatibility, if a command string is given
2300 that does not use any of the group matches, this case is
2301 handled identically to the second one (i.e. match against
2302 file name only).
2303 In a custom function, you can access the group matches with
2304 (match-string n link).
2306 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2307 \"evince -p %1 %s\")
2308 to open [[file:document.pdf::5]] with evince at page 5.
2310 `directory' Matches a directory
2311 `remote' Matches a remote file, accessible through tramp or efs.
2312 Remote files most likely should be visited through Emacs
2313 because external applications cannot handle such paths.
2314 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2315 so all files Emacs knows how to handle. Using this with
2316 command `emacs' will open most files in Emacs. Beware that this
2317 will also open html files inside Emacs, unless you add
2318 (\"html\" . default) to the list as well.
2319 `system' The system command to open files, like `open' on Windows
2320 and macOS, and mailcap under GNU/Linux. This is the command
2321 that will be selected if you call `org-open-at-point' with a
2322 double prefix argument (`\\[universal-argument] \
2323 \\[universal-argument] \\[org-open-at-point]').
2324 t Default for files not matched by any of the other options.
2326 Possible values for the command are:
2328 `emacs' The file will be visited by the current Emacs process.
2329 `default' Use the default application for this file type, which is the
2330 association for t in the list, most likely in the system-specific
2331 part. This can be used to overrule an unwanted setting in the
2332 system-specific variable.
2333 `system' Use the system command for opening files, like \"open\".
2334 This command is specified by the entry whose car is `system'.
2335 Most likely, the system-specific version of this variable
2336 does define this command, but you can overrule/replace it
2337 here.
2338 `mailcap' Use command specified in the mailcaps.
2339 string A command to be executed by a shell; %s will be replaced
2340 by the path to the file.
2341 function A Lisp function, which will be called with two arguments:
2342 the file path and the original link string, without the
2343 \"file:\" prefix.
2345 For more examples, see the system specific constants
2346 `org-file-apps-defaults-macosx'
2347 `org-file-apps-defaults-windowsnt'
2348 `org-file-apps-defaults-gnu'."
2349 :group 'org-link-follow
2350 :type '(repeat
2351 (cons (choice :value ""
2352 (string :tag "Extension")
2353 (const :tag "System command to open files" system)
2354 (const :tag "Default for unrecognized files" t)
2355 (const :tag "Remote file" remote)
2356 (const :tag "Links to a directory" directory)
2357 (const :tag "Any files that have Emacs modes"
2358 auto-mode))
2359 (choice :value ""
2360 (const :tag "Visit with Emacs" emacs)
2361 (const :tag "Use default" default)
2362 (const :tag "Use the system command" system)
2363 (string :tag "Command")
2364 (function :tag "Function")))))
2366 (defcustom org-doi-server-url "http://dx.doi.org/"
2367 "The URL of the DOI server."
2368 :type 'string
2369 :version "24.3"
2370 :group 'org-link-follow)
2372 (defgroup org-refile nil
2373 "Options concerning refiling entries in Org mode."
2374 :tag "Org Refile"
2375 :group 'org)
2377 (defcustom org-directory "~/org"
2378 "Directory with Org files.
2379 This is just a default location to look for Org files. There is no need
2380 at all to put your files into this directory. It is used in the
2381 following situations:
2383 1. When a capture template specifies a target file that is not an
2384 absolute path. The path will then be interpreted relative to
2385 `org-directory'
2386 2. When the value of variable `org-agenda-files' is a single file, any
2387 relative paths in this file will be taken as relative to
2388 `org-directory'."
2389 :group 'org-refile
2390 :group 'org-capture
2391 :type 'directory)
2393 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2394 "Default target for storing notes.
2395 Used as a fall back file for org-capture.el, for templates that
2396 do not specify a target file."
2397 :group 'org-refile
2398 :group 'org-capture
2399 :type 'file)
2401 (defcustom org-goto-interface 'outline
2402 "The default interface to be used for `org-goto'.
2403 Allowed values are:
2404 outline The interface shows an outline of the relevant file
2405 and the correct heading is found by moving through
2406 the outline or by searching with incremental search.
2407 outline-path-completion Headlines in the current buffer are offered via
2408 completion. This is the interface also used by
2409 the refile command."
2410 :group 'org-refile
2411 :type '(choice
2412 (const :tag "Outline" outline)
2413 (const :tag "Outline-path-completion" outline-path-completion)))
2415 (defcustom org-goto-max-level 5
2416 "Maximum target level when running `org-goto' with refile interface."
2417 :group 'org-refile
2418 :type 'integer)
2420 (defcustom org-reverse-note-order nil
2421 "Non-nil means store new notes at the beginning of a file or entry.
2422 When nil, new notes will be filed to the end of a file or entry.
2423 This can also be a list with cons cells of regular expressions that
2424 are matched against file names, and values."
2425 :group 'org-capture
2426 :group 'org-refile
2427 :type '(choice
2428 (const :tag "Reverse always" t)
2429 (const :tag "Reverse never" nil)
2430 (repeat :tag "By file name regexp"
2431 (cons regexp boolean))))
2433 (defcustom org-log-refile nil
2434 "Information to record when a task is refiled.
2436 Possible values are:
2438 nil Don't add anything
2439 time Add a time stamp to the task
2440 note Prompt for a note and add it with template `org-log-note-headings'
2442 This option can also be set with on a per-file-basis with
2444 #+STARTUP: nologrefile
2445 #+STARTUP: logrefile
2446 #+STARTUP: lognoterefile
2448 You can have local logging settings for a subtree by setting the LOGGING
2449 property to one or more of these keywords.
2451 When bulk-refiling from the agenda, the value `note' is forbidden and
2452 will temporarily be changed to `time'."
2453 :group 'org-refile
2454 :group 'org-progress
2455 :version "24.1"
2456 :type '(choice
2457 (const :tag "No logging" nil)
2458 (const :tag "Record timestamp" time)
2459 (const :tag "Record timestamp with note." note)))
2461 (defcustom org-refile-targets nil
2462 "Targets for refiling entries with `\\[org-refile]'.
2463 This is a list of cons cells. Each cell contains:
2464 - a specification of the files to be considered, either a list of files,
2465 or a symbol whose function or variable value will be used to retrieve
2466 a file name or a list of file names. If you use `org-agenda-files' for
2467 that, all agenda files will be scanned for targets. Nil means consider
2468 headings in the current buffer.
2469 - A specification of how to find candidate refile targets. This may be
2470 any of:
2471 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2472 This tag has to be present in all target headlines, inheritance will
2473 not be considered.
2474 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2475 todo keyword.
2476 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2477 headlines that are refiling targets.
2478 - a cons cell (:level . N). Any headline of level N is considered a target.
2479 Note that, when `org-odd-levels-only' is set, level corresponds to
2480 order in hierarchy, not to the number of stars.
2481 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2482 Note that, when `org-odd-levels-only' is set, level corresponds to
2483 order in hierarchy, not to the number of stars.
2485 Each element of this list generates a set of possible targets.
2486 The union of these sets is presented (with completion) to
2487 the user by `org-refile'.
2489 You can set the variable `org-refile-target-verify-function' to a function
2490 to verify each headline found by the simple criteria above.
2492 When this variable is nil, all top-level headlines in the current buffer
2493 are used, equivalent to the value `((nil . (:level . 1))'."
2494 :group 'org-refile
2495 :type '(repeat
2496 (cons
2497 (choice :value org-agenda-files
2498 (const :tag "All agenda files" org-agenda-files)
2499 (const :tag "Current buffer" nil)
2500 (function) (variable) (file))
2501 (choice :tag "Identify target headline by"
2502 (cons :tag "Specific tag" (const :value :tag) (string))
2503 (cons :tag "TODO keyword" (const :value :todo) (string))
2504 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2505 (cons :tag "Level number" (const :value :level) (integer))
2506 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2508 (defcustom org-refile-target-verify-function nil
2509 "Function to verify if the headline at point should be a refile target.
2510 The function will be called without arguments, with point at the
2511 beginning of the headline. It should return t and leave point
2512 where it is if the headline is a valid target for refiling.
2514 If the target should not be selected, the function must return nil.
2515 In addition to this, it may move point to a place from where the search
2516 should be continued. For example, the function may decide that the entire
2517 subtree of the current entry should be excluded and move point to the end
2518 of the subtree."
2519 :group 'org-refile
2520 :type '(choice
2521 (const nil)
2522 (function)))
2524 (defcustom org-refile-use-cache nil
2525 "Non-nil means cache refile targets to speed up the process.
2526 \\<org-mode-map>\
2527 The cache for a particular file will be updated automatically when
2528 the buffer has been killed, or when any of the marker used for flagging
2529 refile targets no longer points at a live buffer.
2530 If you have added new entries to a buffer that might themselves be targets,
2531 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2532 if you find that easier, \
2533 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2534 \\[org-refile]'."
2535 :group 'org-refile
2536 :version "24.1"
2537 :type 'boolean)
2539 (defcustom org-refile-use-outline-path nil
2540 "Non-nil means provide refile targets as paths.
2541 So a level 3 headline will be available as level1/level2/level3.
2543 When the value is `file', also include the file name (without directory)
2544 into the path. In this case, you can also stop the completion after
2545 the file name, to get entries inserted as top level in the file.
2547 When `full-file-path', include the full file path.
2549 When `buffer-name', use the buffer name."
2550 :group 'org-refile
2551 :type '(choice
2552 (const :tag "Not" nil)
2553 (const :tag "Yes" t)
2554 (const :tag "Start with file name" file)
2555 (const :tag "Start with full file path" full-file-path)
2556 (const :tag "Start with buffer name" buffer-name)))
2558 (defcustom org-outline-path-complete-in-steps t
2559 "Non-nil means complete the outline path in hierarchical steps.
2560 When Org uses the refile interface to select an outline path (see
2561 `org-refile-use-outline-path'), the completion of the path can be
2562 done in a single go, or it can be done in steps down the headline
2563 hierarchy. Going in steps is probably the best if you do not use
2564 a special completion package like `ido' or `icicles'. However,
2565 when using these packages, going in one step can be very fast,
2566 while still showing the whole path to the entry."
2567 :group 'org-refile
2568 :type 'boolean)
2570 (defcustom org-refile-allow-creating-parent-nodes nil
2571 "Non-nil means allow the creation of new nodes as refile targets.
2572 New nodes are then created by adding \"/new node name\" to the completion
2573 of an existing node. When the value of this variable is `confirm',
2574 new node creation must be confirmed by the user (recommended).
2575 When nil, the completion must match an existing entry.
2577 Note that, if the new heading is not seen by the criteria
2578 listed in `org-refile-targets', multiple instances of the same
2579 heading would be created by trying again to file under the new
2580 heading."
2581 :group 'org-refile
2582 :type '(choice
2583 (const :tag "Never" nil)
2584 (const :tag "Always" t)
2585 (const :tag "Prompt for confirmation" confirm)))
2587 (defcustom org-refile-active-region-within-subtree nil
2588 "Non-nil means also refile active region within a subtree.
2590 By default `org-refile' doesn't allow refiling regions if they
2591 don't contain a set of subtrees, but it might be convenient to
2592 do so sometimes: in that case, the first line of the region is
2593 converted to a headline before refiling."
2594 :group 'org-refile
2595 :version "24.1"
2596 :type 'boolean)
2598 (defgroup org-todo nil
2599 "Options concerning TODO items in Org mode."
2600 :tag "Org TODO"
2601 :group 'org)
2603 (defgroup org-progress nil
2604 "Options concerning Progress logging in Org mode."
2605 :tag "Org Progress"
2606 :group 'org-time)
2608 (defvar org-todo-interpretation-widgets
2609 '((:tag "Sequence (cycling hits every state)" sequence)
2610 (:tag "Type (cycling directly to DONE)" type))
2611 "The available interpretation symbols for customizing `org-todo-keywords'.
2612 Interested libraries should add to this list.")
2614 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2615 "List of TODO entry keyword sequences and their interpretation.
2616 \\<org-mode-map>This is a list of sequences.
2618 Each sequence starts with a symbol, either `sequence' or `type',
2619 indicating if the keywords should be interpreted as a sequence of
2620 action steps, or as different types of TODO items. The first
2621 keywords are states requiring action - these states will select a headline
2622 for inclusion into the global TODO list Org produces. If one of the
2623 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2624 signify that no further action is necessary. If \"|\" is not found,
2625 the last keyword is treated as the only DONE state of the sequence.
2627 The command `\\[org-todo]' cycles an entry through these states, and one
2628 additional state where no keyword is present. For details about this
2629 cycling, see the manual.
2631 TODO keywords and interpretation can also be set on a per-file basis with
2632 the special #+SEQ_TODO and #+TYP_TODO lines.
2634 Each keyword can optionally specify a character for fast state selection
2635 \(in combination with the variable `org-use-fast-todo-selection')
2636 and specifiers for state change logging, using the same syntax that
2637 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2638 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2639 indicates to record a time stamp each time this state is selected.
2641 Each keyword may also specify if a timestamp or a note should be
2642 recorded when entering or leaving the state, by adding additional
2643 characters in the parenthesis after the keyword. This looks like this:
2644 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2645 record only the time of the state change. With X and Y being either
2646 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2647 Y when leaving the state if and only if the *target* state does not
2648 define X. You may omit any of the fast-selection key or X or /Y,
2649 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2651 For backward compatibility, this variable may also be just a list
2652 of keywords. In this case the interpretation (sequence or type) will be
2653 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2654 :group 'org-todo
2655 :group 'org-keywords
2656 :type '(choice
2657 (repeat :tag "Old syntax, just keywords"
2658 (string :tag "Keyword"))
2659 (repeat :tag "New syntax"
2660 (cons
2661 (choice
2662 :tag "Interpretation"
2663 ;;Quick and dirty way to see
2664 ;;`org-todo-interpretations'. This takes the
2665 ;;place of item arguments
2666 :convert-widget
2667 (lambda (widget)
2668 (widget-put widget
2669 :args (mapcar
2670 (lambda (x)
2671 (widget-convert
2672 (cons 'const x)))
2673 org-todo-interpretation-widgets))
2674 widget))
2675 (repeat
2676 (string :tag "Keyword"))))))
2678 (defvar-local org-todo-keywords-1 nil
2679 "All TODO and DONE keywords active in a buffer.")
2680 (defvar org-todo-keywords-for-agenda nil)
2681 (defvar org-done-keywords-for-agenda nil)
2682 (defvar org-todo-keyword-alist-for-agenda nil)
2683 (defvar org-tag-alist-for-agenda nil
2684 "Alist of all tags from all agenda files.")
2685 (defvar org-tag-groups-alist-for-agenda nil
2686 "Alist of all groups tags from all current agenda files.")
2687 (defvar-local org-tag-groups-alist nil)
2688 (defvar org-agenda-contributing-files nil)
2689 (defvar-local org-current-tag-alist nil
2690 "Alist of all tag groups in current buffer.
2691 This variable takes into consideration `org-tag-alist',
2692 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2693 (defvar-local org-not-done-keywords nil)
2694 (defvar-local org-done-keywords nil)
2695 (defvar-local org-todo-heads nil)
2696 (defvar-local org-todo-sets nil)
2697 (defvar-local org-todo-log-states nil)
2698 (defvar-local org-todo-kwd-alist nil)
2699 (defvar-local org-todo-key-alist nil)
2700 (defvar-local org-todo-key-trigger nil)
2702 (defcustom org-todo-interpretation 'sequence
2703 "Controls how TODO keywords are interpreted.
2704 This variable is in principle obsolete and is only used for
2705 backward compatibility, if the interpretation of todo keywords is
2706 not given already in `org-todo-keywords'. See that variable for
2707 more information."
2708 :group 'org-todo
2709 :group 'org-keywords
2710 :type '(choice (const sequence)
2711 (const type)))
2713 (defcustom org-use-fast-todo-selection t
2714 "\\<org-mode-map>\
2715 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2716 This variable describes if and under what circumstances the cycling
2717 mechanism for TODO keywords will be replaced by a single-key, direct
2718 selection scheme.
2720 When nil, fast selection is never used.
2722 When the symbol `prefix', it will be used when `org-todo' is called
2723 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2724 in an Org buffer, and
2725 `\\[universal-argument] t' in an agenda buffer.
2727 When t, fast selection is used by default. In this case, the prefix
2728 argument forces cycling instead.
2730 In all cases, the special interface is only used if access keys have
2731 actually been assigned by the user, i.e. if keywords in the configuration
2732 are followed by a letter in parenthesis, like TODO(t)."
2733 :group 'org-todo
2734 :type '(choice
2735 (const :tag "Never" nil)
2736 (const :tag "By default" t)
2737 (const :tag "Only with C-u C-c C-t" prefix)))
2739 (defcustom org-provide-todo-statistics t
2740 "Non-nil means update todo statistics after insert and toggle.
2741 ALL-HEADLINES means update todo statistics by including headlines
2742 with no TODO keyword as well, counting them as not done.
2743 A list of TODO keywords means the same, but skip keywords that are
2744 not in this list.
2745 When set to a list of two lists, the first list contains keywords
2746 to consider as TODO keywords, the second list contains keywords
2747 to consider as DONE keywords.
2749 When this is set, todo statistics is updated in the parent of the
2750 current entry each time a todo state is changed."
2751 :group 'org-todo
2752 :type '(choice
2753 (const :tag "Yes, only for TODO entries" t)
2754 (const :tag "Yes, including all entries" all-headlines)
2755 (repeat :tag "Yes, for TODOs in this list"
2756 (string :tag "TODO keyword"))
2757 (list :tag "Yes, for TODOs and DONEs in these lists"
2758 (repeat (string :tag "TODO keyword"))
2759 (repeat (string :tag "DONE keyword")))
2760 (other :tag "No TODO statistics" nil)))
2762 (defcustom org-hierarchical-todo-statistics t
2763 "Non-nil means TODO statistics covers just direct children.
2764 When nil, all entries in the subtree are considered.
2765 This has only an effect if `org-provide-todo-statistics' is set.
2766 To set this to nil for only a single subtree, use a COOKIE_DATA
2767 property and include the word \"recursive\" into the value."
2768 :group 'org-todo
2769 :type 'boolean)
2771 (defcustom org-after-todo-state-change-hook nil
2772 "Hook which is run after the state of a TODO item was changed.
2773 The new state (a string with a TODO keyword, or nil) is available in the
2774 Lisp variable `org-state'."
2775 :group 'org-todo
2776 :type 'hook)
2778 (defvar org-blocker-hook nil
2779 "Hook for functions that are allowed to block a state change.
2781 Functions in this hook should not modify the buffer.
2782 Each function gets as its single argument a property list,
2783 see `org-trigger-hook' for more information about this list.
2785 If any of the functions in this hook returns nil, the state change
2786 is blocked.")
2788 (defvar org-trigger-hook nil
2789 "Hook for functions that are triggered by a state change.
2791 Each function gets as its single argument a property list with at
2792 least the following elements:
2794 (:type type-of-change :position pos-at-entry-start
2795 :from old-state :to new-state)
2797 Depending on the type, more properties may be present.
2799 This mechanism is currently implemented for:
2801 TODO state changes
2802 ------------------
2803 :type todo-state-change
2804 :from previous state (keyword as a string), or nil, or a symbol
2805 `todo' or `done', to indicate the general type of state.
2806 :to new state, like in :from")
2808 (defcustom org-enforce-todo-dependencies nil
2809 "Non-nil means undone TODO entries will block switching the parent to DONE.
2810 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2811 be blocked if any prior sibling is not yet done.
2812 Finally, if the parent is blocked because of ordered siblings of its own,
2813 the child will also be blocked."
2814 :set (lambda (var val)
2815 (set var val)
2816 (if val
2817 (add-hook 'org-blocker-hook
2818 'org-block-todo-from-children-or-siblings-or-parent)
2819 (remove-hook 'org-blocker-hook
2820 'org-block-todo-from-children-or-siblings-or-parent)))
2821 :group 'org-todo
2822 :type 'boolean)
2824 (defcustom org-enforce-todo-checkbox-dependencies nil
2825 "Non-nil means unchecked boxes will block switching the parent to DONE.
2826 When this is nil, checkboxes have no influence on switching TODO states.
2827 When non-nil, you first need to check off all check boxes before the TODO
2828 entry can be switched to DONE.
2829 This variable needs to be set before org.el is loaded, and you need to
2830 restart Emacs after a change to make the change effective. The only way
2831 to change is while Emacs is running is through the customize interface."
2832 :set (lambda (var val)
2833 (set var val)
2834 (if val
2835 (add-hook 'org-blocker-hook
2836 'org-block-todo-from-checkboxes)
2837 (remove-hook 'org-blocker-hook
2838 'org-block-todo-from-checkboxes)))
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-treat-insert-todo-heading-as-state-change nil
2843 "Non-nil means inserting a TODO heading is treated as state change.
2844 So when the command `\\[org-insert-todo-heading]' is used, state change
2845 logging will apply if appropriate. When nil, the new TODO item will
2846 be inserted directly, and no logging will take place."
2847 :group 'org-todo
2848 :type 'boolean)
2850 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2851 "Non-nil means switching TODO states with S-cursor counts as state change.
2852 This is the default behavior. However, setting this to nil allows a
2853 convenient way to select a TODO state and bypass any logging associated
2854 with that."
2855 :group 'org-todo
2856 :type 'boolean)
2858 (defcustom org-todo-state-tags-triggers nil
2859 "Tag changes that should be triggered by TODO state changes.
2860 This is a list. Each entry is
2862 (state-change (tag . flag) .......)
2864 State-change can be a string with a state, and empty string to indicate the
2865 state that has no TODO keyword, or it can be one of the symbols `todo'
2866 or `done', meaning any not-done or done state, respectively."
2867 :group 'org-todo
2868 :group 'org-tags
2869 :type '(repeat
2870 (cons (choice :tag "When changing to"
2871 (const :tag "Not-done state" todo)
2872 (const :tag "Done state" done)
2873 (string :tag "State"))
2874 (repeat
2875 (cons :tag "Tag action"
2876 (string :tag "Tag")
2877 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2879 (defcustom org-log-done nil
2880 "Information to record when a task moves to the DONE state.
2882 Possible values are:
2884 nil Don't add anything, just change the keyword
2885 time Add a time stamp to the task
2886 note Prompt for a note and add it with template `org-log-note-headings'
2888 This option can also be set with on a per-file-basis with
2890 #+STARTUP: nologdone
2891 #+STARTUP: logdone
2892 #+STARTUP: lognotedone
2894 You can have local logging settings for a subtree by setting the LOGGING
2895 property to one or more of these keywords."
2896 :group 'org-todo
2897 :group 'org-progress
2898 :type '(choice
2899 (const :tag "No logging" nil)
2900 (const :tag "Record CLOSED timestamp" time)
2901 (const :tag "Record CLOSED timestamp with note." note)))
2903 ;; Normalize old uses of org-log-done.
2904 (cond
2905 ((eq org-log-done t) (setq org-log-done 'time))
2906 ((and (listp org-log-done) (memq 'done org-log-done))
2907 (setq org-log-done 'note)))
2909 (defcustom org-log-reschedule nil
2910 "Information to record when the scheduling date of a tasks is modified.
2912 Possible values are:
2914 nil Don't add anything, just change the date
2915 time Add a time stamp to the task
2916 note Prompt for a note and add it with template `org-log-note-headings'
2918 This option can also be set with on a per-file-basis with
2920 #+STARTUP: nologreschedule
2921 #+STARTUP: logreschedule
2922 #+STARTUP: lognotereschedule"
2923 :group 'org-todo
2924 :group 'org-progress
2925 :type '(choice
2926 (const :tag "No logging" nil)
2927 (const :tag "Record timestamp" time)
2928 (const :tag "Record timestamp with note." note)))
2930 (defcustom org-log-redeadline nil
2931 "Information to record when the deadline date of a tasks is modified.
2933 Possible values are:
2935 nil Don't add anything, just change the date
2936 time Add a time stamp to the task
2937 note Prompt for a note and add it with template `org-log-note-headings'
2939 This option can also be set with on a per-file-basis with
2941 #+STARTUP: nologredeadline
2942 #+STARTUP: logredeadline
2943 #+STARTUP: lognoteredeadline
2945 You can have local logging settings for a subtree by setting the LOGGING
2946 property to one or more of these keywords."
2947 :group 'org-todo
2948 :group 'org-progress
2949 :type '(choice
2950 (const :tag "No logging" nil)
2951 (const :tag "Record timestamp" time)
2952 (const :tag "Record timestamp with note." note)))
2954 (defcustom org-log-note-clock-out nil
2955 "Non-nil means record a note when clocking out of an item.
2956 This can also be configured on a per-file basis by adding one of
2957 the following lines anywhere in the buffer:
2959 #+STARTUP: lognoteclock-out
2960 #+STARTUP: nolognoteclock-out"
2961 :group 'org-todo
2962 :group 'org-progress
2963 :type 'boolean)
2965 (defcustom org-log-done-with-time t
2966 "Non-nil means the CLOSED time stamp will contain date and time.
2967 When nil, only the date will be recorded."
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-note-headings
2972 '((done . "CLOSING NOTE %t")
2973 (state . "State %-12s from %-12S %t")
2974 (note . "Note taken on %t")
2975 (reschedule . "Rescheduled from %S on %t")
2976 (delschedule . "Not scheduled, was %S on %t")
2977 (redeadline . "New deadline from %S on %t")
2978 (deldeadline . "Removed deadline, was %S on %t")
2979 (refile . "Refiled on %t")
2980 (clock-out . ""))
2981 "Headings for notes added to entries.
2983 The value is an alist, with the car being a symbol indicating the
2984 note context, and the cdr is the heading to be used. The heading
2985 may also be the empty string. The following placeholders can be
2986 used:
2988 %t a time stamp.
2989 %T an active time stamp instead the default inactive one
2990 %d a short-format time stamp.
2991 %D an active short-format time stamp.
2992 %s the new TODO state or time stamp (inactive), in double quotes.
2993 %S the old TODO state or time stamp (inactive), in double quotes.
2994 %u the user name.
2995 %U full user name.
2997 In fact, it is not a good idea to change the `state' entry,
2998 because Agenda Log mode depends on the format of these entries."
2999 :group 'org-todo
3000 :group 'org-progress
3001 :type '(list :greedy t
3002 (cons (const :tag "Heading when closing an item" done) string)
3003 (cons (const :tag
3004 "Heading when changing todo state (todo sequence only)"
3005 state) string)
3006 (cons (const :tag "Heading when just taking a note" note) string)
3007 (cons (const :tag "Heading when rescheduling" reschedule) string)
3008 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3009 (cons (const :tag "Heading when changing deadline" redeadline) string)
3010 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3011 (cons (const :tag "Heading when refiling" refile) string)
3012 (cons (const :tag "Heading when clocking out" clock-out) string)))
3014 (unless (assq 'note org-log-note-headings)
3015 (push '(note . "%t") org-log-note-headings))
3017 (defcustom org-log-into-drawer nil
3018 "Non-nil means insert state change notes and time stamps into a drawer.
3019 When nil, state changes notes will be inserted after the headline and
3020 any scheduling and clock lines, but not inside a drawer.
3022 The value of this variable should be the name of the drawer to use.
3023 LOGBOOK is proposed as the default drawer for this purpose, you can
3024 also set this to a string to define the drawer of your choice.
3026 A value of t is also allowed, representing \"LOGBOOK\".
3028 A value of t or nil can also be set with on a per-file-basis with
3030 #+STARTUP: logdrawer
3031 #+STARTUP: nologdrawer
3033 If this variable is set, `org-log-state-notes-insert-after-drawers'
3034 will be ignored.
3036 You can set the property LOG_INTO_DRAWER to overrule this setting for
3037 a subtree.
3039 Do not check directly this variable in a Lisp program. Call
3040 function `org-log-into-drawer' instead."
3041 :group 'org-todo
3042 :group 'org-progress
3043 :type '(choice
3044 (const :tag "Not into a drawer" nil)
3045 (const :tag "LOGBOOK" t)
3046 (string :tag "Other")))
3048 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3050 (defun org-log-into-drawer ()
3051 "Name of the log drawer, as a string, or nil.
3052 This is the value of `org-log-into-drawer'. However, if the
3053 current entry has or inherits a LOG_INTO_DRAWER property, it will
3054 be used instead of the default value."
3055 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3056 (cond ((equal p "nil") nil)
3057 ((equal p "t") "LOGBOOK")
3058 ((stringp p) p)
3059 (p "LOGBOOK")
3060 ((stringp org-log-into-drawer) org-log-into-drawer)
3061 (org-log-into-drawer "LOGBOOK"))))
3063 (defcustom org-log-state-notes-insert-after-drawers nil
3064 "Non-nil means insert state change notes after any drawers in entry.
3065 Only the drawers that *immediately* follow the headline and the
3066 deadline/scheduled line are skipped.
3067 When nil, insert notes right after the heading and perhaps the line
3068 with deadline/scheduling if present.
3070 This variable will have no effect if `org-log-into-drawer' is
3071 set."
3072 :group 'org-todo
3073 :group 'org-progress
3074 :type 'boolean)
3076 (defcustom org-log-states-order-reversed t
3077 "Non-nil means the latest state note will be directly after heading.
3078 When nil, the state change notes will be ordered according to time.
3080 This option can also be set with on a per-file-basis with
3082 #+STARTUP: logstatesreversed
3083 #+STARTUP: nologstatesreversed"
3084 :group 'org-todo
3085 :group 'org-progress
3086 :type 'boolean)
3088 (defcustom org-todo-repeat-to-state nil
3089 "The TODO state to which a repeater should return the repeating task.
3090 By default this is the first task in a TODO sequence, or the previous state
3091 in a TODO_TYP set. But you can specify another task here.
3092 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3093 :group 'org-todo
3094 :version "24.1"
3095 :type '(choice (const :tag "Head of sequence" nil)
3096 (string :tag "Specific state")))
3098 (defcustom org-log-repeat 'time
3099 "Non-nil means record moving through the DONE state when triggering repeat.
3100 An auto-repeating task is immediately switched back to TODO when
3101 marked DONE. If you are not logging state changes (by adding \"@\"
3102 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3103 record a closing note, there will be no record of the task moving
3104 through DONE. This variable forces taking a note anyway.
3106 nil Don't force a record
3107 time Record a time stamp
3108 note Prompt for a note and add it with template `org-log-note-headings'
3110 This option can also be set with on a per-file-basis with
3112 #+STARTUP: nologrepeat
3113 #+STARTUP: logrepeat
3114 #+STARTUP: lognoterepeat
3116 You can have local logging settings for a subtree by setting the LOGGING
3117 property to one or more of these keywords."
3118 :group 'org-todo
3119 :group 'org-progress
3120 :type '(choice
3121 (const :tag "Don't force a record" nil)
3122 (const :tag "Force recording the DONE state" time)
3123 (const :tag "Force recording a note with the DONE state" note)))
3126 (defgroup org-priorities nil
3127 "Priorities in Org mode."
3128 :tag "Org Priorities"
3129 :group 'org-todo)
3131 (defcustom org-enable-priority-commands t
3132 "Non-nil means priority commands are active.
3133 When nil, these commands will be disabled, so that you never accidentally
3134 set a priority."
3135 :group 'org-priorities
3136 :type 'boolean)
3138 (defcustom org-highest-priority ?A
3139 "The highest priority of TODO items. A character like ?A, ?B etc.
3140 Must have a smaller ASCII number than `org-lowest-priority'."
3141 :group 'org-priorities
3142 :type 'character)
3144 (defcustom org-lowest-priority ?C
3145 "The lowest priority of TODO items. A character like ?A, ?B etc.
3146 Must have a larger ASCII number than `org-highest-priority'."
3147 :group 'org-priorities
3148 :type 'character)
3150 (defcustom org-default-priority ?B
3151 "The default priority of TODO items.
3152 This is the priority an item gets if no explicit priority is given.
3153 When starting to cycle on an empty priority the first step in the cycle
3154 depends on `org-priority-start-cycle-with-default'. The resulting first
3155 step priority must not exceed the range from `org-highest-priority' to
3156 `org-lowest-priority' which means that `org-default-priority' has to be
3157 in this range exclusive or inclusive the range boundaries. Else the
3158 first step refuses to set the default and the second will fall back
3159 to (depending on the command used) the highest or lowest priority."
3160 :group 'org-priorities
3161 :type 'character)
3163 (defcustom org-priority-start-cycle-with-default t
3164 "Non-nil means start with default priority when starting to cycle.
3165 When this is nil, the first step in the cycle will be (depending on the
3166 command used) one higher or lower than the default priority.
3167 See also `org-default-priority'."
3168 :group 'org-priorities
3169 :type 'boolean)
3171 (defcustom org-get-priority-function nil
3172 "Function to extract the priority from a string.
3173 The string is normally the headline. If this is nil Org computes the
3174 priority from the priority cookie like [#A] in the headline. It returns
3175 an integer, increasing by 1000 for each priority level.
3176 The user can set a different function here, which should take a string
3177 as an argument and return the numeric priority."
3178 :group 'org-priorities
3179 :version "24.1"
3180 :type '(choice
3181 (const nil)
3182 (function)))
3184 (defgroup org-time nil
3185 "Options concerning time stamps and deadlines in Org mode."
3186 :tag "Org Time"
3187 :group 'org)
3189 (defcustom org-time-stamp-rounding-minutes '(0 5)
3190 "Number of minutes to round time stamps to.
3191 \\<org-mode-map>\
3192 These are two values, the first applies when first creating a time stamp.
3193 The second applies when changing it with the commands `S-up' and `S-down'.
3194 When changing the time stamp, this means that it will change in steps
3195 of N minutes, as given by the second value.
3197 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3198 numbers should be factors of 60, so for example 5, 10, 15.
3200 When this is larger than 1, you can still force an exact time stamp by using
3201 a double prefix argument to a time stamp command like \
3202 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3203 and by using a prefix arg to `S-up/down' to specify the exact number
3204 of minutes to shift."
3205 :group 'org-time
3206 :get (lambda (var) ; Make sure both elements are there
3207 (if (integerp (default-value var))
3208 (list (default-value var) 5)
3209 (default-value var)))
3210 :type '(list
3211 (integer :tag "when inserting times")
3212 (integer :tag "when modifying times")))
3214 ;; Normalize old customizations of this variable.
3215 (when (integerp org-time-stamp-rounding-minutes)
3216 (setq org-time-stamp-rounding-minutes
3217 (list org-time-stamp-rounding-minutes
3218 org-time-stamp-rounding-minutes)))
3220 (defcustom org-display-custom-times nil
3221 "Non-nil means overlay custom formats over all time stamps.
3222 The formats are defined through the variable `org-time-stamp-custom-formats'.
3223 To turn this on on a per-file basis, insert anywhere in the file:
3224 #+STARTUP: customtime"
3225 :group 'org-time
3226 :set 'set-default
3227 :type 'sexp)
3228 (make-variable-buffer-local 'org-display-custom-times)
3230 (defcustom org-time-stamp-custom-formats
3231 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3232 "Custom formats for time stamps. See `format-time-string' for the syntax.
3233 These are overlaid over the default ISO format if the variable
3234 `org-display-custom-times' is set. Time like %H:%M should be at the
3235 end of the second format. The custom formats are also honored by export
3236 commands, if custom time display is turned on at the time of export."
3237 :group 'org-time
3238 :type 'sexp)
3240 (defun org-time-stamp-format (&optional long inactive)
3241 "Get the right format for a time string."
3242 (let ((f (if long (cdr org-time-stamp-formats)
3243 (car org-time-stamp-formats))))
3244 (if inactive
3245 (concat "[" (substring f 1 -1) "]")
3246 f)))
3248 (defcustom org-deadline-warning-days 14
3249 "Number of days before expiration during which a deadline becomes active.
3250 This variable governs the display in sparse trees and in the agenda.
3251 When 0 or negative, it means use this number (the absolute value of it)
3252 even if a deadline has a different individual lead time specified.
3254 Custom commands can set this variable in the options section."
3255 :group 'org-time
3256 :group 'org-agenda-daily/weekly
3257 :type 'integer)
3259 (defcustom org-scheduled-delay-days 0
3260 "Number of days before a scheduled item becomes active.
3261 This variable governs the display in sparse trees and in the agenda.
3262 The default value (i.e. 0) means: don't delay scheduled item.
3263 When negative, it means use this number (the absolute value of it)
3264 even if a scheduled item has a different individual delay time
3265 specified.
3267 Custom commands can set this variable in the options section."
3268 :group 'org-time
3269 :group 'org-agenda-daily/weekly
3270 :version "24.4"
3271 :package-version '(Org . "8.0")
3272 :type 'integer)
3274 (defcustom org-read-date-prefer-future t
3275 "Non-nil means assume future for incomplete date input from user.
3276 This affects the following situations:
3277 1. The user gives a month but not a year.
3278 For example, if it is April and you enter \"feb 2\", this will be read
3279 as Feb 2, *next* year. \"May 5\", however, will be this year.
3280 2. The user gives a day, but no month.
3281 For example, if today is the 15th, and you enter \"3\", Org will read
3282 this as the third of *next* month. However, if you enter \"17\",
3283 it will be considered as *this* month.
3285 If you set this variable to the symbol `time', then also the following
3286 will work:
3288 3. If the user gives a time.
3289 If the time is before now, it will be interpreted as tomorrow.
3291 Currently none of this works for ISO week specifications.
3293 When this option is nil, the current day, month and year will always be
3294 used as defaults.
3296 See also `org-agenda-jump-prefer-future'."
3297 :group 'org-time
3298 :type '(choice
3299 (const :tag "Never" nil)
3300 (const :tag "Check month and day" t)
3301 (const :tag "Check month, day, and time" time)))
3303 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3304 "Should the agenda jump command prefer the future for incomplete dates?
3305 The default is to do the same as configured in `org-read-date-prefer-future'.
3306 But you can also set a deviating value here.
3307 This may t or nil, or the symbol `org-read-date-prefer-future'."
3308 :group 'org-agenda
3309 :group 'org-time
3310 :version "24.1"
3311 :type '(choice
3312 (const :tag "Use org-read-date-prefer-future"
3313 org-read-date-prefer-future)
3314 (const :tag "Never" nil)
3315 (const :tag "Always" t)))
3317 (defcustom org-read-date-force-compatible-dates t
3318 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3320 Depending on the system Emacs is running on, certain dates cannot
3321 be represented with the type used internally to represent time.
3322 Dates between 1970-1-1 and 2038-1-1 can always be represented
3323 correctly. Some systems allow for earlier dates, some for later,
3324 some for both. One way to find out it to insert any date into an
3325 Org buffer, putting the cursor on the year and hitting S-up and
3326 S-down to test the range.
3328 When this variable is set to t, the date/time prompt will not let
3329 you specify dates outside the 1970-2037 range, so it is certain that
3330 these dates will work in whatever version of Emacs you are
3331 running, and also that you can move a file from one Emacs implementation
3332 to another. WHenever Org is forcing the year for you, it will display
3333 a message and beep.
3335 When this variable is nil, Org will check if the date is
3336 representable in the specific Emacs implementation you are using.
3337 If not, it will force a year, usually the current year, and beep
3338 to remind you. Currently this setting is not recommended because
3339 the likelihood that you will open your Org files in an Emacs that
3340 has limited date range is not negligible.
3342 A workaround for this problem is to use diary sexp dates for time
3343 stamps outside of this range."
3344 :group 'org-time
3345 :version "24.1"
3346 :type 'boolean)
3348 (defcustom org-read-date-display-live t
3349 "Non-nil means display current interpretation of date prompt live.
3350 This display will be in an overlay, in the minibuffer."
3351 :group 'org-time
3352 :type 'boolean)
3354 (defcustom org-read-date-popup-calendar t
3355 "Non-nil means pop up a calendar when prompting for a date.
3356 In the calendar, the date can be selected with mouse-1. However, the
3357 minibuffer will also be active, and you can simply enter the date as well.
3358 When nil, only the minibuffer will be available."
3359 :group 'org-time
3360 :type 'boolean)
3361 (defvaralias 'org-popup-calendar-for-date-prompt
3362 'org-read-date-popup-calendar)
3364 (defcustom org-extend-today-until 0
3365 "The hour when your day really ends. Must be an integer.
3366 This has influence for the following applications:
3367 - When switching the agenda to \"today\". It it is still earlier than
3368 the time given here, the day recognized as TODAY is actually yesterday.
3369 - When a date is read from the user and it is still before the time given
3370 here, the current date and time will be assumed to be yesterday, 23:59.
3371 Also, timestamps inserted in capture templates follow this rule.
3373 IMPORTANT: This is a feature whose implementation is and likely will
3374 remain incomplete. Really, it is only here because past midnight seems to
3375 be the favorite working time of John Wiegley :-)"
3376 :group 'org-time
3377 :type 'integer)
3379 (defcustom org-use-effective-time nil
3380 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3381 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3382 \"effective time\" of any timestamps between midnight and 8am will be
3383 23:59 of the previous day."
3384 :group 'org-time
3385 :version "24.1"
3386 :type 'boolean)
3388 (defcustom org-use-last-clock-out-time-as-effective-time nil
3389 "When non-nil, use the last clock out time for `org-todo'.
3390 Note that this option has precedence over the combined use of
3391 `org-use-effective-time' and `org-extend-today-until'."
3392 :group 'org-time
3393 :version "24.4"
3394 :package-version '(Org . "8.0")
3395 :type 'boolean)
3397 (defcustom org-edit-timestamp-down-means-later nil
3398 "Non-nil means S-down will increase the time in a time stamp.
3399 When nil, S-up will increase."
3400 :group 'org-time
3401 :type 'boolean)
3403 (defcustom org-calendar-follow-timestamp-change t
3404 "Non-nil means make the calendar window follow timestamp changes.
3405 When a timestamp is modified and the calendar window is visible, it will be
3406 moved to the new date."
3407 :group 'org-time
3408 :type 'boolean)
3410 (defgroup org-tags nil
3411 "Options concerning tags in Org mode."
3412 :tag "Org Tags"
3413 :group 'org)
3415 (defcustom org-tag-alist nil
3416 "Default tags available in Org files.
3418 The value of this variable is an alist. Associations either:
3420 (TAG)
3421 (TAG . SELECT)
3422 (SPECIAL)
3424 where TAG is a tag as a string, SELECT is character, used to
3425 select that tag through the fast tag selection interface, and
3426 SPECIAL is one of the following keywords: `:startgroup',
3427 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3428 `:newline'. These keywords are used to define a hierarchy of
3429 tags. See manual for details.
3431 When this variable is nil, Org mode bases tag input on what is
3432 already in the buffer. The value can be overridden locally by
3433 using a TAGS keyword, e.g.,
3435 #+TAGS: tag1 tag2
3437 See also `org-tag-persistent-alist' to sidestep this behavior."
3438 :group 'org-tags
3439 :type '(repeat
3440 (choice
3441 (cons :tag "Tag with key"
3442 (string :tag "Tag name")
3443 (character :tag "Access char"))
3444 (list :tag "Tag" (string :tag "Tag name"))
3445 (const :tag "Start radio group" (:startgroup))
3446 (const :tag "Start tag group, non distinct" (:startgrouptag))
3447 (const :tag "Group tags delimiter" (:grouptags))
3448 (const :tag "End radio group" (:endgroup))
3449 (const :tag "End tag group, non distinct" (:endgrouptag))
3450 (const :tag "New line" (:newline)))))
3452 (defcustom org-tag-persistent-alist nil
3453 "Tags always available in Org files.
3455 The value of this variable is an alist. Associations either:
3457 (TAG)
3458 (TAG . SELECT)
3459 (SPECIAL)
3461 where TAG is a tag as a string, SELECT is a character, used to
3462 select that tag through the fast tag selection interface, and
3463 SPECIAL is one of the following keywords: `:startgroup',
3464 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3465 `:newline'. These keywords are used to define a hierarchy of
3466 tags. See manual for details.
3468 Unlike to `org-tag-alist', tags defined in this variable do not
3469 depend on a local TAGS keyword. Instead, to disable these tags
3470 on a per-file basis, insert anywhere in the file:
3472 #+STARTUP: noptag"
3473 :group 'org-tags
3474 :type '(repeat
3475 (choice
3476 (cons :tag "Tag with key"
3477 (string :tag "Tag name")
3478 (character :tag "Access char"))
3479 (list :tag "Tag" (string :tag "Tag name"))
3480 (const :tag "Start radio group" (:startgroup))
3481 (const :tag "Start tag group, non distinct" (:startgrouptag))
3482 (const :tag "Group tags delimiter" (:grouptags))
3483 (const :tag "End radio group" (:endgroup))
3484 (const :tag "End tag group, non distinct" (:endgrouptag))
3485 (const :tag "New line" (:newline)))))
3487 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3488 "If non-nil, always offer completion for all tags of all agenda files.
3489 Instead of customizing this variable directly, you might want to
3490 set it locally for capture buffers, because there no list of
3491 tags in that file can be created dynamically (there are none).
3493 (add-hook \\='org-capture-mode-hook
3494 (lambda ()
3495 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3496 :group 'org-tags
3497 :version "24.1"
3498 :type 'boolean)
3500 (defvar org-file-tags nil
3501 "List of tags that can be inherited by all entries in the file.
3502 The tags will be inherited if the variable `org-use-tag-inheritance'
3503 says they should be.
3504 This variable is populated from #+FILETAGS lines.")
3506 (defcustom org-use-fast-tag-selection 'auto
3507 "Non-nil means use fast tag selection scheme.
3508 This is a special interface to select and deselect tags with single keys.
3509 When nil, fast selection is never used.
3510 When the symbol `auto', fast selection is used if and only if selection
3511 characters for tags have been configured, either through the variable
3512 `org-tag-alist' or through a #+TAGS line in the buffer.
3513 When t, fast selection is always used and selection keys are assigned
3514 automatically if necessary."
3515 :group 'org-tags
3516 :type '(choice
3517 (const :tag "Always" t)
3518 (const :tag "Never" nil)
3519 (const :tag "When selection characters are configured" auto)))
3521 (defcustom org-fast-tag-selection-single-key nil
3522 "Non-nil means fast tag selection exits after first change.
3523 When nil, you have to press RET to exit it.
3524 During fast tag selection, you can toggle this flag with `C-c'.
3525 This variable can also have the value `expert'. In this case, the window
3526 displaying the tags menu is not even shown, until you press C-c again."
3527 :group 'org-tags
3528 :type '(choice
3529 (const :tag "No" nil)
3530 (const :tag "Yes" t)
3531 (const :tag "Expert" expert)))
3533 (defvar org-fast-tag-selection-include-todo nil
3534 "Non-nil means fast tags selection interface will also offer TODO states.
3535 This is an undocumented feature, you should not rely on it.")
3537 (defcustom org-tags-column -77
3538 "The column to which tags should be indented in a headline.
3539 If this number is positive, it specifies the column. If it is negative,
3540 it means that the tags should be flushright to that column. For example,
3541 -80 works well for a normal 80 character screen.
3542 When 0, place tags directly after headline text, with only one space in
3543 between."
3544 :group 'org-tags
3545 :type 'integer)
3547 (defcustom org-auto-align-tags t
3548 "Non-nil keeps tags aligned when modifying headlines.
3549 Some operations (i.e. demoting) change the length of a headline and
3550 therefore shift the tags around. With this option turned on, after
3551 each such operation the tags are again aligned to `org-tags-column'."
3552 :group 'org-tags
3553 :type 'boolean)
3555 (defcustom org-use-tag-inheritance t
3556 "Non-nil means tags in levels apply also for sublevels.
3557 When nil, only the tags directly given in a specific line apply there.
3558 This may also be a list of tags that should be inherited, or a regexp that
3559 matches tags that should be inherited. Additional control is possible
3560 with the variable `org-tags-exclude-from-inheritance' which gives an
3561 explicit list of tags to be excluded from inheritance, even if the value of
3562 `org-use-tag-inheritance' would select it for inheritance.
3564 If this option is t, a match early-on in a tree can lead to a large
3565 number of matches in the subtree when constructing the agenda or creating
3566 a sparse tree. If you only want to see the first match in a tree during
3567 a search, check out the variable `org-tags-match-list-sublevels'."
3568 :group 'org-tags
3569 :type '(choice
3570 (const :tag "Not" nil)
3571 (const :tag "Always" t)
3572 (repeat :tag "Specific tags" (string :tag "Tag"))
3573 (regexp :tag "Tags matched by regexp")))
3575 (defcustom org-tags-exclude-from-inheritance nil
3576 "List of tags that should never be inherited.
3577 This is a way to exclude a few tags from inheritance. For way to do
3578 the opposite, to actively allow inheritance for selected tags,
3579 see the variable `org-use-tag-inheritance'."
3580 :group 'org-tags
3581 :type '(repeat (string :tag "Tag")))
3583 (defun org-tag-inherit-p (tag)
3584 "Check if TAG is one that should be inherited."
3585 (cond
3586 ((member tag org-tags-exclude-from-inheritance) nil)
3587 ((eq org-use-tag-inheritance t) t)
3588 ((not org-use-tag-inheritance) nil)
3589 ((stringp org-use-tag-inheritance)
3590 (string-match org-use-tag-inheritance tag))
3591 ((listp org-use-tag-inheritance)
3592 (member tag org-use-tag-inheritance))
3593 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3595 (defcustom org-tags-match-list-sublevels t
3596 "Non-nil means list also sublevels of headlines matching a search.
3597 This variable applies to tags/property searches, and also to stuck
3598 projects because this search is based on a tags match as well.
3600 When set to the symbol `indented', sublevels are indented with
3601 leading dots.
3603 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3604 the sublevels of a headline matching a tag search often also match
3605 the same search. Listing all of them can create very long lists.
3606 Setting this variable to nil causes subtrees of a match to be skipped.
3608 This variable is semi-obsolete and probably should always be true. It
3609 is better to limit inheritance to certain tags using the variables
3610 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3611 :group 'org-tags
3612 :type '(choice
3613 (const :tag "No, don't list them" nil)
3614 (const :tag "Yes, do list them" t)
3615 (const :tag "List them, indented with leading dots" indented)))
3617 (defcustom org-tags-sort-function nil
3618 "When set, tags are sorted using this function as a comparator."
3619 :group 'org-tags
3620 :type '(choice
3621 (const :tag "No sorting" nil)
3622 (const :tag "Alphabetical" string<)
3623 (const :tag "Reverse alphabetical" string>)
3624 (function :tag "Custom function" nil)))
3626 (defvar org-tags-history nil
3627 "History of minibuffer reads for tags.")
3628 (defvar org-last-tags-completion-table nil
3629 "The last used completion table for tags.")
3630 (defvar org-after-tags-change-hook nil
3631 "Hook that is run after the tags in a line have changed.")
3633 (defgroup org-properties nil
3634 "Options concerning properties in Org mode."
3635 :tag "Org Properties"
3636 :group 'org)
3638 (defcustom org-property-format "%-10s %s"
3639 "How property key/value pairs should be formatted by `indent-line'.
3640 When `indent-line' hits a property definition, it will format the line
3641 according to this format, mainly to make sure that the values are
3642 lined-up with respect to each other."
3643 :group 'org-properties
3644 :type 'string)
3646 (defcustom org-properties-postprocess-alist nil
3647 "Alist of properties and functions to adjust inserted values.
3648 Elements of this alist must be of the form
3650 ([string] [function])
3652 where [string] must be a property name and [function] must be a
3653 lambda expression: this lambda expression must take one argument,
3654 the value to adjust, and return the new value as a string.
3656 For example, this element will allow the property \"Remaining\"
3657 to be updated wrt the relation between the \"Effort\" property
3658 and the clock summary:
3660 ((\"Remaining\" (lambda(value)
3661 (let ((clocksum (org-clock-sum-current-item))
3662 (effort (org-duration-to-minutes
3663 (org-entry-get (point) \"Effort\"))))
3664 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3665 :group 'org-properties
3666 :version "24.1"
3667 :type '(alist :key-type (string :tag "Property")
3668 :value-type (function :tag "Function")))
3670 (defcustom org-use-property-inheritance nil
3671 "Non-nil means properties apply also for sublevels.
3673 This setting is chiefly used during property searches. Turning it on can
3674 cause significant overhead when doing a search, which is why it is not
3675 on by default.
3677 When nil, only the properties directly given in the current entry count.
3678 When t, every property is inherited. The value may also be a list of
3679 properties that should have inheritance, or a regular expression matching
3680 properties that should be inherited.
3682 However, note that some special properties use inheritance under special
3683 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3684 and the properties ending in \"_ALL\" when they are used as descriptor
3685 for valid values of a property.
3687 Note for programmers:
3688 When querying an entry with `org-entry-get', you can control if inheritance
3689 should be used. By default, `org-entry-get' looks only at the local
3690 properties. You can request inheritance by setting the inherit argument
3691 to t (to force inheritance) or to `selective' (to respect the setting
3692 in this variable)."
3693 :group 'org-properties
3694 :type '(choice
3695 (const :tag "Not" nil)
3696 (const :tag "Always" t)
3697 (repeat :tag "Specific properties" (string :tag "Property"))
3698 (regexp :tag "Properties matched by regexp")))
3700 (defun org-property-inherit-p (property)
3701 "Return a non-nil value if PROPERTY should be inherited."
3702 (cond
3703 ((eq org-use-property-inheritance t) t)
3704 ((not org-use-property-inheritance) nil)
3705 ((stringp org-use-property-inheritance)
3706 (string-match org-use-property-inheritance property))
3707 ((listp org-use-property-inheritance)
3708 (member-ignore-case property org-use-property-inheritance))
3709 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3711 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3712 "The default column format, if no other format has been defined.
3713 This variable can be set on the per-file basis by inserting a line
3715 #+COLUMNS: %25ITEM ....."
3716 :group 'org-properties
3717 :type 'string)
3719 (defcustom org-columns-ellipses ".."
3720 "The ellipses to be used when a field in column view is truncated.
3721 When this is the empty string, as many characters as possible are shown,
3722 but then there will be no visual indication that the field has been truncated.
3723 When this is a string of length N, the last N characters of a truncated
3724 field are replaced by this string. If the column is narrower than the
3725 ellipses string, only part of the ellipses string will be shown."
3726 :group 'org-properties
3727 :type 'string)
3729 (defconst org-global-properties-fixed
3730 '(("VISIBILITY_ALL" . "folded children content all")
3731 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3732 "List of property/value pairs that can be inherited by any entry.
3734 These are fixed values, for the preset properties. The user variable
3735 that can be used to add to this list is `org-global-properties'.
3737 The entries in this list are cons cells where the car is a property
3738 name and cdr is a string with the value. If the value represents
3739 multiple items like an \"_ALL\" property, separate the items by
3740 spaces.")
3742 (defcustom org-global-properties nil
3743 "List of property/value pairs that can be inherited by any entry.
3745 This list will be combined with the constant `org-global-properties-fixed'.
3747 The entries in this list are cons cells where the car is a property
3748 name and cdr is a string with the value.
3750 You can set buffer-local values for the same purpose in the variable
3751 `org-file-properties' this by adding lines like
3753 #+PROPERTY: NAME VALUE"
3754 :group 'org-properties
3755 :type '(repeat
3756 (cons (string :tag "Property")
3757 (string :tag "Value"))))
3759 (defvar-local org-file-properties nil
3760 "List of property/value pairs that can be inherited by any entry.
3761 Valid for the current buffer.
3762 This variable is populated from #+PROPERTY lines.")
3764 (defgroup org-agenda nil
3765 "Options concerning agenda views in Org mode."
3766 :tag "Org Agenda"
3767 :group 'org)
3769 (defvar-local org-category nil
3770 "Variable used by org files to set a category for agenda display.
3771 Such files should use a file variable to set it, for example
3773 # -*- mode: org; org-category: \"ELisp\"
3775 or contain a special line
3777 #+CATEGORY: ELisp
3779 If the file does not specify a category, then file's base name
3780 is used instead.")
3781 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3783 (defcustom org-agenda-files nil
3784 "The files to be used for agenda display.
3786 If an entry is a directory, all files in that directory that are matched
3787 by `org-agenda-file-regexp' will be part of the file list.
3789 If the value of the variable is not a list but a single file name, then
3790 the list of agenda files is actually stored and maintained in that file,
3791 one agenda file per line. In this file paths can be given relative to
3792 `org-directory'. Tilde expansion and environment variable substitution
3793 are also made.
3795 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3796 and removed with `\\[org-remove-file]'."
3797 :group 'org-agenda
3798 :type '(choice
3799 (repeat :tag "List of files and directories" file)
3800 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3802 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3803 "Regular expression to match files for `org-agenda-files'.
3804 If any element in the list in that variable contains a directory instead
3805 of a normal file, all files in that directory that are matched by this
3806 regular expression will be included."
3807 :group 'org-agenda
3808 :type 'regexp)
3810 (defcustom org-agenda-text-search-extra-files nil
3811 "List of extra files to be searched by text search commands.
3812 These files will be searched in addition to the agenda files by the
3813 commands `org-search-view' (`\\[org-agenda] s') \
3814 and `org-occur-in-agenda-files'.
3815 Note that these files will only be searched for text search commands,
3816 not for the other agenda views like todo lists, tag searches or the weekly
3817 agenda. This variable is intended to list notes and possibly archive files
3818 that should also be searched by these two commands.
3819 In fact, if the first element in the list is the symbol `agenda-archives',
3820 then all archive files of all agenda files will be added to the search
3821 scope."
3822 :group 'org-agenda
3823 :type '(set :greedy t
3824 (const :tag "Agenda Archives" agenda-archives)
3825 (repeat :inline t (file))))
3827 (defvaralias 'org-agenda-multi-occur-extra-files
3828 'org-agenda-text-search-extra-files)
3830 (defcustom org-agenda-skip-unavailable-files nil
3831 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3832 A nil value means to remove them, after a query, from the list."
3833 :group 'org-agenda
3834 :type 'boolean)
3836 (defcustom org-calendar-to-agenda-key [?c]
3837 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3838 The command `org-calendar-goto-agenda' will be bound to this key. The
3839 default is the character `c' because then `c' can be used to switch back and
3840 forth between agenda and calendar."
3841 :group 'org-agenda
3842 :type 'sexp)
3844 (defcustom org-calendar-insert-diary-entry-key [?i]
3845 "The key to be installed in `calendar-mode-map' for adding diary entries.
3846 This option is irrelevant until `org-agenda-diary-file' has been configured
3847 to point to an Org file. When that is the case, the command
3848 `org-agenda-diary-entry' will be bound to the key given here, by default
3849 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3850 if you want to continue doing this, you need to change this to a different
3851 key."
3852 :group 'org-agenda
3853 :type 'sexp)
3855 (defcustom org-agenda-diary-file 'diary-file
3856 "File to which to add new entries with the `i' key in agenda and calendar.
3857 When this is the symbol `diary-file', the functionality in the Emacs
3858 calendar will be used to add entries to the `diary-file'. But when this
3859 points to a file, `org-agenda-diary-entry' will be used instead."
3860 :group 'org-agenda
3861 :type '(choice
3862 (const :tag "The standard Emacs diary file" diary-file)
3863 (file :tag "Special Org file diary entries")))
3865 (eval-after-load "calendar"
3866 '(progn
3867 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3868 'org-calendar-goto-agenda)
3869 (add-hook 'calendar-mode-hook
3870 (lambda ()
3871 (unless (eq org-agenda-diary-file 'diary-file)
3872 (define-key calendar-mode-map
3873 org-calendar-insert-diary-entry-key
3874 'org-agenda-diary-entry))))))
3876 (defgroup org-latex nil
3877 "Options for embedding LaTeX code into Org mode."
3878 :tag "Org LaTeX"
3879 :group 'org)
3881 (defcustom org-format-latex-options
3882 '(:foreground default :background default :scale 1.0
3883 :html-foreground "Black" :html-background "Transparent"
3884 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3885 "Options for creating images from LaTeX fragments.
3886 This is a property list with the following properties:
3887 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3888 `default' means use the foreground of the default face.
3889 `auto' means use the foreground from the text face.
3890 :background the background color, or \"Transparent\".
3891 `default' means use the background of the default face.
3892 `auto' means use the background from the text face.
3893 :scale a scaling factor for the size of the images, to get more pixels
3894 :html-foreground, :html-background, :html-scale
3895 the same numbers for HTML export.
3896 :matchers a list indicating which matchers should be used to
3897 find LaTeX fragments. Valid members of this list are:
3898 \"begin\" find environments
3899 \"$1\" find single characters surrounded by $.$
3900 \"$\" find math expressions surrounded by $...$
3901 \"$$\" find math expressions surrounded by $$....$$
3902 \"\\(\" find math expressions surrounded by \\(...\\)
3903 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3904 :group 'org-latex
3905 :type 'plist)
3907 (defcustom org-format-latex-signal-error t
3908 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3909 When nil, just push out a message."
3910 :group 'org-latex
3911 :version "24.1"
3912 :type 'boolean)
3914 (defcustom org-latex-to-mathml-jar-file nil
3915 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3916 Use this to specify additional executable file say a jar file.
3918 When using MathToWeb as the converter, specify the full-path to
3919 your mathtoweb.jar file."
3920 :group 'org-latex
3921 :version "24.1"
3922 :type '(choice
3923 (const :tag "None" nil)
3924 (file :tag "JAR file" :must-match t)))
3926 (defcustom org-latex-to-mathml-convert-command nil
3927 "Command to convert LaTeX fragments to MathML.
3928 Replace format-specifiers in the command as noted below and use
3929 `shell-command' to convert LaTeX to MathML.
3930 %j: Executable file in fully expanded form as specified by
3931 `org-latex-to-mathml-jar-file'.
3932 %I: Input LaTeX file in fully expanded form.
3933 %i: The latex fragment to be converted.
3934 %o: Output MathML file.
3936 This command is used by `org-create-math-formula'.
3938 When using MathToWeb as the converter, set this option to
3939 \"java -jar %j -unicode -force -df %o %I\".
3941 When using LaTeXML set this option to
3942 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3943 :group 'org-latex
3944 :version "24.1"
3945 :type '(choice
3946 (const :tag "None" nil)
3947 (string :tag "\nShell command")))
3949 (defcustom org-preview-latex-default-process 'dvipng
3950 "The default process to convert LaTeX fragments to image files.
3951 All available processes and theirs documents can be found in
3952 `org-preview-latex-process-alist', which see."
3953 :group 'org-latex
3954 :version "26.1"
3955 :package-version '(Org . "9.0")
3956 :type 'symbol)
3958 (defcustom org-preview-latex-process-alist
3959 '((dvipng
3960 :programs ("latex" "dvipng")
3961 :description "dvi > png"
3962 :message "you need to install the programs: latex and dvipng."
3963 :image-input-type "dvi"
3964 :image-output-type "png"
3965 :image-size-adjust (1.0 . 1.0)
3966 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3967 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3968 (dvisvgm
3969 :programs ("latex" "dvisvgm")
3970 :description "dvi > svg"
3971 :message "you need to install the programs: latex and dvisvgm."
3972 :use-xcolor t
3973 :image-input-type "dvi"
3974 :image-output-type "svg"
3975 :image-size-adjust (1.7 . 1.5)
3976 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3977 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3978 (imagemagick
3979 :programs ("latex" "convert")
3980 :description "pdf > png"
3981 :message "you need to install the programs: latex and imagemagick."
3982 :use-xcolor t
3983 :image-input-type "pdf"
3984 :image-output-type "png"
3985 :image-size-adjust (1.0 . 1.0)
3986 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3987 :image-converter
3988 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3989 "Definitions of external processes for LaTeX previewing.
3990 Org mode can use some external commands to generate TeX snippet's images for
3991 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3992 `org-create-formula-image' how to call them.
3994 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3995 PROPERTIES accepts the following attributes:
3997 :programs list of strings, required programs.
3998 :description string, describe the process.
3999 :message string, message it when required programs cannot be found.
4000 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4001 :image-output-type string, output file type of image converter (e.g., \"png\").
4002 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4003 deal with background and foreground color of image.
4004 Otherwise, dvipng style background and foreground color
4005 format are generated. You may then refer to them in
4006 command options with \"%F\" and \"%B\".
4007 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4008 image size showed in buffer and the cdr element is for
4009 HTML file. This option is only useful for process
4010 developers, users should use variable
4011 `org-format-latex-options' instead.
4012 :post-clean list of strings, files matched are to be cleaned up once
4013 the image is generated. When nil, the files with \".dvi\",
4014 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4015 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4016 be cleaned up.
4017 :latex-header list of strings, the LaTeX header of the snippet file.
4018 When nil, the fallback value is used instead, which is
4019 controlled by `org-format-latex-header',
4020 `org-latex-default-packages-alist' and
4021 `org-latex-packages-alist', which see.
4022 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4023 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4024 replaced with values defined below.
4025 :image-converter list of image converter commands strings. Each of them is
4026 given to the shell and supports any of the following
4027 place-holders defined below.
4029 Place-holders used by `:image-converter' and `:latex-compiler':
4031 %f input file name
4032 %b base name of input file
4033 %o base directory of input file
4034 %O absolute output file name
4036 Place-holders only used by `:image-converter':
4038 %F foreground of image
4039 %B background of image
4040 %D dpi, which is used to adjust image size by some processing commands.
4041 %S the image size scale ratio, which is used to adjust image size by some
4042 processing commands."
4043 :group 'org-latex
4044 :version "26.1"
4045 :package-version '(Org . "9.0")
4046 :type '(alist :tag "LaTeX to image backends"
4047 :value-type (plist)))
4049 (defcustom org-preview-latex-image-directory "ltximg/"
4050 "Path to store latex preview images.
4051 A relative path here creates many directories relative to the
4052 processed org files paths. An absolute path puts all preview
4053 images at the same place."
4054 :group 'org-latex
4055 :version "26.1"
4056 :package-version '(Org . "9.0")
4057 :type 'string)
4059 (defun org-format-latex-mathml-available-p ()
4060 "Return t if `org-latex-to-mathml-convert-command' is usable."
4061 (save-match-data
4062 (when (and (boundp 'org-latex-to-mathml-convert-command)
4063 org-latex-to-mathml-convert-command)
4064 (let ((executable (car (split-string
4065 org-latex-to-mathml-convert-command))))
4066 (when (executable-find executable)
4067 (if (string-match
4068 "%j" org-latex-to-mathml-convert-command)
4069 (file-readable-p org-latex-to-mathml-jar-file)
4070 t))))))
4072 (defcustom org-format-latex-header "\\documentclass{article}
4073 \\usepackage[usenames]{color}
4074 \[PACKAGES]
4075 \[DEFAULT-PACKAGES]
4076 \\pagestyle{empty} % do not remove
4077 % The settings below are copied from fullpage.sty
4078 \\setlength{\\textwidth}{\\paperwidth}
4079 \\addtolength{\\textwidth}{-3cm}
4080 \\setlength{\\oddsidemargin}{1.5cm}
4081 \\addtolength{\\oddsidemargin}{-2.54cm}
4082 \\setlength{\\evensidemargin}{\\oddsidemargin}
4083 \\setlength{\\textheight}{\\paperheight}
4084 \\addtolength{\\textheight}{-\\headheight}
4085 \\addtolength{\\textheight}{-\\headsep}
4086 \\addtolength{\\textheight}{-\\footskip}
4087 \\addtolength{\\textheight}{-3cm}
4088 \\setlength{\\topmargin}{1.5cm}
4089 \\addtolength{\\topmargin}{-2.54cm}"
4090 "The document header used for processing LaTeX fragments.
4091 It is imperative that this header make sure that no page number
4092 appears on the page. The package defined in the variables
4093 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4094 will either replace the placeholder \"[PACKAGES]\" in this
4095 header, or they will be appended."
4096 :group 'org-latex
4097 :type 'string)
4099 (defun org-set-packages-alist (var val)
4100 "Set the packages alist and make sure it has 3 elements per entry."
4101 (set var (mapcar (lambda (x)
4102 (if (and (consp x) (= (length x) 2))
4103 (list (car x) (nth 1 x) t)
4105 val)))
4107 (defun org-get-packages-alist (var)
4108 "Get the packages alist and make sure it has 3 elements per entry."
4109 (mapcar (lambda (x)
4110 (if (and (consp x) (= (length x) 2))
4111 (list (car x) (nth 1 x) t)
4113 (default-value var)))
4115 (defcustom org-latex-default-packages-alist
4116 '(("AUTO" "inputenc" t ("pdflatex"))
4117 ("T1" "fontenc" t ("pdflatex"))
4118 ("" "graphicx" t)
4119 ("" "grffile" t)
4120 ("" "longtable" nil)
4121 ("" "wrapfig" nil)
4122 ("" "rotating" nil)
4123 ("normalem" "ulem" t)
4124 ("" "amsmath" t)
4125 ("" "textcomp" t)
4126 ("" "amssymb" t)
4127 ("" "capt-of" nil)
4128 ("" "hyperref" nil))
4129 "Alist of default packages to be inserted in the header.
4131 Change this only if one of the packages here causes an
4132 incompatibility with another package you are using.
4134 The packages in this list are needed by one part or another of
4135 Org mode to function properly:
4137 - inputenc, fontenc: for basic font and character selection
4138 - graphicx: for including images
4139 - grffile: allow periods and spaces in graphics file names
4140 - longtable: For multipage tables
4141 - wrapfig: for figure placement
4142 - rotating: for sideways figures and tables
4143 - ulem: for underline and strike-through
4144 - amsmath: for subscript and superscript and math environments
4145 - textcomp, amssymb: for various symbols used
4146 for interpreting the entities in `org-entities'. You can skip
4147 some of these packages if you don't use any of their symbols.
4148 - capt-of: for captions outside of floats
4149 - hyperref: for cross references
4151 Therefore you should not modify this variable unless you know
4152 what you are doing. The one reason to change it anyway is that
4153 you might be loading some other package that conflicts with one
4154 of the default packages. Each element is either a cell or
4155 a string.
4157 A cell is of the format
4159 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4161 If SNIPPET-FLAG is non-nil, the package also needs to be included
4162 when compiling LaTeX snippets into images for inclusion into
4163 non-LaTeX output. COMPILERS is a list of compilers that should
4164 include the package, see `org-latex-compiler'. If the document
4165 compiler is not in the list, and the list is non-nil, the package
4166 will not be inserted in the final document.
4168 A string will be inserted as-is in the header of the document."
4169 :group 'org-latex
4170 :group 'org-export-latex
4171 :set 'org-set-packages-alist
4172 :get 'org-get-packages-alist
4173 :version "26.1"
4174 :package-version '(Org . "8.3")
4175 :type '(repeat
4176 (choice
4177 (list :tag "options/package pair"
4178 (string :tag "options")
4179 (string :tag "package")
4180 (boolean :tag "Snippet"))
4181 (string :tag "A line of LaTeX"))))
4183 (defcustom org-latex-packages-alist nil
4184 "Alist of packages to be inserted in every LaTeX header.
4186 These will be inserted after `org-latex-default-packages-alist'.
4187 Each element is either a cell or a string.
4189 A cell is of the format:
4191 (\"options\" \"package\" SNIPPET-FLAG)
4193 SNIPPET-FLAG, when non-nil, indicates that this package is also
4194 needed when turning LaTeX snippets into images for inclusion into
4195 non-LaTeX output.
4197 A string will be inserted as-is in the header of the document.
4199 Make sure that you only list packages here which:
4201 - you want in every file;
4202 - do not conflict with the setup in `org-format-latex-header';
4203 - do not conflict with the default packages in
4204 `org-latex-default-packages-alist'."
4205 :group 'org-latex
4206 :group 'org-export-latex
4207 :set 'org-set-packages-alist
4208 :get 'org-get-packages-alist
4209 :type '(repeat
4210 (choice
4211 (list :tag "options/package pair"
4212 (string :tag "options")
4213 (string :tag "package")
4214 (boolean :tag "Snippet"))
4215 (string :tag "A line of LaTeX"))))
4217 (defgroup org-appearance nil
4218 "Settings for Org mode appearance."
4219 :tag "Org Appearance"
4220 :group 'org)
4222 (defcustom org-level-color-stars-only nil
4223 "Non-nil means fontify only the stars in each headline.
4224 When nil, the entire headline is fontified.
4225 Changing it requires restart of `font-lock-mode' to become effective
4226 also in regions already fontified."
4227 :group 'org-appearance
4228 :type 'boolean)
4230 (defcustom org-hide-leading-stars nil
4231 "Non-nil means hide the first N-1 stars in a headline.
4232 This works by using the face `org-hide' for these stars. This
4233 face is white for a light background, and black for a dark
4234 background. You may have to customize the face `org-hide' to
4235 make this work.
4236 Changing it requires restart of `font-lock-mode' to become effective
4237 also in regions already fontified.
4238 You may also set this on a per-file basis by adding one of the following
4239 lines to the buffer:
4241 #+STARTUP: hidestars
4242 #+STARTUP: showstars"
4243 :group 'org-appearance
4244 :type 'boolean)
4246 (defcustom org-hidden-keywords nil
4247 "List of symbols corresponding to keywords to be hidden the org buffer.
4248 For example, a value \\='(title) for this list will make the document's title
4249 appear in the buffer without the initial #+TITLE: keyword."
4250 :group 'org-appearance
4251 :version "24.1"
4252 :type '(set (const :tag "#+AUTHOR" author)
4253 (const :tag "#+DATE" date)
4254 (const :tag "#+EMAIL" email)
4255 (const :tag "#+TITLE" title)))
4257 (defcustom org-custom-properties nil
4258 "List of properties (as strings) with a special meaning.
4259 The default use of these custom properties is to let the user
4260 hide them with `org-toggle-custom-properties-visibility'."
4261 :group 'org-properties
4262 :group 'org-appearance
4263 :version "24.3"
4264 :type '(repeat (string :tag "Property Name")))
4266 (defcustom org-fontify-done-headline nil
4267 "Non-nil means change the face of a headline if it is marked DONE.
4268 Normally, only the TODO/DONE keyword indicates the state of a headline.
4269 When this is non-nil, the headline after the keyword is set to the
4270 `org-headline-done' as an additional indication."
4271 :group 'org-appearance
4272 :type 'boolean)
4274 (defcustom org-fontify-emphasized-text t
4275 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4276 Changing this variable requires a restart of Emacs to take effect."
4277 :group 'org-appearance
4278 :type 'boolean)
4280 (defcustom org-fontify-whole-heading-line nil
4281 "Non-nil means fontify the whole line for headings.
4282 This is useful when setting a background color for the
4283 org-level-* faces."
4284 :group 'org-appearance
4285 :type 'boolean)
4287 (defcustom org-highlight-latex-and-related nil
4288 "Non-nil means highlight LaTeX related syntax in the buffer.
4289 When non nil, the value should be a list containing any of the
4290 following symbols:
4291 `latex' Highlight LaTeX snippets and environments.
4292 `script' Highlight subscript and superscript.
4293 `entities' Highlight entities."
4294 :group 'org-appearance
4295 :version "24.4"
4296 :package-version '(Org . "8.0")
4297 :type '(choice
4298 (const :tag "No highlighting" nil)
4299 (set :greedy t :tag "Highlight"
4300 (const :tag "LaTeX snippets and environments" latex)
4301 (const :tag "Subscript and superscript" script)
4302 (const :tag "Entities" entities))))
4304 (defcustom org-hide-emphasis-markers nil
4305 "Non-nil mean font-lock should hide the emphasis marker characters."
4306 :group 'org-appearance
4307 :type 'boolean)
4309 (defcustom org-hide-macro-markers nil
4310 "Non-nil mean font-lock should hide the brackets marking macro calls."
4311 :group 'org-appearance
4312 :type 'boolean)
4314 (defcustom org-pretty-entities nil
4315 "Non-nil means show entities as UTF8 characters.
4316 When nil, the \\name form remains in the buffer."
4317 :group 'org-appearance
4318 :version "24.1"
4319 :type 'boolean)
4321 (defcustom org-pretty-entities-include-sub-superscripts t
4322 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4323 :group 'org-appearance
4324 :version "24.1"
4325 :type 'boolean)
4327 (defvar org-emph-re nil
4328 "Regular expression for matching emphasis.
4329 After a match, the match groups contain these elements:
4330 0 The match of the full regular expression, including the characters
4331 before and after the proper match
4332 1 The character before the proper match, or empty at beginning of line
4333 2 The proper match, including the leading and trailing markers
4334 3 The leading marker like * or /, indicating the type of highlighting
4335 4 The text between the emphasis markers, not including the markers
4336 5 The character after the match, empty at the end of a line")
4338 (defvar org-verbatim-re nil
4339 "Regular expression for matching verbatim text.")
4341 (defvar org-emphasis-regexp-components) ; defined just below
4342 (defvar org-emphasis-alist) ; defined just below
4343 (defun org-set-emph-re (var val)
4344 "Set variable and compute the emphasis regular expression."
4345 (set var val)
4346 (when (and (boundp 'org-emphasis-alist)
4347 (boundp 'org-emphasis-regexp-components)
4348 org-emphasis-alist org-emphasis-regexp-components)
4349 (pcase-let*
4350 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4351 (body (if (<= nl 0) body
4352 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4353 (template
4354 (format (concat "\\([%s]\\|^\\)" ;before markers
4355 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4356 "\\([%s]\\|$\\)") ;after markers
4357 pre border border body border post)))
4358 (setq org-emph-re (format template "*/_+"))
4359 (setq org-verbatim-re (format template "=~")))))
4361 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4362 ;; set this option proved cumbersome. See this message/thread:
4363 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4364 (defvar org-emphasis-regexp-components
4365 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4366 "Components used to build the regular expression for emphasis.
4367 This is a list with five entries. Terminology: In an emphasis string
4368 like \" *strong word* \", we call the initial space PREMATCH, the final
4369 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4370 and \"trong wor\" is the body. The different components in this variable
4371 specify what is allowed/forbidden in each part:
4373 pre Chars allowed as prematch. Beginning of line will be allowed too.
4374 post Chars allowed as postmatch. End of line will be allowed too.
4375 border The chars *forbidden* as border characters.
4376 body-regexp A regexp like \".\" to match a body character. Don't use
4377 non-shy groups here, and don't allow newline here.
4378 newline The maximum number of newlines allowed in an emphasis exp.
4380 You need to reload Org or to restart Emacs after customizing this.")
4382 (defcustom org-emphasis-alist
4383 '(("*" bold)
4384 ("/" italic)
4385 ("_" underline)
4386 ("=" org-verbatim verbatim)
4387 ("~" org-code verbatim)
4388 ("+" (:strike-through t)))
4389 "Alist of characters and faces to emphasize text.
4390 Text starting and ending with a special character will be emphasized,
4391 for example *bold*, _underlined_ and /italic/. This variable sets the
4392 marker characters and the face to be used by font-lock for highlighting
4393 in Org buffers.
4395 You need to reload Org or to restart Emacs after customizing this."
4396 :group 'org-appearance
4397 :set 'org-set-emph-re
4398 :version "24.4"
4399 :package-version '(Org . "8.0")
4400 :type '(repeat
4401 (list
4402 (string :tag "Marker character")
4403 (choice
4404 (face :tag "Font-lock-face")
4405 (plist :tag "Face property list"))
4406 (option (const verbatim)))))
4408 (defvar org-protecting-blocks '("src" "example" "export")
4409 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4410 This is needed for font-lock setup.")
4412 ;;; Functions and variables from their packages
4413 ;; Declared here to avoid compiler warnings
4414 (defvar mark-active)
4416 ;; Various packages
4417 (declare-function calc-eval "calc" (str &optional separator &rest args))
4418 (declare-function calendar-forward-day "cal-move" (arg))
4419 (declare-function calendar-goto-date "cal-move" (date))
4420 (declare-function calendar-goto-today "cal-move" ())
4421 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4422 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4423 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4424 (declare-function cdlatex-tab "ext:cdlatex" ())
4425 (declare-function dired-get-filename
4426 "dired"
4427 (&optional localp no-error-if-not-filep))
4428 (declare-function iswitchb-read-buffer
4429 "iswitchb"
4430 (prompt &optional
4431 default require-match _predicate start matches-set))
4432 (declare-function org-agenda-change-all-lines
4433 "org-agenda"
4434 (newhead hdmarker &optional fixface just-this))
4435 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4436 "org-agenda"
4437 (&optional end))
4438 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4439 (declare-function org-agenda-format-item
4440 "org-agenda"
4441 (extra txt &optional level category tags dotime
4442 remove-re habitp))
4443 (declare-function org-agenda-maybe-redo "org-agenda" ())
4444 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4445 (declare-function org-agenda-save-markers-for-cut-and-paste
4446 "org-agenda"
4447 (beg end))
4448 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4449 (declare-function org-agenda-skip "org-agenda" ())
4450 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4451 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4452 (declare-function org-indent-mode "org-indent" (&optional arg))
4453 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4454 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4455 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4456 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4457 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4458 (declare-function parse-time-string "parse-time" (string))
4459 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4461 (defvar align-mode-rules-list)
4462 (defvar calc-embedded-close-formula)
4463 (defvar calc-embedded-open-formula)
4464 (defvar calc-embedded-open-mode)
4465 (defvar font-lock-unfontify-region-function)
4466 (defvar iswitchb-temp-buflist)
4467 (defvar org-agenda-tags-todo-honor-ignore-options)
4468 (defvar remember-data-file)
4469 (defvar texmathp-why)
4471 ;;;###autoload
4472 (defun turn-on-orgtbl ()
4473 "Unconditionally turn on `orgtbl-mode'."
4474 (require 'org-table)
4475 (orgtbl-mode 1))
4477 (defun org-at-table-p (&optional table-type)
4478 "Non-nil if the cursor is inside an Org table.
4479 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4480 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4481 (or (not (derived-mode-p 'org-mode))
4482 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4483 (and e (or table-type
4484 (eq 'org (org-element-property :type e))))))))
4486 (defun org-at-table.el-p ()
4487 "Non-nil when point is at a table.el table."
4488 (and (org-match-line "[ \t]*[|+]")
4489 (let ((element (org-element-at-point)))
4490 (and (eq (org-element-type element) 'table)
4491 (eq (org-element-property :type element) 'table.el)))))
4493 (defun org-at-table-hline-p ()
4494 "Non-nil when point is inside a hline in a table.
4495 Assume point is already in a table."
4496 (org-match-line org-table-hline-regexp))
4498 (defun org-table-map-tables (function &optional quietly)
4499 "Apply FUNCTION to the start of all tables in the buffer."
4500 (org-with-wide-buffer
4501 (goto-char (point-min))
4502 (while (re-search-forward org-table-any-line-regexp nil t)
4503 (unless quietly
4504 (message "Mapping tables: %d%%"
4505 (floor (* 100.0 (point)) (buffer-size))))
4506 (beginning-of-line 1)
4507 (when (and (looking-at org-table-line-regexp)
4508 ;; Exclude tables in src/example/verbatim/clocktable blocks
4509 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4510 (save-excursion (funcall function))
4511 (or (looking-at org-table-line-regexp)
4512 (forward-char 1)))
4513 (re-search-forward org-table-any-border-regexp nil 1)))
4514 (unless quietly (message "Mapping tables: done")))
4516 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4517 (declare-function org-clock-update-mode-line "org-clock" ())
4518 (declare-function org-resolve-clocks "org-clock"
4519 (&optional also-non-dangling-p prompt last-valid))
4521 (defun org-at-TBLFM-p (&optional pos)
4522 "Non-nil when point (or POS) is in #+TBLFM line."
4523 (save-excursion
4524 (goto-char (or pos (point)))
4525 (beginning-of-line)
4526 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4527 (eq (org-element-type (org-element-at-point)) 'table))))
4529 (defvar org-clock-start-time)
4530 (defvar org-clock-marker (make-marker)
4531 "Marker recording the last clock-in.")
4532 (defvar org-clock-hd-marker (make-marker)
4533 "Marker recording the last clock-in, but the headline position.")
4534 (defvar org-clock-heading ""
4535 "The heading of the current clock entry.")
4536 (defun org-clock-is-active ()
4537 "Return the buffer where the clock is currently running.
4538 Return nil if no clock is running."
4539 (marker-buffer org-clock-marker))
4541 (defun org-check-running-clock ()
4542 "Check if the current buffer contains the running clock.
4543 If yes, offer to stop it and to save the buffer with the changes."
4544 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4545 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4546 (buffer-name))))
4547 (org-clock-out)
4548 (when (y-or-n-p "Save changed buffer?")
4549 (save-buffer))))
4551 (defun org-clocktable-try-shift (dir n)
4552 "Check if this line starts a clock table, if yes, shift the time block."
4553 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4554 (org-clocktable-shift dir n)))
4556 ;;;###autoload
4557 (defun org-clock-persistence-insinuate ()
4558 "Set up hooks for clock persistence."
4559 (require 'org-clock)
4560 (add-hook 'org-mode-hook 'org-clock-load)
4561 (add-hook 'kill-emacs-hook 'org-clock-save))
4563 (defgroup org-archive nil
4564 "Options concerning archiving in Org mode."
4565 :tag "Org Archive"
4566 :group 'org-structure)
4568 (defcustom org-archive-location "%s_archive::"
4569 "The location where subtrees should be archived.
4571 The value of this variable is a string, consisting of two parts,
4572 separated by a double-colon. The first part is a filename and
4573 the second part is a headline.
4575 When the filename is omitted, archiving happens in the same file.
4576 %s in the filename will be replaced by the current file
4577 name (without the directory part). Archiving to a different file
4578 is useful to keep archived entries from contributing to the
4579 Org Agenda.
4581 The archived entries will be filed as subtrees of the specified
4582 headline. When the headline is omitted, the subtrees are simply
4583 filed away at the end of the file, as top-level entries. Also in
4584 the heading you can use %s to represent the file name, this can be
4585 useful when using the same archive for a number of different files.
4587 Here are a few examples:
4588 \"%s_archive::\"
4589 If the current file is Projects.org, archive in file
4590 Projects.org_archive, as top-level trees. This is the default.
4592 \"::* Archived Tasks\"
4593 Archive in the current file, under the top-level headline
4594 \"* Archived Tasks\".
4596 \"~/org/archive.org::\"
4597 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4599 \"~/org/archive.org::* From %s\"
4600 Archive in file ~/org/archive.org (absolute path), under headlines
4601 \"From FILENAME\" where file name is the current file name.
4603 \"~/org/datetree.org::datetree/* Finished Tasks\"
4604 The \"datetree/\" string is special, signifying to archive
4605 items to the datetree. Items are placed in either the CLOSED
4606 date of the item, or the current date if there is no CLOSED date.
4607 The heading will be a subentry to the current date. There doesn't
4608 need to be a heading, but there always needs to be a slash after
4609 datetree. For example, to store archived items directly in the
4610 datetree, use \"~/org/datetree.org::datetree/\".
4612 \"basement::** Finished Tasks\"
4613 Archive in file ./basement (relative path), as level 3 trees
4614 below the level 2 heading \"** Finished Tasks\".
4616 You may set this option on a per-file basis by adding to the buffer a
4617 line like
4619 #+ARCHIVE: basement::** Finished Tasks
4621 You may also define it locally for a subtree by setting an ARCHIVE property
4622 in the entry. If such a property is found in an entry, or anywhere up
4623 the hierarchy, it will be used."
4624 :group 'org-archive
4625 :type 'string)
4627 (defcustom org-agenda-skip-archived-trees t
4628 "Non-nil means the agenda will skip any items located in archived trees.
4629 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4630 variable is no longer recommended, you should leave it at the value t.
4631 Instead, use the key `v' to cycle the archives-mode in the agenda."
4632 :group 'org-archive
4633 :group 'org-agenda-skip
4634 :type 'boolean)
4636 (defcustom org-columns-skip-archived-trees t
4637 "Non-nil means ignore archived trees when creating column view."
4638 :group 'org-archive
4639 :group 'org-properties
4640 :type 'boolean)
4642 (defcustom org-cycle-open-archived-trees nil
4643 "Non-nil means `org-cycle' will open archived trees.
4644 An archived tree is a tree marked with the tag ARCHIVE.
4645 When nil, archived trees will stay folded. You can still open them with
4646 normal outline commands like `show-all', but not with the cycling commands."
4647 :group 'org-archive
4648 :group 'org-cycle
4649 :type 'boolean)
4651 (defcustom org-sparse-tree-open-archived-trees nil
4652 "Non-nil means sparse tree construction shows matches in archived trees.
4653 When nil, matches in these trees are highlighted, but the trees are kept in
4654 collapsed state."
4655 :group 'org-archive
4656 :group 'org-sparse-trees
4657 :type 'boolean)
4659 (defcustom org-sparse-tree-default-date-type nil
4660 "The default date type when building a sparse tree.
4661 When this is nil, a date is a scheduled or a deadline timestamp.
4662 Otherwise, these types are allowed:
4664 all: all timestamps
4665 active: only active timestamps (<...>)
4666 inactive: only inactive timestamps ([...])
4667 scheduled: only scheduled timestamps
4668 deadline: only deadline timestamps"
4669 :type '(choice (const :tag "Scheduled or deadline" nil)
4670 (const :tag "All timestamps" all)
4671 (const :tag "Only active timestamps" active)
4672 (const :tag "Only inactive timestamps" inactive)
4673 (const :tag "Only scheduled timestamps" scheduled)
4674 (const :tag "Only deadline timestamps" deadline)
4675 (const :tag "Only closed timestamps" closed))
4676 :version "26.1"
4677 :package-version '(Org . "8.3")
4678 :group 'org-sparse-trees)
4680 (defun org-cycle-hide-archived-subtrees (state)
4681 "Re-hide all archived subtrees after a visibility state change.
4682 STATE should be one of the symbols listed in the docstring of
4683 `org-cycle-hook'."
4684 (when (and (not org-cycle-open-archived-trees)
4685 (not (memq state '(overview folded))))
4686 (save-excursion
4687 (let* ((globalp (memq state '(contents all)))
4688 (beg (if globalp (point-min) (point)))
4689 (end (if globalp (point-max) (org-end-of-subtree t))))
4690 (org-hide-archived-subtrees beg end)
4691 (goto-char beg)
4692 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4693 (message "%s" (substitute-command-keys
4694 "Subtree is archived and stays closed. Use \
4695 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4697 (defun org-force-cycle-archived ()
4698 "Cycle subtree even if it is archived."
4699 (interactive)
4700 (setq this-command 'org-cycle)
4701 (let ((org-cycle-open-archived-trees t))
4702 (call-interactively 'org-cycle)))
4704 (defun org-hide-archived-subtrees (beg end)
4705 "Re-hide all archived subtrees after a visibility state change."
4706 (org-with-wide-buffer
4707 (let ((case-fold-search nil)
4708 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4709 (goto-char beg)
4710 ;; Include headline point is currently on.
4711 (beginning-of-line)
4712 (while (and (< (point) end) (re-search-forward re end t))
4713 (when (member org-archive-tag (org-get-tags))
4714 (org-flag-subtree t)
4715 (org-end-of-subtree t))))))
4717 (declare-function outline-end-of-heading "outline" ())
4718 (declare-function outline-flag-region "outline" (from to flag))
4719 (defun org-flag-subtree (flag)
4720 (save-excursion
4721 (org-back-to-heading t)
4722 (outline-end-of-heading)
4723 (outline-flag-region (point)
4724 (progn (org-end-of-subtree t) (point))
4725 flag)))
4727 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4729 ;; Declare Column View Code
4731 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4732 (declare-function org-columns-compute "org-colview" (property))
4734 ;; Declare ID code
4736 (declare-function org-id-store-link "org-id")
4737 (declare-function org-id-locations-load "org-id")
4738 (declare-function org-id-locations-save "org-id")
4739 (defvar org-id-track-globally)
4741 ;;; Variables for pre-computed regular expressions, all buffer local
4743 (defvar-local org-todo-regexp nil
4744 "Matches any of the TODO state keywords.
4745 Since TODO keywords are case-sensitive, `case-fold-search' is
4746 expected to be bound to nil when matching against this regexp.")
4748 (defvar-local org-not-done-regexp nil
4749 "Matches any of the TODO state keywords except the last one.
4750 Since TODO keywords are case-sensitive, `case-fold-search' is
4751 expected to be bound to nil when matching against this regexp.")
4753 (defvar-local org-not-done-heading-regexp nil
4754 "Matches a TODO headline that is not done.
4755 Since TODO keywords are case-sensitive, `case-fold-search' is
4756 expected to be bound to nil when matching against this regexp.")
4758 (defvar-local org-todo-line-regexp nil
4759 "Matches a headline and puts TODO state into group 2 if present.
4760 Since TODO keywords are case-sensitive, `case-fold-search' is
4761 expected to be bound to nil when matching against this regexp.")
4763 (defvar-local org-complex-heading-regexp nil
4764 "Matches a headline and puts everything into groups:
4766 group 1: Stars
4767 group 2: The TODO keyword, maybe
4768 group 3: Priority cookie
4769 group 4: True headline
4770 group 5: Tags
4772 Since TODO keywords are case-sensitive, `case-fold-search' is
4773 expected to be bound to nil when matching against this regexp.")
4775 (defvar-local org-complex-heading-regexp-format nil
4776 "Printf format to make regexp to match an exact headline.
4777 This regexp will match the headline of any node which has the
4778 exact headline text that is put into the format, but may have any
4779 TODO state, priority and tags.")
4781 (defvar-local org-todo-line-tags-regexp nil
4782 "Matches a headline and puts TODO state into group 2 if present.
4783 Also put tags into group 4 if tags are present.")
4785 (defconst org-plain-time-of-day-regexp
4786 (concat
4787 "\\(\\<[012]?[0-9]"
4788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4789 "\\(--?"
4790 "\\(\\<[012]?[0-9]"
4791 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4792 "\\)?")
4793 "Regular expression to match a plain time or time range.
4794 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4795 groups carry important information:
4796 0 the full match
4797 1 the first time, range or not
4798 8 the second time, if it is a range.")
4800 (defconst org-plain-time-extension-regexp
4801 (concat
4802 "\\(\\<[012]?[0-9]"
4803 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4804 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4805 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4806 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4807 groups carry important information:
4808 0 the full match
4809 7 hours of duration
4810 9 minutes of duration")
4812 (defconst org-stamp-time-of-day-regexp
4813 (concat
4814 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4815 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4816 "\\(--?"
4817 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4818 "Regular expression to match a timestamp time or time range.
4819 After a match, the following groups carry important information:
4820 0 the full match
4821 1 date plus weekday, for back referencing to make sure both times are on the same day
4822 2 the first time, range or not
4823 4 the second time, if it is a range.")
4825 (defconst org-startup-options
4826 '(("fold" org-startup-folded t)
4827 ("overview" org-startup-folded t)
4828 ("nofold" org-startup-folded nil)
4829 ("showall" org-startup-folded nil)
4830 ("showeverything" org-startup-folded showeverything)
4831 ("content" org-startup-folded content)
4832 ("indent" org-startup-indented t)
4833 ("noindent" org-startup-indented nil)
4834 ("hidestars" org-hide-leading-stars t)
4835 ("showstars" org-hide-leading-stars nil)
4836 ("odd" org-odd-levels-only t)
4837 ("oddeven" org-odd-levels-only nil)
4838 ("align" org-startup-align-all-tables t)
4839 ("noalign" org-startup-align-all-tables nil)
4840 ("shrink" org-startup-shrink-all-tables t)
4841 ("inlineimages" org-startup-with-inline-images t)
4842 ("noinlineimages" org-startup-with-inline-images nil)
4843 ("latexpreview" org-startup-with-latex-preview t)
4844 ("nolatexpreview" org-startup-with-latex-preview nil)
4845 ("customtime" org-display-custom-times t)
4846 ("logdone" org-log-done time)
4847 ("lognotedone" org-log-done note)
4848 ("nologdone" org-log-done nil)
4849 ("lognoteclock-out" org-log-note-clock-out t)
4850 ("nolognoteclock-out" org-log-note-clock-out nil)
4851 ("logrepeat" org-log-repeat state)
4852 ("lognoterepeat" org-log-repeat note)
4853 ("logdrawer" org-log-into-drawer t)
4854 ("nologdrawer" org-log-into-drawer nil)
4855 ("logstatesreversed" org-log-states-order-reversed t)
4856 ("nologstatesreversed" org-log-states-order-reversed nil)
4857 ("nologrepeat" org-log-repeat nil)
4858 ("logreschedule" org-log-reschedule time)
4859 ("lognotereschedule" org-log-reschedule note)
4860 ("nologreschedule" org-log-reschedule nil)
4861 ("logredeadline" org-log-redeadline time)
4862 ("lognoteredeadline" org-log-redeadline note)
4863 ("nologredeadline" org-log-redeadline nil)
4864 ("logrefile" org-log-refile time)
4865 ("lognoterefile" org-log-refile note)
4866 ("nologrefile" org-log-refile nil)
4867 ("fninline" org-footnote-define-inline t)
4868 ("nofninline" org-footnote-define-inline nil)
4869 ("fnlocal" org-footnote-section nil)
4870 ("fnauto" org-footnote-auto-label t)
4871 ("fnprompt" org-footnote-auto-label nil)
4872 ("fnconfirm" org-footnote-auto-label confirm)
4873 ("fnplain" org-footnote-auto-label plain)
4874 ("fnadjust" org-footnote-auto-adjust t)
4875 ("nofnadjust" org-footnote-auto-adjust nil)
4876 ("constcgs" constants-unit-system cgs)
4877 ("constSI" constants-unit-system SI)
4878 ("noptag" org-tag-persistent-alist nil)
4879 ("hideblocks" org-hide-block-startup t)
4880 ("nohideblocks" org-hide-block-startup nil)
4881 ("beamer" org-startup-with-beamer-mode t)
4882 ("entitiespretty" org-pretty-entities t)
4883 ("entitiesplain" org-pretty-entities nil))
4884 "Variable associated with STARTUP options for org-mode.
4885 Each element is a list of three items: the startup options (as written
4886 in the #+STARTUP line), the corresponding variable, and the value to set
4887 this variable to if the option is found. An optional forth element PUSH
4888 means to push this value onto the list in the variable.")
4890 (defcustom org-group-tags t
4891 "When non-nil (the default), use group tags.
4892 This can be turned on/off through `org-toggle-tags-groups'."
4893 :group 'org-tags
4894 :group 'org-startup
4895 :type 'boolean)
4897 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4899 (defun org-toggle-tags-groups ()
4900 "Toggle support for group tags.
4901 Support for group tags is controlled by the option
4902 `org-group-tags', which is non-nil by default."
4903 (interactive)
4904 (setq org-group-tags (not org-group-tags))
4905 (cond ((and (derived-mode-p 'org-agenda-mode)
4906 org-group-tags)
4907 (org-agenda-redo))
4908 ((derived-mode-p 'org-mode)
4909 (let ((org-inhibit-startup t)) (org-mode))))
4910 (message "Groups tags support has been turned %s"
4911 (if org-group-tags "on" "off")))
4913 (defun org-set-regexps-and-options (&optional tags-only)
4914 "Precompute regular expressions used in the current buffer.
4915 When optional argument TAGS-ONLY is non-nil, only compute tags
4916 related expressions."
4917 (when (derived-mode-p 'org-mode)
4918 (let ((alist (org--setup-collect-keywords
4919 (org-make-options-regexp
4920 (append '("FILETAGS" "TAGS" "SETUPFILE")
4921 (and (not tags-only)
4922 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4923 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4924 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4925 ;; Startup options. Get this early since it does change
4926 ;; behavior for other options (e.g., tags).
4927 (let ((startup (cdr (assq 'startup alist))))
4928 (dolist (option startup)
4929 (let ((entry (assoc-string option org-startup-options t)))
4930 (when entry
4931 (let ((var (nth 1 entry))
4932 (val (nth 2 entry)))
4933 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4934 (unless (listp (symbol-value var))
4935 (set (make-local-variable var) nil))
4936 (add-to-list var val)))))))
4937 (setq-local org-file-tags
4938 (mapcar #'org-add-prop-inherited
4939 (cdr (assq 'filetags alist))))
4940 (setq org-current-tag-alist
4941 (append org-tag-persistent-alist
4942 (let ((tags (cdr (assq 'tags alist))))
4943 (if tags (org-tag-string-to-alist tags)
4944 org-tag-alist))))
4945 (setq org-tag-groups-alist
4946 (org-tag-alist-to-groups org-current-tag-alist))
4947 (unless tags-only
4948 ;; File properties.
4949 (setq-local org-file-properties (cdr (assq 'property alist)))
4950 ;; Archive location.
4951 (let ((archive (cdr (assq 'archive alist))))
4952 (when archive (setq-local org-archive-location archive)))
4953 ;; Category.
4954 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4955 (when cat
4956 (setq-local org-category (intern cat))
4957 (setq-local org-file-properties
4958 (org--update-property-plist
4959 "CATEGORY" cat org-file-properties))))
4960 ;; Columns.
4961 (let ((column (cdr (assq 'columns alist))))
4962 (when column (setq-local org-columns-default-format column)))
4963 ;; Constants.
4964 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4965 ;; Link abbreviations.
4966 (let ((links (cdr (assq 'link alist))))
4967 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4968 ;; Priorities.
4969 (let ((priorities (cdr (assq 'priorities alist))))
4970 (when priorities
4971 (setq-local org-highest-priority (nth 0 priorities))
4972 (setq-local org-lowest-priority (nth 1 priorities))
4973 (setq-local org-default-priority (nth 2 priorities))))
4974 ;; Scripts.
4975 (let ((scripts (assq 'scripts alist)))
4976 (when scripts
4977 (setq-local org-use-sub-superscripts (cdr scripts))))
4978 ;; TODO keywords.
4979 (setq-local org-todo-kwd-alist nil)
4980 (setq-local org-todo-key-alist nil)
4981 (setq-local org-todo-key-trigger nil)
4982 (setq-local org-todo-keywords-1 nil)
4983 (setq-local org-done-keywords nil)
4984 (setq-local org-todo-heads nil)
4985 (setq-local org-todo-sets nil)
4986 (setq-local org-todo-log-states nil)
4987 (let ((todo-sequences
4988 (or (nreverse (cdr (assq 'todo alist)))
4989 (let ((d (default-value 'org-todo-keywords)))
4990 (if (not (stringp (car d))) d
4991 ;; XXX: Backward compatibility code.
4992 (list (cons org-todo-interpretation d)))))))
4993 (dolist (sequence todo-sequences)
4994 (let* ((sequence (or (run-hook-with-args-until-success
4995 'org-todo-setup-filter-hook sequence)
4996 sequence))
4997 (sequence-type (car sequence))
4998 (keywords (cdr sequence))
4999 (sep (member "|" keywords))
5000 names alist)
5001 (dolist (k (remove "|" keywords))
5002 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5004 (error "Invalid TODO keyword %s" k))
5005 (let ((name (match-string 1 k))
5006 (key (match-string 2 k))
5007 (log (org-extract-log-state-settings k)))
5008 (push name names)
5009 (push (cons name (and key (string-to-char key))) alist)
5010 (when log (push log org-todo-log-states))))
5011 (let* ((names (nreverse names))
5012 (done (if sep (org-remove-keyword-keys (cdr sep))
5013 (last names)))
5014 (head (car names))
5015 (tail (list sequence-type head (car done) (org-last done))))
5016 (add-to-list 'org-todo-heads head 'append)
5017 (push names org-todo-sets)
5018 (setq org-done-keywords (append org-done-keywords done nil))
5019 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5020 (setq org-todo-key-alist
5021 (append org-todo-key-alist
5022 (and alist
5023 (append '((:startgroup))
5024 (nreverse alist)
5025 '((:endgroup))))))
5026 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5027 (setq org-todo-sets (nreverse org-todo-sets)
5028 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5029 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5030 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5031 ;; Compute the regular expressions and other local variables.
5032 ;; Using `org-outline-regexp-bol' would complicate them much,
5033 ;; because of the fixed white space at the end of that string.
5034 (unless org-done-keywords
5035 (setq org-done-keywords
5036 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5037 (setq org-not-done-keywords
5038 (org-delete-all org-done-keywords
5039 (copy-sequence org-todo-keywords-1))
5040 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5041 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5042 org-not-done-heading-regexp
5043 (format org-heading-keyword-regexp-format org-not-done-regexp)
5044 org-todo-line-regexp
5045 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5046 org-complex-heading-regexp
5047 (concat "^\\(\\*+\\)"
5048 "\\(?: +" org-todo-regexp "\\)?"
5049 "\\(?: +\\(\\[#.\\]\\)\\)?"
5050 "\\(?: +\\(.*?\\)\\)??"
5051 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5052 "[ \t]*$")
5053 org-complex-heading-regexp-format
5054 (concat "^\\(\\*+\\)"
5055 "\\(?: +" org-todo-regexp "\\)?"
5056 "\\(?: +\\(\\[#.\\]\\)\\)?"
5057 "\\(?: +"
5058 ;; Stats cookies can be stuck to body.
5059 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5060 "\\(%s\\)"
5061 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5062 "\\)"
5063 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5064 "[ \t]*$")
5065 org-todo-line-tags-regexp
5066 (concat "^\\(\\*+\\)"
5067 "\\(?: +" org-todo-regexp "\\)?"
5068 "\\(?: +\\(.*?\\)\\)??"
5069 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5070 "[ \t]*$"))
5071 (org-compute-latex-and-related-regexp)))))
5073 (defun org--setup-collect-keywords (regexp &optional files alist)
5074 "Return setup keywords values as an alist.
5076 REGEXP matches a subset of setup keywords. FILES is a list of
5077 file names already visited. It is used to avoid circular setup
5078 files. ALIST, when non-nil, is the alist computed so far.
5080 Return value contains the following keys: `archive', `category',
5081 `columns', `constants', `filetags', `link', `priorities',
5082 `property', `scripts', `startup', `tags' and `todo'."
5083 (org-with-wide-buffer
5084 (goto-char (point-min))
5085 (let ((case-fold-search t))
5086 (while (re-search-forward regexp nil t)
5087 (let ((element (org-element-at-point)))
5088 (when (eq (org-element-type element) 'keyword)
5089 (let ((key (org-element-property :key element))
5090 (value (org-element-property :value element)))
5091 (cond
5092 ((equal key "ARCHIVE")
5093 (when (org-string-nw-p value)
5094 (push (cons 'archive value) alist)))
5095 ((equal key "CATEGORY") (push (cons 'category value) alist))
5096 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5097 ((equal key "CONSTANTS")
5098 (let* ((constants (assq 'constants alist))
5099 (store (cdr constants)))
5100 (dolist (pair (split-string value))
5101 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5102 pair)
5103 (let* ((name (match-string 1 pair))
5104 (value (match-string 2 pair))
5105 (old (assoc name store)))
5106 (if old (setcdr old value)
5107 (push (cons name value) store)))))
5108 (if constants (setcdr constants store)
5109 (push (cons 'constants store) alist))))
5110 ((equal key "FILETAGS")
5111 (when (org-string-nw-p value)
5112 (let ((old (assq 'filetags alist))
5113 (new (apply #'nconc
5114 (mapcar (lambda (x) (org-split-string x ":"))
5115 (split-string value)))))
5116 (if old (setcdr old (append new (cdr old)))
5117 (push (cons 'filetags new) alist)))))
5118 ((equal key "LINK")
5119 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5120 (let ((links (assq 'link alist))
5121 (pair (cons (match-string-no-properties 1 value)
5122 (match-string-no-properties 2 value))))
5123 (if links (push pair (cdr links))
5124 (push (list 'link pair) alist)))))
5125 ((equal key "OPTIONS")
5126 (when (and (org-string-nw-p value)
5127 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5128 (push (cons 'scripts (read (match-string 1 value))) alist)))
5129 ((equal key "PRIORITIES")
5130 (push (cons 'priorities
5131 (let ((prio (split-string value)))
5132 (if (< (length prio) 3) '(?A ?C ?B)
5133 (mapcar #'string-to-char prio))))
5134 alist))
5135 ((equal key "PROPERTY")
5136 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5137 (let* ((property (assq 'property alist))
5138 (value (org--update-property-plist
5139 (match-string-no-properties 1 value)
5140 (match-string-no-properties 2 value)
5141 (cdr property))))
5142 (if property (setcdr property value)
5143 (push (cons 'property value) alist)))))
5144 ((equal key "STARTUP")
5145 (let ((startup (assq 'startup alist)))
5146 (if startup
5147 (setcdr startup
5148 (append (cdr startup) (split-string value)))
5149 (push (cons 'startup (split-string value)) alist))))
5150 ((equal key "TAGS")
5151 (let ((tag-cell (assq 'tags alist)))
5152 (if tag-cell
5153 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5154 (push (cons 'tags value) alist))))
5155 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5156 (let ((todo (assq 'todo alist))
5157 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5158 (split-string value))))
5159 (if todo (push value (cdr todo))
5160 (push (list 'todo value) alist))))
5161 ((equal key "SETUPFILE")
5162 (unless buffer-read-only ; Do not check in Gnus messages.
5163 (let ((f (and (org-string-nw-p value)
5164 (expand-file-name
5165 (org-unbracket-string "\"" "\"" value)))))
5166 (when (and f (file-readable-p f) (not (member f files)))
5167 (with-temp-buffer
5168 (setq default-directory (file-name-directory f))
5169 (insert-file-contents f)
5170 (setq alist
5171 ;; Fake Org mode to benefit from cache
5172 ;; without recurring needlessly.
5173 (let ((major-mode 'org-mode))
5174 (org--setup-collect-keywords
5175 regexp (cons f files) alist)))))))))))))))
5176 alist)
5178 (defun org-tag-string-to-alist (s)
5179 "Return tag alist associated to string S.
5180 S is a value for TAGS keyword or produced with
5181 `org-tag-alist-to-string'. Return value is an alist suitable for
5182 `org-tag-alist' or `org-tag-persistent-alist'."
5183 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5184 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5185 "\\|{.+?}\\)" ; regular expression
5186 "\\(?:(\\(.\\))\\)?\\'"))
5187 alist group-flag)
5188 (dolist (tokens lines (cdr (nreverse alist)))
5189 (push '(:newline) alist)
5190 (while tokens
5191 (let ((token (pop tokens)))
5192 (pcase token
5193 ("{"
5194 (push '(:startgroup) alist)
5195 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5196 ("}"
5197 (push '(:endgroup) alist)
5198 (setq group-flag nil))
5199 ("["
5200 (push '(:startgrouptag) alist)
5201 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5202 ("]"
5203 (push '(:endgrouptag) alist)
5204 (setq group-flag nil))
5205 (":"
5206 (push '(:grouptags) alist))
5207 ((guard (string-match tag-re token))
5208 (let ((tag (match-string 1 token))
5209 (key (and (match-beginning 2)
5210 (string-to-char (match-string 2 token)))))
5211 ;; Push all tags in groups, no matter if they already
5212 ;; appear somewhere else in the list.
5213 (when (or group-flag (not (assoc tag alist)))
5214 (push (cons tag key) alist))))))))))
5216 (defun org-tag-alist-to-string (alist &optional skip-key)
5217 "Return tag string associated to ALIST.
5219 ALIST is an alist, as defined in `org-tag-alist' or
5220 `org-tag-persistent-alist', or produced with
5221 `org-tag-string-to-alist'.
5223 Return value is a string suitable as a value for \"TAGS\"
5224 keyword.
5226 When optional argument SKIP-KEY is non-nil, skip selection keys
5227 next to tags."
5228 (mapconcat (lambda (token)
5229 (pcase token
5230 (`(:startgroup) "{")
5231 (`(:endgroup) "}")
5232 (`(:startgrouptag) "[")
5233 (`(:endgrouptag) "]")
5234 (`(:grouptags) ":")
5235 (`(:newline) "\\n")
5236 ((and
5237 (guard (not skip-key))
5238 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5239 (format "%s(%c)" tag key))
5240 (`(,(and tag (pred stringp)) . ,_) tag)
5241 (_ (user-error "Invalid tag token: %S" token))))
5242 alist
5243 " "))
5245 (defun org-tag-alist-to-groups (alist)
5246 "Return group alist from tag ALIST.
5247 ALIST is an alist, as defined in `org-tag-alist' or
5248 `org-tag-persistent-alist', or produced with
5249 `org-tag-string-to-alist'. Return value is an alist following
5250 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5251 a string, summarizing TAGS, as a list of strings."
5252 (let (groups group-status current-group)
5253 (dolist (token alist (nreverse groups))
5254 (pcase token
5255 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5256 (`(,(or :endgroup :endgrouptag))
5257 (when (eq group-status 'append)
5258 (push (nreverse current-group) groups))
5259 (setq group-status nil))
5260 (`(:grouptags) (setq group-status 'append))
5261 ((and `(,tag . ,_) (guard group-status))
5262 (if (eq group-status 'append) (push tag current-group)
5263 (setq current-group (list tag))))
5264 (_ nil)))))
5266 (defvar org--file-cache (make-hash-table :test #'equal)
5267 "Hash table to store contents of files referenced via a URL.
5268 This is the cache of file URLs read using `org-file-contents'.")
5270 (defun org-reset-file-cache ()
5271 "Reset the cache of files downloaded by `org-file-contents'."
5272 (clrhash org--file-cache))
5274 (defun org-file-url-p (file)
5275 "Non-nil if FILE is a URL."
5276 (require 'ffap)
5277 (string-match-p ffap-url-regexp file))
5279 (defun org-file-contents (file &optional noerror nocache)
5280 "Return the contents of FILE, as a string.
5282 FILE can be a file name or URL.
5284 If FILE is a URL, download the contents. If the URL contents are
5285 already cached in the `org--file-cache' hash table, the download step
5286 is skipped.
5288 If NOERROR is non-nil, ignore the error when unable to read the FILE
5289 from file or URL.
5291 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5292 is available. This option applies only if FILE is a URL."
5293 (let* ((is-url (org-file-url-p file))
5294 (cache (and is-url
5295 (not nocache)
5296 (gethash file org--file-cache))))
5297 (cond
5298 (cache)
5299 (is-url
5300 (with-current-buffer (url-retrieve-synchronously file)
5301 (goto-char (point-min))
5302 ;; Move point to after the url-retrieve header.
5303 (search-forward "\n\n" nil :move)
5304 ;; Search for the success code only in the url-retrieve header.
5305 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5306 ;; Update the cache `org--file-cache' and return contents.
5307 (puthash file
5308 (buffer-substring-no-properties (point) (point-max))
5309 org--file-cache)
5310 (funcall (if noerror #'message #'user-error)
5311 "Unable to fetch file from %S"
5312 file))))
5314 (with-temp-buffer
5315 (condition-case err
5316 (progn
5317 (insert-file-contents file)
5318 (buffer-string))
5319 (file-error
5320 (funcall (if noerror #'message #'user-error)
5321 (error-message-string err)))))))))
5323 (defun org-extract-log-state-settings (x)
5324 "Extract the log state setting from a TODO keyword string.
5325 This will extract info from a string like \"WAIT(w@/!)\"."
5326 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5327 (let ((kw (match-string 1 x))
5328 (log1 (and (match-end 3) (match-string 3 x)))
5329 (log2 (and (match-end 4) (match-string 4 x))))
5330 (and (or log1 log2)
5331 (list kw
5332 (and log1 (if (equal log1 "!") 'time 'note))
5333 (and log2 (if (equal log2 "!") 'time 'note)))))))
5335 (defun org-remove-keyword-keys (list)
5336 "Remove a pair of parenthesis at the end of each string in LIST."
5337 (mapcar (lambda (x)
5338 (if (string-match "(.*)$" x)
5339 (substring x 0 (match-beginning 0))
5341 list))
5343 (defun org-assign-fast-keys (alist)
5344 "Assign fast keys to a keyword-key alist.
5345 Respect keys that are already there."
5346 (let (new e (alt ?0))
5347 (while (setq e (pop alist))
5348 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5349 (cdr e)) ;; Key already assigned.
5350 (push e new)
5351 (let ((clist (string-to-list (downcase (car e))))
5352 (used (append new alist)))
5353 (when (= (car clist) ?@)
5354 (pop clist))
5355 (while (and clist (rassoc (car clist) used))
5356 (pop clist))
5357 (unless clist
5358 (while (rassoc alt used)
5359 (cl-incf alt)))
5360 (push (cons (car e) (or (car clist) alt)) new))))
5361 (nreverse new)))
5363 ;;; Some variables used in various places
5365 (defvar org-window-configuration nil
5366 "Used in various places to store a window configuration.")
5367 (defvar org-selected-window nil
5368 "Used in various places to store a window configuration.")
5369 (defvar org-finish-function nil
5370 "Function to be called when `C-c C-c' is used.
5371 This is for getting out of special buffers like capture.")
5372 (defvar org-last-state)
5374 ;; Defined somewhere in this file, but used before definition.
5375 (defvar org-entities) ;; defined in org-entities.el
5376 (defvar org-struct-menu)
5377 (defvar org-org-menu)
5378 (defvar org-tbl-menu)
5380 ;;;; Define the Org mode
5382 ;; We use a before-change function to check if a table might need
5383 ;; an update.
5384 (defvar org-table-may-need-update t
5385 "Indicates that a table might need an update.
5386 This variable is set by `org-before-change-function'.
5387 `org-table-align' sets it back to nil.")
5388 (defun org-before-change-function (_beg _end)
5389 "Every change indicates that a table might need an update."
5390 (setq org-table-may-need-update t))
5391 (defvar org-mode-map)
5392 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5393 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5394 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5395 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5396 (defvar org-table-buffer-is-an nil)
5398 (defvar bidi-paragraph-direction)
5399 (defvar buffer-face-mode-face)
5401 (require 'outline)
5403 ;; Other stuff we need.
5404 (require 'time-date)
5405 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5406 (require 'easymenu)
5407 (autoload 'easy-menu-add "easymenu")
5408 (require 'overlay)
5410 ;; (require 'org-macs) moved higher up in the file before it is first used
5411 (require 'org-entities)
5412 ;; (require 'org-compat) moved higher up in the file before it is first used
5413 (require 'org-faces)
5414 (require 'org-list)
5415 (require 'org-pcomplete)
5416 (require 'org-src)
5417 (require 'org-footnote)
5418 (require 'org-macro)
5420 ;; babel
5421 (require 'ob)
5423 ;;;###autoload
5424 (define-derived-mode org-mode outline-mode "Org"
5425 "Outline-based notes management and organizer, alias
5426 \"Carsten's outline-mode for keeping track of everything.\"
5428 Org mode develops organizational tasks around a NOTES file which
5429 contains information about projects as plain text. Org mode is
5430 implemented on top of Outline mode, which is ideal to keep the content
5431 of large files well structured. It supports ToDo items, deadlines and
5432 time stamps, which magically appear in the diary listing of the Emacs
5433 calendar. Tables are easily created with a built-in table editor.
5434 Plain text URL-like links connect to websites, emails (VM), Usenet
5435 messages (Gnus), BBDB entries, and any files related to the project.
5436 For printing and sharing of notes, an Org file (or a part of it)
5437 can be exported as a structured ASCII or HTML file.
5439 The following commands are available:
5441 \\{org-mode-map}"
5443 ;; Get rid of Outline menus, they are not needed
5444 ;; Need to do this here because define-derived-mode sets up
5445 ;; the keymap so late. Still, it is a waste to call this each time
5446 ;; we switch another buffer into Org mode.
5447 (define-key org-mode-map [menu-bar headings] 'undefined)
5448 (define-key org-mode-map [menu-bar hide] 'undefined)
5449 (define-key org-mode-map [menu-bar show] 'undefined)
5451 (org-load-modules-maybe)
5452 (org-install-agenda-files-menu)
5453 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5454 (add-to-invisibility-spec '(org-hide-block . t))
5455 (setq-local outline-regexp org-outline-regexp)
5456 (setq-local outline-level 'org-outline-level)
5457 (setq bidi-paragraph-direction 'left-to-right)
5458 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5459 (unless org-display-table
5460 (setq org-display-table (make-display-table)))
5461 (set-display-table-slot
5462 org-display-table 4
5463 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5464 org-ellipsis)))
5465 (setq buffer-display-table org-display-table))
5466 (org-set-regexps-and-options)
5467 (org-set-font-lock-defaults)
5468 (when (and org-tag-faces (not org-tags-special-faces-re))
5469 ;; tag faces set outside customize.... force initialization.
5470 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5471 ;; Calc embedded
5472 (setq-local calc-embedded-open-mode "# ")
5473 ;; Modify a few syntax entries
5474 (modify-syntax-entry ?@ "w")
5475 (modify-syntax-entry ?\" "\"")
5476 (modify-syntax-entry ?\\ "_")
5477 (modify-syntax-entry ?~ "_")
5478 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5479 ;; Activate before-change-function
5480 (setq-local org-table-may-need-update t)
5481 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5482 ;; Check for running clock before killing a buffer
5483 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5484 ;; Initialize macros templates.
5485 (org-macro-initialize-templates)
5486 ;; Initialize radio targets.
5487 (org-update-radio-target-regexp)
5488 ;; Indentation.
5489 (setq-local indent-line-function 'org-indent-line)
5490 (setq-local indent-region-function 'org-indent-region)
5491 ;; Filling and auto-filling.
5492 (org-setup-filling)
5493 ;; Comments.
5494 (org-setup-comments-handling)
5495 ;; Initialize cache.
5496 (org-element-cache-reset)
5497 ;; Beginning/end of defun
5498 (setq-local beginning-of-defun-function 'org-backward-element)
5499 (setq-local end-of-defun-function
5500 (lambda ()
5501 (if (not (org-at-heading-p))
5502 (org-forward-element)
5503 (org-forward-element)
5504 (forward-char -1))))
5505 ;; Next error for sparse trees
5506 (setq-local next-error-function 'org-occur-next-match)
5507 ;; Make sure dependence stuff works reliably, even for users who set it
5508 ;; too late :-(
5509 (if org-enforce-todo-dependencies
5510 (add-hook 'org-blocker-hook
5511 'org-block-todo-from-children-or-siblings-or-parent)
5512 (remove-hook 'org-blocker-hook
5513 'org-block-todo-from-children-or-siblings-or-parent))
5514 (if org-enforce-todo-checkbox-dependencies
5515 (add-hook 'org-blocker-hook
5516 'org-block-todo-from-checkboxes)
5517 (remove-hook 'org-blocker-hook
5518 'org-block-todo-from-checkboxes))
5520 ;; Align options lines
5521 (setq-local
5522 align-mode-rules-list
5523 '((org-in-buffer-settings
5524 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5525 (modes . '(org-mode)))))
5527 ;; Imenu
5528 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5530 ;; Make isearch reveal context
5531 (setq-local outline-isearch-open-invisible-function
5532 (lambda (&rest _) (org-show-context 'isearch)))
5534 ;; Setup the pcomplete hooks
5535 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5536 (setq-local pcomplete-command-name-function 'org-command-at-point)
5537 (setq-local pcomplete-default-completion-function 'ignore)
5538 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5539 (setq-local pcomplete-termination-string "")
5540 (setq-local buffer-face-mode-face 'org-default)
5542 ;; If empty file that did not turn on Org mode automatically, make
5543 ;; it to.
5544 (when (and org-insert-mode-line-in-empty-file
5545 (called-interactively-p 'any)
5546 (= (point-min) (point-max)))
5547 (insert "# -*- mode: org -*-\n\n"))
5548 (unless org-inhibit-startup
5549 (org-unmodified
5550 (when org-startup-with-beamer-mode (org-beamer-mode))
5551 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5552 (org-table-map-tables
5553 (cond ((and org-startup-align-all-tables
5554 org-startup-shrink-all-tables)
5555 (lambda () (org-table-align) (org-table-shrink)))
5556 (org-startup-align-all-tables #'org-table-align)
5557 (t #'org-table-shrink))
5559 (when org-startup-with-inline-images (org-display-inline-images))
5560 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5561 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5562 (when org-startup-truncated (setq truncate-lines t))
5563 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5564 (org-refresh-effort-properties)))
5565 ;; Try to set `org-hide' face correctly.
5566 (let ((foreground (org-find-invisible-foreground)))
5567 (when foreground
5568 (set-face-foreground 'org-hide foreground))))
5570 ;; Update `customize-package-emacs-version-alist'
5571 (add-to-list 'customize-package-emacs-version-alist
5572 '(Org ("8.0" . "24.4")
5573 ("8.1" . "24.4")
5574 ("8.2" . "24.4")
5575 ("8.2.7" . "24.4")
5576 ("8.3" . "26.1")
5577 ("9.0" . "26.1")
5578 ("9.1" . "26.1")))
5580 (defvar org-mode-transpose-word-syntax-table
5581 (let ((st (make-syntax-table text-mode-syntax-table)))
5582 (dolist (c org-emphasis-alist st)
5583 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5585 (when (fboundp 'abbrev-table-put)
5586 (abbrev-table-put org-mode-abbrev-table
5587 :parents (list text-mode-abbrev-table)))
5589 (defun org-find-invisible-foreground ()
5590 (let ((candidates (remove
5591 "unspecified-bg"
5592 (nconc
5593 (list (face-background 'default)
5594 (face-background 'org-default))
5595 (mapcar
5596 (lambda (alist)
5597 (when (boundp alist)
5598 (cdr (assq 'background-color (symbol-value alist)))))
5599 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5600 (list (face-foreground 'org-hide))))))
5601 (car (remove nil candidates))))
5603 (defun org-current-time (&optional rounding-minutes past)
5604 "Current time, possibly rounded to ROUNDING-MINUTES.
5605 When ROUNDING-MINUTES is not an integer, fall back on the car of
5606 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5607 the rounding returns a past time."
5608 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5609 (car org-time-stamp-rounding-minutes)))
5610 (time (decode-time)) res)
5611 (if (< r 1)
5612 (current-time)
5613 (setq res
5614 (apply 'encode-time
5615 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5616 (nthcdr 2 time))))
5617 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5618 (seconds-to-time (- (float-time res) (* r 60)))
5619 res))))
5621 (defun org-today ()
5622 "Return today date, considering `org-extend-today-until'."
5623 (time-to-days
5624 (time-subtract (current-time)
5625 (list 0 (* 3600 org-extend-today-until) 0))))
5627 ;;;; Font-Lock stuff, including the activators
5629 (defvar org-mouse-map (make-sparse-keymap))
5630 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5631 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5632 (when org-mouse-1-follows-link
5633 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5634 (when org-tab-follows-link
5635 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5636 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5638 (require 'font-lock)
5640 (defconst org-non-link-chars "]\t\n\r<>")
5641 (defvar org-link-types-re nil
5642 "Matches a link that has a url-like prefix like \"http:\"")
5643 (defvar org-link-re-with-space nil
5644 "Matches a link with spaces, optional angular brackets around it.")
5645 (defvar org-link-re-with-space2 nil
5646 "Matches a link with spaces, optional angular brackets around it.")
5647 (defvar org-link-re-with-space3 nil
5648 "Matches a link with spaces, only for internal part in bracket links.")
5649 (defvar org-angle-link-re nil
5650 "Matches link with angular brackets, spaces are allowed.")
5651 (defvar org-plain-link-re nil
5652 "Matches plain link, without spaces.")
5653 (defvar org-bracket-link-regexp nil
5654 "Matches a link in double brackets.")
5655 (defvar org-bracket-link-analytic-regexp nil
5656 "Regular expression used to analyze links.
5657 Here is what the match groups contain after a match:
5658 1: http:
5659 2: http
5660 3: path
5661 4: [desc]
5662 5: desc")
5663 (defvar org-bracket-link-analytic-regexp++ nil
5664 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5665 (defvar org-any-link-re nil
5666 "Regular expression matching any link.")
5668 (defconst org-match-sexp-depth 3
5669 "Number of stacked braces for sub/superscript matching.")
5671 (defun org-create-multibrace-regexp (left right n)
5672 "Create a regular expression which will match a balanced sexp.
5673 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5674 as single character strings.
5675 The regexp returned will match the entire expression including the
5676 delimiters. It will also define a single group which contains the
5677 match except for the outermost delimiters. The maximum depth of
5678 stacked delimiters is N. Escaping delimiters is not possible."
5679 (let* ((nothing (concat "[^" left right "]*?"))
5680 (or "\\|")
5681 (re nothing)
5682 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5683 (while (> n 1)
5684 (setq n (1- n)
5685 re (concat re or next)
5686 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5687 (concat left "\\(" re "\\)" right)))
5689 (defconst org-match-substring-regexp
5690 (concat
5691 "\\(\\S-\\)\\([_^]\\)\\("
5692 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5693 "\\|"
5694 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5695 "\\|"
5696 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5697 "The regular expression matching a sub- or superscript.")
5699 (defconst org-match-substring-with-braces-regexp
5700 (concat
5701 "\\(\\S-\\)\\([_^]\\)"
5702 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5703 "The regular expression matching a sub- or superscript, forcing braces.")
5705 (defun org-make-link-regexps ()
5706 "Update the link regular expressions.
5707 This should be called after the variable `org-link-parameters' has changed."
5708 (let ((types-re (regexp-opt (org-link-types) t)))
5709 (setq org-link-types-re
5710 (concat "\\`" types-re ":")
5711 org-link-re-with-space
5712 (concat "<?" types-re ":"
5713 "\\([^" org-non-link-chars " ]"
5714 "[^" org-non-link-chars "]*"
5715 "[^" org-non-link-chars " ]\\)>?")
5716 org-link-re-with-space2
5717 (concat "<?" types-re ":"
5718 "\\([^" org-non-link-chars " ]"
5719 "[^\t\n\r]*"
5720 "[^" org-non-link-chars " ]\\)>?")
5721 org-link-re-with-space3
5722 (concat "<?" types-re ":"
5723 "\\([^" org-non-link-chars " ]"
5724 "[^\t\n\r]*\\)")
5725 org-angle-link-re
5726 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5727 types-re)
5728 org-plain-link-re
5729 (concat
5730 "\\<" types-re ":"
5731 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5732 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5733 org-bracket-link-regexp
5734 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5735 org-bracket-link-analytic-regexp
5736 (concat
5737 "\\[\\["
5738 "\\(" types-re ":\\)?"
5739 "\\([^]]+\\)"
5740 "\\]"
5741 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5742 "\\]")
5743 org-bracket-link-analytic-regexp++
5744 (concat
5745 "\\[\\["
5746 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5747 "\\([^]]+\\)"
5748 "\\]"
5749 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5750 "\\]")
5751 org-any-link-re
5752 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5753 org-angle-link-re "\\)\\|\\("
5754 org-plain-link-re "\\)"))))
5756 (org-make-link-regexps)
5758 (defvar org-emph-face nil)
5760 (defun org-do-emphasis-faces (limit)
5761 "Run through the buffer and emphasize strings."
5762 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5763 (car org-emphasis-regexp-components))))
5764 (catch :exit
5765 (while (re-search-forward quick-re limit t)
5766 (let* ((marker (match-string 2))
5767 (verbatim? (member marker '("~" "="))))
5768 (when (save-excursion
5769 (goto-char (match-beginning 0))
5770 ;; Do not match headline stars. Do not consider
5771 ;; stars of a headline as closing marker for bold
5772 ;; markup either. Do not match table hlines.
5773 (and
5774 (not (looking-at-p org-outline-regexp-bol))
5775 (not (and (equal marker "+")
5776 (org-match-line
5777 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5778 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5779 (not (string-match-p
5780 (concat org-outline-regexp-bol "\\'")
5781 (match-string 0)))))
5782 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5783 (font-lock-prepend-text-property
5784 (match-beginning 2) (match-end 2) 'face face)
5785 (when verbatim?
5786 (org-remove-flyspell-overlays-in
5787 (match-beginning 0) (match-end 0)))
5788 (add-text-properties (match-beginning 2) (match-end 2)
5789 '(font-lock-multiline t org-emphasis t))
5790 (when org-hide-emphasis-markers
5791 (add-text-properties (match-end 4) (match-beginning 5)
5792 '(invisible org-link))
5793 (add-text-properties (match-beginning 3) (match-end 3)
5794 '(invisible org-link)))
5795 (throw :exit t))))))))
5797 (defun org-emphasize (&optional char)
5798 "Insert or change an emphasis, i.e. a font like bold or italic.
5799 If there is an active region, change that region to a new emphasis.
5800 If there is no region, just insert the marker characters and position
5801 the cursor between them.
5802 CHAR should be the marker character. If it is a space, it means to
5803 remove the emphasis of the selected region.
5804 If CHAR is not given (for example in an interactive call) it will be
5805 prompted for."
5806 (interactive)
5807 (let ((erc org-emphasis-regexp-components)
5808 (string "") beg end move s)
5809 (if (org-region-active-p)
5810 (setq beg (region-beginning)
5811 end (region-end)
5812 string (buffer-substring beg end))
5813 (setq move t))
5815 (unless char
5816 (message "Emphasis marker or tag: [%s]"
5817 (mapconcat #'car org-emphasis-alist ""))
5818 (setq char (read-char-exclusive)))
5819 (if (equal char ?\s)
5820 (setq s ""
5821 move nil)
5822 (unless (assoc (char-to-string char) org-emphasis-alist)
5823 (user-error "No such emphasis marker: \"%c\"" char))
5824 (setq s (char-to-string char)))
5825 (while (and (> (length string) 1)
5826 (equal (substring string 0 1) (substring string -1))
5827 (assoc (substring string 0 1) org-emphasis-alist))
5828 (setq string (substring string 1 -1)))
5829 (setq string (concat s string s))
5830 (when beg (delete-region beg end))
5831 (unless (or (bolp)
5832 (string-match (concat "[" (nth 0 erc) "\n]")
5833 (char-to-string (char-before (point)))))
5834 (insert " "))
5835 (unless (or (eobp)
5836 (string-match (concat "[" (nth 1 erc) "\n]")
5837 (char-to-string (char-after (point)))))
5838 (insert " ") (backward-char 1))
5839 (insert string)
5840 (and move (backward-char 1))))
5842 (defconst org-nonsticky-props
5843 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5845 (defsubst org-rear-nonsticky-at (pos)
5846 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5848 (defun org-activate-links (limit)
5849 "Add link properties to links.
5850 This includes angle, plain, and bracket links."
5851 (catch :exit
5852 (while (re-search-forward org-any-link-re limit t)
5853 (let* ((start (match-beginning 0))
5854 (end (match-end 0))
5855 (style (cond ((eq ?< (char-after start)) 'angle)
5856 ((eq ?\[ (char-after (1+ start))) 'bracket)
5857 (t 'plain))))
5858 (when (and (memq style org-highlight-links)
5859 ;; Do not confuse plain links with tags.
5860 (not (and (eq style 'plain)
5861 (let ((face (get-text-property
5862 (max (1- start) (point-min)) 'face)))
5863 (if (consp face) (memq 'org-tag face)
5864 (eq 'org-tag face))))))
5865 (let* ((link-object (save-excursion
5866 (goto-char start)
5867 (save-match-data (org-element-link-parser))))
5868 (link (org-element-property :raw-link link-object))
5869 (type (org-element-property :type link-object))
5870 (path (org-element-property :path link-object))
5871 (properties ;for link's visible part
5872 (list
5873 'face (pcase (org-link-get-parameter type :face)
5874 ((and (pred functionp) face) (funcall face path))
5875 ((and (pred facep) face) face)
5876 ((and (pred consp) face) face) ;anonymous
5877 (_ 'org-link))
5878 'mouse-face (or (org-link-get-parameter type :mouse-face)
5879 'highlight)
5880 'keymap (or (org-link-get-parameter type :keymap)
5881 org-mouse-map)
5882 'help-echo (pcase (org-link-get-parameter type :help-echo)
5883 ((and (pred stringp) echo) echo)
5884 ((and (pred functionp) echo) echo)
5885 (_ (concat "LINK: " link)))
5886 'htmlize-link (pcase (org-link-get-parameter type
5887 :htmlize-link)
5888 ((and (pred functionp) f) (funcall f))
5889 (_ `(:uri ,link)))
5890 'font-lock-multiline t)))
5891 (org-remove-flyspell-overlays-in start end)
5892 (org-rear-nonsticky-at end)
5893 (if (not (eq 'bracket style))
5894 (add-text-properties start end properties)
5895 ;; Handle invisible parts in bracket links.
5896 (remove-text-properties start end '(invisible nil))
5897 (let ((hidden
5898 (append `(invisible
5899 ,(or (org-link-get-parameter type :display)
5900 'org-link))
5901 properties))
5902 (visible-start (or (match-beginning 4) (match-beginning 2)))
5903 (visible-end (or (match-end 4) (match-end 2))))
5904 (add-text-properties start visible-start hidden)
5905 (add-text-properties visible-start visible-end properties)
5906 (add-text-properties visible-end end hidden)
5907 (org-rear-nonsticky-at visible-start)
5908 (org-rear-nonsticky-at visible-end)))
5909 (let ((f (org-link-get-parameter type :activate-func)))
5910 (when (functionp f)
5911 (funcall f start end path (eq style 'bracket))))
5912 (throw :exit t))))) ;signal success
5913 nil))
5915 (defun org-activate-code (limit)
5916 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5917 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5918 (remove-text-properties (match-beginning 0) (match-end 0)
5919 '(display t invisible t intangible t))
5922 (defcustom org-src-fontify-natively t
5923 "When non-nil, fontify code in code blocks.
5924 See also the `org-block' face."
5925 :type 'boolean
5926 :version "26.1"
5927 :package-version '(Org . "8.3")
5928 :group 'org-appearance
5929 :group 'org-babel)
5931 (defcustom org-allow-promoting-top-level-subtree nil
5932 "When non-nil, allow promoting a top level subtree.
5933 The leading star of the top level headline will be replaced
5934 by a #."
5935 :type 'boolean
5936 :version "24.1"
5937 :group 'org-appearance)
5939 (defun org-fontify-meta-lines-and-blocks (limit)
5940 (condition-case nil
5941 (org-fontify-meta-lines-and-blocks-1 limit)
5942 (error (message "org-mode fontification error in %S at %d"
5943 (current-buffer)
5944 (line-number-at-pos)))))
5946 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5947 "Fontify #+ lines and blocks."
5948 (let ((case-fold-search t))
5949 (when (re-search-forward
5950 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5951 limit t)
5952 (let ((beg (match-beginning 0))
5953 (block-start (match-end 0))
5954 (block-end nil)
5955 (lang (match-string 7))
5956 (beg1 (line-beginning-position 2))
5957 (dc1 (downcase (match-string 2)))
5958 (dc3 (downcase (match-string 3)))
5959 end end1 quoting block-type)
5960 (cond
5961 ((and (match-end 4) (equal dc3 "+begin"))
5962 ;; Truly a block
5963 (setq block-type (downcase (match-string 5))
5964 quoting (member block-type org-protecting-blocks))
5965 (when (re-search-forward
5966 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5967 nil t) ;; on purpose, we look further than LIMIT
5968 (setq end (min (point-max) (match-end 0))
5969 end1 (min (point-max) (1- (match-beginning 0))))
5970 (setq block-end (match-beginning 0))
5971 (when quoting
5972 (org-remove-flyspell-overlays-in beg1 end1)
5973 (remove-text-properties beg end
5974 '(display t invisible t intangible t)))
5975 (add-text-properties
5976 beg end '(font-lock-fontified t font-lock-multiline t))
5977 (add-text-properties beg beg1 '(face org-meta-line))
5978 (org-remove-flyspell-overlays-in beg beg1)
5979 (add-text-properties ; For end_src
5980 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5981 (org-remove-flyspell-overlays-in end1 end)
5982 (cond
5983 ((and lang (not (string= lang "")) org-src-fontify-natively)
5984 (org-src-font-lock-fontify-block lang block-start block-end)
5985 (add-text-properties beg1 block-end '(src-block t)))
5986 (quoting
5987 (add-text-properties beg1 (min (point-max) (1+ end1))
5988 (list 'face
5989 (list :inherit
5990 (let ((face-name
5991 (intern (format "org-block-%s" lang))))
5992 (append (and (facep face-name) (list face-name))
5993 '(org-block))))))) ; end of source block
5994 ((not org-fontify-quote-and-verse-blocks))
5995 ((string= block-type "quote")
5996 (add-face-text-property
5997 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5998 ((string= block-type "verse")
5999 (add-face-text-property
6000 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6001 (add-text-properties beg beg1 '(face org-block-begin-line))
6002 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6003 '(face org-block-end-line))
6005 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6006 (org-remove-flyspell-overlays-in
6007 (match-beginning 0)
6008 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6009 (add-text-properties
6010 beg (match-end 3)
6011 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6012 '(font-lock-fontified t invisible t)
6013 '(font-lock-fontified t face org-document-info-keyword)))
6014 (add-text-properties
6015 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6016 (if (string-equal dc1 "+title:")
6017 '(font-lock-fontified t face org-document-title)
6018 '(font-lock-fontified t face org-document-info))))
6019 ((string-prefix-p "+caption" dc1)
6020 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6021 (remove-text-properties (match-beginning 0) (match-end 0)
6022 '(display t invisible t intangible t))
6023 ;; Handle short captions.
6024 (save-excursion
6025 (beginning-of-line)
6026 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6027 (add-text-properties (line-beginning-position) (match-end 1)
6028 '(font-lock-fontified t face org-meta-line))
6029 (add-text-properties (match-end 0) (line-end-position)
6030 '(font-lock-fontified t face org-block))
6032 ((member dc3 '(" " ""))
6033 (org-remove-flyspell-overlays-in beg (match-end 0))
6034 (add-text-properties
6035 beg (match-end 0)
6036 '(font-lock-fontified t face font-lock-comment-face)))
6037 (t ;; just any other in-buffer setting, but not indented
6038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6039 (remove-text-properties (match-beginning 0) (match-end 0)
6040 '(display t invisible t intangible t))
6041 (add-text-properties beg (match-end 0)
6042 '(font-lock-fontified t face org-meta-line))
6043 t))))))
6045 (defun org-fontify-drawers (limit)
6046 "Fontify drawers."
6047 (when (re-search-forward org-drawer-regexp limit t)
6048 (add-text-properties
6049 (match-beginning 0) (match-end 0)
6050 '(font-lock-fontified t face org-special-keyword))
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6054 (defun org-fontify-macros (limit)
6055 "Fontify macros."
6056 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6057 (add-text-properties
6058 (match-beginning 0) (match-end 0)
6059 '(font-lock-fontified t face org-macro))
6060 (when org-hide-macro-markers
6061 (add-text-properties (match-end 2) (match-beginning 2)
6062 '(invisible t))
6063 (add-text-properties (match-beginning 1) (match-end 1)
6064 '(invisible t)))
6065 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6068 (defun org-activate-footnote-links (limit)
6069 "Add text properties for footnotes."
6070 (let ((fn (org-footnote-next-reference-or-definition limit)))
6071 (when fn
6072 (let* ((beg (nth 1 fn))
6073 (end (nth 2 fn))
6074 (label (car fn))
6075 (referencep (/= (line-beginning-position) beg)))
6076 (when (and referencep (nth 3 fn))
6077 (save-excursion
6078 (goto-char beg)
6079 (search-forward (or label "fn:"))
6080 (org-remove-flyspell-overlays-in beg (match-end 0))))
6081 (add-text-properties beg end
6082 (list 'mouse-face 'highlight
6083 'keymap org-mouse-map
6084 'help-echo
6085 (if referencep "Footnote reference"
6086 "Footnote definition")
6087 'font-lock-fontified t
6088 'font-lock-multiline t
6089 'face 'org-footnote))))))
6091 (defun org-activate-dates (limit)
6092 "Add text properties for dates."
6093 (when (and (re-search-forward org-tsr-regexp-both limit t)
6094 (not (equal (char-before (match-beginning 0)) 91)))
6095 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6096 (add-text-properties (match-beginning 0) (match-end 0)
6097 (list 'mouse-face 'highlight
6098 'keymap org-mouse-map))
6099 (org-rear-nonsticky-at (match-end 0))
6100 (when org-display-custom-times
6101 ;; If it's a date range, activate custom time for second date.
6102 (when (match-end 3)
6103 (org-display-custom-time (match-beginning 3) (match-end 3)))
6104 (org-display-custom-time (match-beginning 1) (match-end 1)))
6107 (defvar-local org-target-link-regexp nil
6108 "Regular expression matching radio targets in plain text.")
6110 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6111 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6112 border border border))
6113 "Regular expression matching a link target.")
6115 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6116 "Regular expression matching a radio target.")
6118 (defconst org-any-target-regexp
6119 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6120 "Regular expression matching any target.")
6122 (defun org-activate-target-links (limit)
6123 "Add text properties for target matches."
6124 (when org-target-link-regexp
6125 (let ((case-fold-search t))
6126 (when (re-search-forward org-target-link-regexp limit t)
6127 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6128 (add-text-properties (match-beginning 1) (match-end 1)
6129 (list 'mouse-face 'highlight
6130 'keymap org-mouse-map
6131 'help-echo "Radio target link"
6132 'org-linked-text t))
6133 (org-rear-nonsticky-at (match-end 1))
6134 t))))
6136 (defun org-update-radio-target-regexp ()
6137 "Find all radio targets in this file and update the regular expression.
6138 Also refresh fontification if needed."
6139 (interactive)
6140 (let ((old-regexp org-target-link-regexp)
6141 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6142 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6143 (targets
6144 (org-with-wide-buffer
6145 (goto-char (point-min))
6146 (let (rtn)
6147 (while (re-search-forward org-radio-target-regexp nil t)
6148 ;; Make sure point is really within the object.
6149 (backward-char)
6150 (let ((obj (org-element-context)))
6151 (when (eq (org-element-type obj) 'radio-target)
6152 (cl-pushnew (org-element-property :value obj) rtn
6153 :test #'equal))))
6154 rtn))))
6155 (setq org-target-link-regexp
6156 (and targets
6157 (concat before-re
6158 (mapconcat
6159 (lambda (x)
6160 (replace-regexp-in-string
6161 " +" "\\s-+" (regexp-quote x) t t))
6162 targets
6163 "\\|")
6164 after-re)))
6165 (unless (equal old-regexp org-target-link-regexp)
6166 ;; Clean-up cache.
6167 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6168 ((not org-target-link-regexp) old-regexp)
6170 (concat before-re
6171 (mapconcat
6172 (lambda (re)
6173 (substring re (length before-re)
6174 (- (length after-re))))
6175 (list old-regexp org-target-link-regexp)
6176 "\\|")
6177 after-re)))))
6178 (org-with-wide-buffer
6179 (goto-char (point-min))
6180 (while (re-search-forward regexp nil t)
6181 (org-element-cache-refresh (match-beginning 1)))))
6182 ;; Re fontify buffer.
6183 (when (memq 'radio org-highlight-links)
6184 (org-restart-font-lock)))))
6186 (defvar org-latex-and-related-regexp nil
6187 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6189 (defun org-compute-latex-and-related-regexp ()
6190 "Compute regular expression for LaTeX, entities and sub/superscript.
6191 Result depends on variable `org-highlight-latex-and-related'."
6192 (setq-local
6193 org-latex-and-related-regexp
6194 (let* ((re-sub
6195 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6196 ((eq org-use-sub-superscripts '{})
6197 (list org-match-substring-with-braces-regexp))
6198 (org-use-sub-superscripts (list org-match-substring-regexp))))
6199 (re-latex
6200 (when (memq 'latex org-highlight-latex-and-related)
6201 (let ((matchers (plist-get org-format-latex-options :matchers)))
6202 (delq nil
6203 (mapcar (lambda (x)
6204 (and (member (car x) matchers) (nth 1 x)))
6205 org-latex-regexps)))))
6206 (re-entities
6207 (when (memq 'entities org-highlight-latex-and-related)
6208 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6209 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6211 (defun org-do-latex-and-related (limit)
6212 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6213 LIMIT bounds the search for syntax to highlight. Stop at first
6214 highlighted object, if any. Return t if some highlighting was
6215 done, nil otherwise."
6216 (when (org-string-nw-p org-latex-and-related-regexp)
6217 (catch 'found
6218 (while (re-search-forward org-latex-and-related-regexp limit t)
6219 (unless
6220 (cl-some
6221 (lambda (f)
6222 (memq f '(org-code org-verbatim underline org-special-keyword)))
6223 (save-excursion
6224 (goto-char (1+ (match-beginning 0)))
6225 (face-at-point nil t)))
6226 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6227 '(?_ ?^))
6229 0)))
6230 (font-lock-prepend-text-property
6231 (+ offset (match-beginning 0)) (match-end 0)
6232 'face 'org-latex-and-related)
6233 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6234 '(font-lock-multiline t)))
6235 (throw 'found t)))
6236 nil)))
6238 (defun org-restart-font-lock ()
6239 "Restart `font-lock-mode', to force refontification."
6240 (when (and (boundp 'font-lock-mode) font-lock-mode)
6241 (font-lock-mode -1)
6242 (font-lock-mode 1)))
6244 (defun org-activate-tags (limit)
6245 (when (re-search-forward
6246 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6247 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6248 (add-text-properties (match-beginning 1) (match-end 1)
6249 (list 'mouse-face 'highlight
6250 'keymap org-mouse-map))
6251 (org-rear-nonsticky-at (match-end 1))
6254 (defun org-outline-level ()
6255 "Compute the outline level of the heading at point.
6257 If this is called at a normal headline, the level is the number
6258 of stars. Use `org-reduced-level' to remove the effect of
6259 `org-odd-levels'. Unlike to `org-current-level', this function
6260 takes into consideration inlinetasks."
6261 (org-with-wide-buffer
6262 (end-of-line)
6263 (if (re-search-backward org-outline-regexp-bol nil t)
6264 (1- (- (match-end 0) (match-beginning 0)))
6265 0)))
6267 (defvar org-font-lock-keywords nil)
6269 (defsubst org-re-property (property &optional literal allow-null value)
6270 "Return a regexp matching a PROPERTY line.
6272 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6273 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6274 non-nil, match properties even without a value.
6276 Match group 3 is set to the value when it exists. If there is no
6277 value and ALLOW-NULL is non-nil, it is set to the empty string.
6279 With optional argument VALUE, match only property lines with
6280 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6281 unless LITERAL is non-nil."
6282 (concat
6283 "^\\(?4:[ \t]*\\)"
6284 (format "\\(?1::\\(?2:%s\\):\\)"
6285 (if literal property (regexp-quote property)))
6286 (cond (value
6287 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6288 (if literal value (regexp-quote value))))
6289 (allow-null
6290 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6292 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6294 (defconst org-property-re
6295 (org-re-property "\\S-+" 'literal t)
6296 "Regular expression matching a property line.
6297 There are four matching groups:
6298 1: :PROPKEY: including the leading and trailing colon,
6299 2: PROPKEY without the leading and trailing colon,
6300 3: PROPVAL without leading or trailing spaces,
6301 4: the indentation of the current line,
6302 5: trailing whitespace.")
6304 (defvar org-font-lock-hook nil
6305 "Functions to be called for special font lock stuff.")
6307 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6309 (defvar org-font-lock-set-keywords-hook nil
6310 "Functions that can manipulate `org-font-lock-extra-keywords'.
6311 This is called after `org-font-lock-extra-keywords' is defined, but before
6312 it is installed to be used by font lock. This can be useful if something
6313 needs to be inserted at a specific position in the font-lock sequence.")
6315 (defun org-font-lock-hook (limit)
6316 "Run `org-font-lock-hook' within LIMIT."
6317 (run-hook-with-args 'org-font-lock-hook limit))
6319 (defun org-set-font-lock-defaults ()
6320 "Set font lock defaults for the current buffer."
6321 (let* ((em org-fontify-emphasized-text)
6322 (lk org-highlight-links)
6323 (org-font-lock-extra-keywords
6324 (list
6325 ;; Call the hook
6326 '(org-font-lock-hook)
6327 ;; Headlines
6328 `(,(if org-fontify-whole-heading-line
6329 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6330 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6331 (1 (org-get-level-face 1))
6332 (2 (org-get-level-face 2))
6333 (3 (org-get-level-face 3)))
6334 ;; Table lines
6335 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6336 (1 'org-table t))
6337 ;; Table internals
6338 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6339 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6340 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6341 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6342 ;; Drawers
6343 '(org-fontify-drawers)
6344 ;; Properties
6345 (list org-property-re
6346 '(1 'org-special-keyword t)
6347 '(3 'org-property-value t))
6348 ;; Link related fontification.
6349 '(org-activate-links)
6350 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6351 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6352 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6353 (when (memq 'footnote lk) '(org-activate-footnote-links))
6354 ;; Targets.
6355 (list org-any-target-regexp '(0 'org-target t))
6356 ;; Diary sexps.
6357 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6358 ;; Macro
6359 '(org-fontify-macros)
6360 ;; TODO keyword
6361 (list (format org-heading-keyword-regexp-format
6362 org-todo-regexp)
6363 '(2 (org-get-todo-face 2) t))
6364 ;; DONE
6365 (if org-fontify-done-headline
6366 (list (format org-heading-keyword-regexp-format
6367 (concat
6368 "\\(?:"
6369 (mapconcat 'regexp-quote org-done-keywords "\\|")
6370 "\\)"))
6371 '(2 'org-headline-done t))
6372 nil)
6373 ;; Priorities
6374 '(org-font-lock-add-priority-faces)
6375 ;; Tags
6376 '(org-font-lock-add-tag-faces)
6377 ;; Tags groups
6378 (when (and org-group-tags org-tag-groups-alist)
6379 (list (concat org-outline-regexp-bol ".+\\(:"
6380 (regexp-opt (mapcar 'car org-tag-groups-alist))
6381 ":\\).*$")
6382 '(1 'org-tag-group prepend)))
6383 ;; Special keywords
6384 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6385 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6386 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6387 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6388 ;; Emphasis
6389 (when em '(org-do-emphasis-faces))
6390 ;; Checkboxes
6391 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6392 1 'org-checkbox prepend)
6393 (when (cdr (assq 'checkbox org-list-automatic-rules))
6394 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6395 (0 (org-get-checkbox-statistics-face) t)))
6396 ;; Description list items
6397 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6398 1 'org-list-dt prepend)
6399 ;; ARCHIVEd headings
6400 (list (concat
6401 org-outline-regexp-bol
6402 "\\(.*:" org-archive-tag ":.*\\)")
6403 '(1 'org-archived prepend))
6404 ;; Specials
6405 '(org-do-latex-and-related)
6406 '(org-fontify-entities)
6407 '(org-raise-scripts)
6408 ;; Code
6409 '(org-activate-code (1 'org-code t))
6410 ;; COMMENT
6411 (list (format
6412 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6413 org-todo-regexp
6414 org-comment-string)
6415 '(9 'org-special-keyword t))
6416 ;; Blocks and meta lines
6417 '(org-fontify-meta-lines-and-blocks))))
6418 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6419 (run-hooks 'org-font-lock-set-keywords-hook)
6420 ;; Now set the full font-lock-keywords
6421 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6422 (setq-local font-lock-defaults
6423 '(org-font-lock-keywords t nil nil backward-paragraph))
6424 (kill-local-variable 'font-lock-keywords)
6425 nil))
6427 (defun org-toggle-pretty-entities ()
6428 "Toggle the composition display of entities as UTF8 characters."
6429 (interactive)
6430 (setq-local org-pretty-entities (not org-pretty-entities))
6431 (org-restart-font-lock)
6432 (if org-pretty-entities
6433 (message "Entities are now displayed as UTF8 characters")
6434 (save-restriction
6435 (widen)
6436 (decompose-region (point-min) (point-max))
6437 (message "Entities are now displayed as plain text"))))
6439 (defvar-local org-custom-properties-overlays nil
6440 "List of overlays used for custom properties.")
6442 (defun org-toggle-custom-properties-visibility ()
6443 "Display or hide properties in `org-custom-properties'."
6444 (interactive)
6445 (if org-custom-properties-overlays
6446 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6447 (setq org-custom-properties-overlays nil))
6448 (when org-custom-properties
6449 (org-with-wide-buffer
6450 (goto-char (point-min))
6451 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6452 (while (re-search-forward regexp nil t)
6453 (let ((end (cdr (save-match-data (org-get-property-block)))))
6454 (when (and end (< (point) end))
6455 ;; Hide first custom property in current drawer.
6456 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6457 (overlay-put o 'invisible t)
6458 (overlay-put o 'org-custom-property t)
6459 (push o org-custom-properties-overlays))
6460 ;; Hide additional custom properties in the same drawer.
6461 (while (re-search-forward regexp end t)
6462 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6463 (overlay-put o 'invisible t)
6464 (overlay-put o 'org-custom-property t)
6465 (push o org-custom-properties-overlays)))))
6466 ;; Each entry is limited to a single property drawer.
6467 (outline-next-heading)))))))
6469 (defun org-fontify-entities (limit)
6470 "Find an entity to fontify."
6471 (let (ee)
6472 (when org-pretty-entities
6473 (catch 'match
6474 ;; "\_ "-family is left out on purpose. Only the first one,
6475 ;; i.e., "\_ ", could be fontified anyway, and it would be
6476 ;; confusing when adding a second white space character.
6477 (while (re-search-forward
6478 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6479 limit t)
6480 (when (and (not (org-at-comment-p))
6481 (setq ee (org-entity-get (match-string 1)))
6482 (= (length (nth 6 ee)) 1))
6483 (let* ((end (if (equal (match-string 2) "{}")
6484 (match-end 2)
6485 (match-end 1))))
6486 (add-text-properties
6487 (match-beginning 0) end
6488 (list 'font-lock-fontified t))
6489 (compose-region (match-beginning 0) end
6490 (nth 6 ee) nil)
6491 (backward-char 1)
6492 (throw 'match t))))
6493 nil))))
6495 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6496 "Fontify string S like in Org mode."
6497 (with-temp-buffer
6498 (insert s)
6499 (let ((org-odd-levels-only odd-levels))
6500 (org-mode)
6501 (org-font-lock-ensure)
6502 (buffer-string))))
6504 (defvar org-m nil)
6505 (defvar org-l nil)
6506 (defvar org-f nil)
6507 (defun org-get-level-face (n)
6508 "Get the right face for match N in font-lock matching of headlines."
6509 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6510 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6511 (if org-cycle-level-faces
6512 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6513 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6514 (cond
6515 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6516 ((eq n 2) org-f)
6517 (t (unless org-level-color-stars-only org-f))))
6519 (defun org-face-from-face-or-color (context inherit face-or-color)
6520 "Create a face list that inherits INHERIT, but sets the foreground color.
6521 When FACE-OR-COLOR is not a string, just return it."
6522 (if (stringp face-or-color)
6523 (list :inherit inherit
6524 (cdr (assoc context org-faces-easy-properties))
6525 face-or-color)
6526 face-or-color))
6528 (defun org-get-todo-face (kwd)
6529 "Get the right face for a TODO keyword KWD.
6530 If KWD is a number, get the corresponding match group."
6531 (when (numberp kwd) (setq kwd (match-string kwd)))
6532 (or (org-face-from-face-or-color
6533 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6534 (and (member kwd org-done-keywords) 'org-done)
6535 'org-todo))
6537 (defun org-get-priority-face (priority)
6538 "Get the right face for PRIORITY.
6539 PRIORITY is a character."
6540 (or (org-face-from-face-or-color
6541 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6542 'org-priority))
6544 (defun org-get-tag-face (tag)
6545 "Get the right face for TAG.
6546 If TAG is a number, get the corresponding match group."
6547 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6548 (or (org-face-from-face-or-color
6549 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6550 'org-tag)))
6552 (defun org-font-lock-add-priority-faces (limit)
6553 "Add the special priority faces."
6554 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6555 (add-text-properties
6556 (match-beginning 1) (match-end 1)
6557 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6558 'font-lock-fontified t))))
6560 (defun org-font-lock-add-tag-faces (limit)
6561 "Add the special tag faces."
6562 (when (and org-tag-faces org-tags-special-faces-re)
6563 (while (re-search-forward org-tags-special-faces-re limit t)
6564 (add-text-properties (match-beginning 1) (match-end 1)
6565 (list 'face (org-get-tag-face 1)
6566 'font-lock-fontified t))
6567 (backward-char 1))))
6569 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6570 "Remove fontification and activation overlays from links."
6571 (font-lock-default-unfontify-region beg end)
6572 (let* ((buffer-undo-list t)
6573 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6574 (inhibit-modification-hooks t)
6575 deactivate-mark buffer-file-name buffer-file-truename)
6576 (decompose-region beg end)
6577 (remove-text-properties beg end
6578 '(mouse-face t keymap t org-linked-text t
6579 invisible t intangible t
6580 org-emphasis t))
6581 (org-remove-font-lock-display-properties beg end)))
6583 (defconst org-script-display '(((raise -0.3) (height 0.7))
6584 ((raise 0.3) (height 0.7))
6585 ((raise -0.5))
6586 ((raise 0.5)))
6587 "Display properties for showing superscripts and subscripts.")
6589 (defun org-remove-font-lock-display-properties (beg end)
6590 "Remove specific display properties that have been added by font lock.
6591 The will remove the raise properties that are used to show superscripts
6592 and subscripts."
6593 (let (next prop)
6594 (while (< beg end)
6595 (setq next (next-single-property-change beg 'display nil end)
6596 prop (get-text-property beg 'display))
6597 (when (member prop org-script-display)
6598 (put-text-property beg next 'display nil))
6599 (setq beg next))))
6601 (defun org-raise-scripts (limit)
6602 "Add raise properties to sub/superscripts."
6603 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6604 (re-search-forward
6605 (if (eq org-use-sub-superscripts t)
6606 org-match-substring-regexp
6607 org-match-substring-with-braces-regexp)
6608 limit t))
6609 (let* ((pos (point)) table-p comment-p
6610 (mpos (match-beginning 3))
6611 (emph-p (get-text-property mpos 'org-emphasis))
6612 (link-p (get-text-property mpos 'mouse-face))
6613 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6614 (goto-char (point-at-bol))
6615 (setq table-p (looking-at-p org-table-dataline-regexp)
6616 comment-p (looking-at-p "^[ \t]*#[ +]"))
6617 (goto-char pos)
6618 ;; Handle a_b^c
6619 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6620 (unless (or comment-p emph-p link-p keyw-p)
6621 (put-text-property (match-beginning 3) (match-end 0)
6622 'display
6623 (if (equal (char-after (match-beginning 2)) ?^)
6624 (nth (if table-p 3 1) org-script-display)
6625 (nth (if table-p 2 0) org-script-display)))
6626 (add-text-properties (match-beginning 2) (match-end 2)
6627 (list 'invisible t))
6628 (when (and (eq (char-after (match-beginning 3)) ?{)
6629 (eq (char-before (match-end 3)) ?}))
6630 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6631 (list 'invisible t))
6632 (add-text-properties (1- (match-end 3)) (match-end 3)
6633 (list 'invisible t))))
6634 t)))
6636 ;;;; Visibility cycling, including org-goto and indirect buffer
6638 ;;; Cycling
6640 (defvar-local org-cycle-global-status nil)
6641 (put 'org-cycle-global-status 'org-state t)
6642 (defvar-local org-cycle-subtree-status nil)
6643 (put 'org-cycle-subtree-status 'org-state t)
6645 (defvar org-inlinetask-min-level)
6647 (defun org-unlogged-message (&rest args)
6648 "Display a message, but avoid logging it in the *Messages* buffer."
6649 (let ((message-log-max nil))
6650 (apply 'message args)))
6652 ;;;###autoload
6653 (defun org-cycle (&optional arg)
6654 "TAB-action and visibility cycling for Org mode.
6656 This is the command invoked in Org mode by the `TAB' key. Its main
6657 purpose is outline visibility cycling, but it also invokes other actions
6658 in special contexts.
6660 When this function is called with a `\\[universal-argument]' prefix, rotate \
6661 the entire
6662 buffer through 3 states (global cycling)
6663 1. OVERVIEW: Show only top-level headlines.
6664 2. CONTENTS: Show all headlines of all levels, but no body text.
6665 3. SHOW ALL: Show everything.
6667 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6668 switch to the startup visibility,
6669 determined by the variable `org-startup-folded', and by any VISIBILITY
6670 properties in the buffer.
6672 With a `\\[universal-argument] \\[universal-argument] \
6673 \\[universal-argument]' prefix argument, show the entire buffer, including
6674 any drawers.
6676 When inside a table, re-align the table and move to the next field.
6678 When point is at the beginning of a headline, rotate the subtree started
6679 by this line through 3 different states (local cycling)
6680 1. FOLDED: Only the main headline is shown.
6681 2. CHILDREN: The main headline and the direct children are shown.
6682 From this state, you can move to one of the children
6683 and zoom in further.
6684 3. SUBTREE: Show the entire subtree, including body text.
6685 If there is no subtree, switch directly from CHILDREN to FOLDED.
6687 When point is at the beginning of an empty headline and the variable
6688 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6689 of the headline by demoting and promoting it to likely levels. This
6690 speeds up creation document structure by pressing `TAB' once or several
6691 times right after creating a new headline.
6693 When there is a numeric prefix, go up to a heading with level ARG, do
6694 a `show-subtree' and return to the previous cursor position. If ARG
6695 is negative, go up that many levels.
6697 When point is not at the beginning of a headline, execute the global
6698 binding for `TAB', which is re-indenting the line. See the option
6699 `org-cycle-emulate-tab' for details.
6701 As a special case, if point is at the beginning of the buffer and there is
6702 no headline in line 1, this function will act as if called with prefix arg
6703 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6704 prefix arg, but only
6705 if the variable `org-cycle-global-at-bob' is t."
6706 (interactive "P")
6707 (org-load-modules-maybe)
6708 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6709 (and org-cycle-level-after-item/entry-creation
6710 (or (org-cycle-level)
6711 (org-cycle-item-indentation))))
6712 (let* ((limit-level
6713 (or org-cycle-max-level
6714 (and (boundp 'org-inlinetask-min-level)
6715 org-inlinetask-min-level
6716 (1- org-inlinetask-min-level))))
6717 (nstars (and limit-level
6718 (if org-odd-levels-only
6719 (and limit-level (1- (* limit-level 2)))
6720 limit-level)))
6721 (org-outline-regexp
6722 (if (not (derived-mode-p 'org-mode))
6723 outline-regexp
6724 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6725 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6726 (not (looking-at org-outline-regexp))))
6727 (org-cycle-hook
6728 (if bob-special
6729 (delq 'org-optimize-window-after-visibility-change
6730 (copy-sequence org-cycle-hook))
6731 org-cycle-hook))
6732 (pos (point)))
6734 (cond
6736 ((equal arg '(16))
6737 (setq last-command 'dummy)
6738 (org-set-startup-visibility)
6739 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6741 ((equal arg '(64))
6742 (outline-show-all)
6743 (org-unlogged-message "Entire buffer visible, including drawers"))
6745 ((equal arg '(4)) (org-cycle-internal-global))
6747 ;; Try hiding block at point.
6748 ((org-hide-block-toggle-maybe))
6750 ;; Try cdlatex TAB completion
6751 ((org-try-cdlatex-tab))
6753 ;; Table: enter it or move to the next field.
6754 ((org-at-table-p 'any)
6755 (if (org-at-table.el-p)
6756 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6757 Use `\\[org-edit-special]' to edit table.el tables"))
6758 (if arg (org-table-edit-field t)
6759 (org-table-justify-field-maybe)
6760 (call-interactively 'org-table-next-field))))
6762 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6764 ;; Global cycling: delegate to `org-cycle-internal-global'.
6765 (bob-special (org-cycle-internal-global))
6767 ;; Drawers: delegate to `org-flag-drawer'.
6768 ((save-excursion
6769 (beginning-of-line 1)
6770 (looking-at org-drawer-regexp))
6771 (org-flag-drawer ; toggle block visibility
6772 (not (get-char-property (match-end 0) 'invisible))))
6774 ;; Show-subtree, ARG levels up from here.
6775 ((integerp arg)
6776 (save-excursion
6777 (org-back-to-heading)
6778 (outline-up-heading (if (< arg 0) (- arg)
6779 (- (funcall outline-level) arg)))
6780 (org-show-subtree)))
6782 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6783 ((and (featurep 'org-inlinetask)
6784 (org-inlinetask-at-task-p)
6785 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6786 (org-inlinetask-toggle-visibility))
6788 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6789 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6790 (save-excursion (move-beginning-of-line 1)
6791 (looking-at org-outline-regexp)))
6792 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6793 (org-cycle-internal-local))
6795 ;; From there: TAB emulation and template completion.
6796 (buffer-read-only (org-back-to-heading))
6798 ((run-hook-with-args-until-success
6799 'org-tab-after-check-for-cycling-hook))
6801 ((org-try-structure-completion))
6803 ((run-hook-with-args-until-success
6804 'org-tab-before-tab-emulation-hook))
6806 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6807 (or (not (bolp))
6808 (not (looking-at org-outline-regexp))))
6809 (call-interactively (global-key-binding "\t")))
6811 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6812 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6813 (or (and (eq org-cycle-emulate-tab 'white)
6814 (= (match-end 0) (point-at-eol)))
6815 (and (eq org-cycle-emulate-tab 'whitestart)
6816 (>= (match-end 0) pos))))
6818 (eq org-cycle-emulate-tab t))
6819 (call-interactively (global-key-binding "\t")))
6821 (t (save-excursion
6822 (org-back-to-heading)
6823 (org-cycle)))))))
6825 (defun org-cycle-internal-global ()
6826 "Do the global cycling action."
6827 ;; Hack to avoid display of messages for .org attachments in Gnus
6828 (let ((ga (string-match "\\*fontification" (buffer-name))))
6829 (cond
6830 ((and (eq last-command this-command)
6831 (eq org-cycle-global-status 'overview))
6832 ;; We just created the overview - now do table of contents
6833 ;; This can be slow in very large buffers, so indicate action
6834 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6835 (unless ga (org-unlogged-message "CONTENTS..."))
6836 (org-content)
6837 (unless ga (org-unlogged-message "CONTENTS...done"))
6838 (setq org-cycle-global-status 'contents)
6839 (run-hook-with-args 'org-cycle-hook 'contents))
6841 ((and (eq last-command this-command)
6842 (eq org-cycle-global-status 'contents))
6843 ;; We just showed the table of contents - now show everything
6844 (run-hook-with-args 'org-pre-cycle-hook 'all)
6845 (outline-show-all)
6846 (unless ga (org-unlogged-message "SHOW ALL"))
6847 (setq org-cycle-global-status 'all)
6848 (run-hook-with-args 'org-cycle-hook 'all))
6851 ;; Default action: go to overview
6852 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6853 (org-overview)
6854 (unless ga (org-unlogged-message "OVERVIEW"))
6855 (setq org-cycle-global-status 'overview)
6856 (run-hook-with-args 'org-cycle-hook 'overview)))))
6858 (defvar org-called-with-limited-levels nil
6859 "Non-nil when `org-with-limited-levels' is currently active.")
6861 (defun org-invisible-p (&optional pos)
6862 "Non-nil if the character after POS is invisible.
6863 If POS is nil, use `point' instead."
6864 (get-char-property (or pos (point)) 'invisible))
6866 (defun org-cycle-internal-local ()
6867 "Do the local cycling action."
6868 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6869 ;; First, determine end of headline (EOH), end of subtree or item
6870 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6871 (save-excursion
6872 (if (org-at-item-p)
6873 (progn
6874 (beginning-of-line)
6875 (setq struct (org-list-struct))
6876 (setq eoh (point-at-eol))
6877 (setq eos (org-list-get-item-end-before-blank (point) struct))
6878 (setq has-children (org-list-has-child-p (point) struct)))
6879 (org-back-to-heading)
6880 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6881 (setq eos (save-excursion (org-end-of-subtree t t)
6882 (when (bolp) (backward-char)) (point)))
6883 (setq has-children
6884 (or (save-excursion
6885 (let ((level (funcall outline-level)))
6886 (outline-next-heading)
6887 (and (org-at-heading-p t)
6888 (> (funcall outline-level) level))))
6889 (save-excursion
6890 (org-list-search-forward (org-item-beginning-re) eos t)))))
6891 ;; Determine end invisible part of buffer (EOL)
6892 (beginning-of-line 2)
6893 (while (and (not (eobp)) ;This is like `next-line'.
6894 (get-char-property (1- (point)) 'invisible))
6895 (goto-char (next-single-char-property-change (point) 'invisible))
6896 (and (eolp) (beginning-of-line 2)))
6897 (setq eol (point)))
6898 ;; Find out what to do next and set `this-command'
6899 (cond
6900 ((= eos eoh)
6901 ;; Nothing is hidden behind this heading
6902 (unless (org-before-first-heading-p)
6903 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6904 (org-unlogged-message "EMPTY ENTRY")
6905 (setq org-cycle-subtree-status nil)
6906 (save-excursion
6907 (goto-char eos)
6908 (outline-next-heading)
6909 (when (org-invisible-p) (org-flag-heading nil))))
6910 ((and (or (>= eol eos)
6911 (not (string-match "\\S-" (buffer-substring eol eos))))
6912 (or has-children
6913 (not (setq children-skipped
6914 org-cycle-skip-children-state-if-no-children))))
6915 ;; Entire subtree is hidden in one line: children view
6916 (unless (org-before-first-heading-p)
6917 (run-hook-with-args 'org-pre-cycle-hook 'children))
6918 (if (org-at-item-p)
6919 (org-list-set-item-visibility (point-at-bol) struct 'children)
6920 (org-show-entry)
6921 (org-with-limited-levels (org-show-children))
6922 ;; FIXME: This slows down the func way too much.
6923 ;; How keep drawers hidden in subtree anyway?
6924 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6925 ;; (org-cycle-hide-drawers 'subtree))
6927 ;; Fold every list in subtree to top-level items.
6928 (when (eq org-cycle-include-plain-lists 'integrate)
6929 (save-excursion
6930 (org-back-to-heading)
6931 (while (org-list-search-forward (org-item-beginning-re) eos t)
6932 (beginning-of-line 1)
6933 (let* ((struct (org-list-struct))
6934 (prevs (org-list-prevs-alist struct))
6935 (end (org-list-get-bottom-point struct)))
6936 (dolist (e (org-list-get-all-items (point) struct prevs))
6937 (org-list-set-item-visibility e struct 'folded))
6938 (goto-char (if (< end eos) end eos)))))))
6939 (org-unlogged-message "CHILDREN")
6940 (save-excursion
6941 (goto-char eos)
6942 (outline-next-heading)
6943 (when (org-invisible-p) (org-flag-heading nil)))
6944 (setq org-cycle-subtree-status 'children)
6945 (unless (org-before-first-heading-p)
6946 (run-hook-with-args 'org-cycle-hook 'children)))
6947 ((or children-skipped
6948 (and (eq last-command this-command)
6949 (eq org-cycle-subtree-status 'children)))
6950 ;; We just showed the children, or no children are there,
6951 ;; now show everything.
6952 (unless (org-before-first-heading-p)
6953 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6954 (outline-flag-region eoh eos nil)
6955 (org-unlogged-message
6956 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6957 (setq org-cycle-subtree-status 'subtree)
6958 (unless (org-before-first-heading-p)
6959 (run-hook-with-args 'org-cycle-hook 'subtree)))
6961 ;; Default action: hide the subtree.
6962 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6963 (outline-flag-region eoh eos t)
6964 (org-unlogged-message "FOLDED")
6965 (setq org-cycle-subtree-status 'folded)
6966 (unless (org-before-first-heading-p)
6967 (run-hook-with-args 'org-cycle-hook 'folded))))))
6969 ;;;###autoload
6970 (defun org-global-cycle (&optional arg)
6971 "Cycle the global visibility. For details see `org-cycle'.
6972 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6973 With a numeric prefix, show all headlines up to that level."
6974 (interactive "P")
6975 (let ((org-cycle-include-plain-lists
6976 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6977 (cond
6978 ((integerp arg)
6979 (outline-show-all)
6980 (outline-hide-sublevels arg)
6981 (setq org-cycle-global-status 'contents))
6982 ((equal arg '(4))
6983 (org-set-startup-visibility)
6984 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6986 (org-cycle '(4))))))
6988 (defun org-set-startup-visibility ()
6989 "Set the visibility required by startup options and properties."
6990 (cond
6991 ((eq org-startup-folded t)
6992 (org-overview))
6993 ((eq org-startup-folded 'content)
6994 (org-content))
6995 ((or (eq org-startup-folded 'showeverything)
6996 (eq org-startup-folded nil))
6997 (outline-show-all)))
6998 (unless (eq org-startup-folded 'showeverything)
6999 (when org-hide-block-startup (org-hide-block-all))
7000 (org-set-visibility-according-to-property 'no-cleanup)
7001 (org-cycle-hide-archived-subtrees 'all)
7002 (org-cycle-hide-drawers 'all)
7003 (org-cycle-show-empty-lines t)))
7005 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7006 "Switch subtree visibilities according to :VISIBILITY: property."
7007 (interactive)
7008 (org-with-wide-buffer
7009 (goto-char (point-min))
7010 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7011 (if (not (org-at-property-p)) (outline-next-heading)
7012 (let ((state (match-string 3)))
7013 (save-excursion
7014 (org-back-to-heading t)
7015 (outline-hide-subtree)
7016 (org-reveal)
7017 (cond
7018 ((equal state "folded")
7019 (outline-hide-subtree))
7020 ((equal state "children")
7021 (org-show-hidden-entry)
7022 (org-show-children))
7023 ((equal state "content")
7024 (save-excursion
7025 (save-restriction
7026 (org-narrow-to-subtree)
7027 (org-content))))
7028 ((member state '("all" "showall"))
7029 (outline-show-subtree)))))))
7030 (unless no-cleanup
7031 (org-cycle-hide-archived-subtrees 'all)
7032 (org-cycle-hide-drawers 'all)
7033 (org-cycle-show-empty-lines 'all))))
7035 ;; This function uses outline-regexp instead of the more fundamental
7036 ;; org-outline-regexp so that org-cycle-global works outside of Org
7037 ;; buffers, where outline-regexp is needed.
7038 (defun org-overview ()
7039 "Switch to overview mode, showing only top-level headlines.
7040 This shows all headlines with a level equal or greater than the level
7041 of the first headline in the buffer. This is important, because if the
7042 first headline is not level one, then (hide-sublevels 1) gives confusing
7043 results."
7044 (interactive)
7045 (save-excursion
7046 (let ((level
7047 (save-excursion
7048 (goto-char (point-min))
7049 (when (re-search-forward (concat "^" outline-regexp) nil t)
7050 (goto-char (match-beginning 0))
7051 (funcall outline-level)))))
7052 (and level (outline-hide-sublevels level)))))
7054 (defun org-content (&optional arg)
7055 "Show all headlines in the buffer, like a table of contents.
7056 With numerical argument N, show content up to level N."
7057 (interactive "P")
7058 (org-overview)
7059 (save-excursion
7060 ;; Visit all headings and show their offspring
7061 (and (integerp arg) (org-overview))
7062 (goto-char (point-max))
7063 (catch 'exit
7064 (while (and (progn (condition-case nil
7065 (outline-previous-visible-heading 1)
7066 (error (goto-char (point-min))))
7068 (looking-at org-outline-regexp))
7069 (if (integerp arg)
7070 (org-show-children (1- arg))
7071 (outline-show-branches))
7072 (when (bobp) (throw 'exit nil))))))
7074 (defun org-optimize-window-after-visibility-change (state)
7075 "Adjust the window after a change in outline visibility.
7076 This function is the default value of the hook `org-cycle-hook'."
7077 (when (get-buffer-window (current-buffer))
7078 (cond
7079 ((eq state 'content) nil)
7080 ((eq state 'all) nil)
7081 ((eq state 'folded) nil)
7082 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7083 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7085 (defun org-remove-empty-overlays-at (pos)
7086 "Remove outline overlays that do not contain non-white stuff."
7087 (dolist (o (overlays-at pos))
7088 (and (eq 'outline (overlay-get o 'invisible))
7089 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7090 (overlay-end o))))
7091 (delete-overlay o))))
7093 (defun org-clean-visibility-after-subtree-move ()
7094 "Fix visibility issues after moving a subtree."
7095 ;; First, find a reasonable region to look at:
7096 ;; Start two siblings above, end three below
7097 (let* ((beg (save-excursion
7098 (and (org-get-last-sibling)
7099 (org-get-last-sibling))
7100 (point)))
7101 (end (save-excursion
7102 (and (org-get-next-sibling)
7103 (org-get-next-sibling)
7104 (org-get-next-sibling))
7105 (if (org-at-heading-p)
7106 (point-at-eol)
7107 (point))))
7108 (level (looking-at "\\*+"))
7109 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7110 (save-excursion
7111 (save-restriction
7112 (narrow-to-region beg end)
7113 (when re
7114 ;; Properly fold already folded siblings
7115 (goto-char (point-min))
7116 (while (re-search-forward re nil t)
7117 (when (and (not (org-invisible-p))
7118 (save-excursion
7119 (goto-char (point-at-eol)) (org-invisible-p)))
7120 (outline-hide-entry))))
7121 (org-cycle-show-empty-lines 'overview)
7122 (org-cycle-hide-drawers 'overview)))))
7124 (defun org-cycle-show-empty-lines (state)
7125 "Show empty lines above all visible headlines.
7126 The region to be covered depends on STATE when called through
7127 `org-cycle-hook'. Lisp program can use t for STATE to get the
7128 entire buffer covered. Note that an empty line is only shown if there
7129 are at least `org-cycle-separator-lines' empty lines before the headline."
7130 (when (/= org-cycle-separator-lines 0)
7131 (save-excursion
7132 (let* ((n (abs org-cycle-separator-lines))
7133 (re (cond
7134 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7135 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7136 (t (let ((ns (number-to-string (- n 2))))
7137 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7138 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7139 beg end)
7140 (cond
7141 ((memq state '(overview contents t))
7142 (setq beg (point-min) end (point-max)))
7143 ((memq state '(children folded))
7144 (setq beg (point)
7145 end (progn (org-end-of-subtree t t)
7146 (line-beginning-position 2)))))
7147 (when beg
7148 (goto-char beg)
7149 (while (re-search-forward re end t)
7150 (unless (get-char-property (match-end 1) 'invisible)
7151 (let ((e (match-end 1))
7152 (b (if (>= org-cycle-separator-lines 0)
7153 (match-beginning 1)
7154 (save-excursion
7155 (goto-char (match-beginning 0))
7156 (skip-chars-backward " \t\n")
7157 (line-end-position)))))
7158 (outline-flag-region b e nil))))))))
7159 ;; Never hide empty lines at the end of the file.
7160 (save-excursion
7161 (goto-char (point-max))
7162 (outline-previous-heading)
7163 (outline-end-of-heading)
7164 (when (and (looking-at "[ \t\n]+")
7165 (= (match-end 0) (point-max)))
7166 (outline-flag-region (point) (match-end 0) nil))))
7168 (defun org-show-empty-lines-in-parent ()
7169 "Move to the parent and re-show empty lines before visible headlines."
7170 (save-excursion
7171 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7172 (org-cycle-show-empty-lines context))))
7174 (defun org-files-list ()
7175 "Return `org-agenda-files' list, plus all open Org files.
7176 This is useful for operations that need to scan all of a user's
7177 open and agenda-wise Org files."
7178 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7179 (dolist (buf (buffer-list))
7180 (with-current-buffer buf
7181 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7182 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7183 files))
7185 (defsubst org-entry-beginning-position ()
7186 "Return the beginning position of the current entry."
7187 (save-excursion (org-back-to-heading t) (point)))
7189 (defsubst org-entry-end-position ()
7190 "Return the end position of the current entry."
7191 (save-excursion (outline-next-heading) (point)))
7193 (defun org-cycle-hide-drawers (state &optional exceptions)
7194 "Re-hide all drawers after a visibility state change.
7195 STATE should be one of the symbols listed in the docstring of
7196 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7197 a list of strings specifying which drawers should not be hidden."
7198 (when (and (derived-mode-p 'org-mode)
7199 (not (memq state '(overview folded contents))))
7200 (save-excursion
7201 (let* ((globalp (eq state 'all))
7202 (beg (if globalp (point-min) (point)))
7203 (end (if globalp (point-max)
7204 (if (eq state 'children)
7205 (save-excursion (outline-next-heading) (point))
7206 (org-end-of-subtree t)))))
7207 (goto-char beg)
7208 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7209 (unless (member-ignore-case (match-string 1) exceptions)
7210 (let ((drawer (org-element-at-point)))
7211 (when (memq (org-element-type drawer) '(drawer property-drawer))
7212 (org-flag-drawer t drawer)
7213 ;; Make sure to skip drawer entirely or we might flag
7214 ;; it another time when matching its ending line with
7215 ;; `org-drawer-regexp'.
7216 (goto-char (org-element-property :end drawer))))))))))
7218 (defun org-flag-drawer (flag &optional element)
7219 "When FLAG is non-nil, hide the drawer we are at.
7220 Otherwise make it visible. When optional argument ELEMENT is
7221 a parsed drawer, as returned by `org-element-at-point', hide or
7222 show that drawer instead."
7223 (let ((drawer (or element
7224 (and (save-excursion
7225 (beginning-of-line)
7226 (looking-at-p org-drawer-regexp))
7227 (org-element-at-point)))))
7228 (when (memq (org-element-type drawer) '(drawer property-drawer))
7229 (let ((post (org-element-property :post-affiliated drawer)))
7230 (save-excursion
7231 (outline-flag-region
7232 (progn (goto-char post) (line-end-position))
7233 (progn (goto-char (org-element-property :end drawer))
7234 (skip-chars-backward " \r\t\n")
7235 (line-end-position))
7236 flag))
7237 ;; When the drawer is hidden away, make sure point lies in
7238 ;; a visible part of the buffer.
7239 (when (and flag (> (line-beginning-position) post))
7240 (goto-char post))))))
7242 (defun org-subtree-end-visible-p ()
7243 "Is the end of the current subtree visible?"
7244 (pos-visible-in-window-p
7245 (save-excursion (org-end-of-subtree t) (point))))
7247 (defun org-first-headline-recenter ()
7248 "Move cursor to the first headline and recenter the headline."
7249 (let ((window (get-buffer-window)))
7250 (when window
7251 (goto-char (point-min))
7252 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7253 (set-window-start window (line-beginning-position))))))
7255 ;;; Saving and restoring visibility
7257 (defun org-outline-overlay-data (&optional use-markers)
7258 "Return a list of the locations of all outline overlays.
7259 These are overlays with the `invisible' property value `outline'.
7260 The return value is a list of cons cells, with start and stop
7261 positions for each overlay.
7262 If USE-MARKERS is set, return the positions as markers."
7263 (let (beg end)
7264 (org-with-wide-buffer
7265 (delq nil
7266 (mapcar (lambda (o)
7267 (when (eq (overlay-get o 'invisible) 'outline)
7268 (setq beg (overlay-start o)
7269 end (overlay-end o))
7270 (and beg end (> end beg)
7271 (if use-markers
7272 (cons (copy-marker beg)
7273 (copy-marker end t))
7274 (cons beg end)))))
7275 (overlays-in (point-min) (point-max)))))))
7277 (defun org-set-outline-overlay-data (data)
7278 "Create visibility overlays for all positions in DATA.
7279 DATA should have been made by `org-outline-overlay-data'."
7280 (org-with-wide-buffer
7281 (outline-show-all)
7282 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7284 ;;; Folding of blocks
7286 (defvar-local org-hide-block-overlays nil
7287 "Overlays hiding blocks.")
7289 (defun org-block-map (function &optional start end)
7290 "Call FUNCTION at the head of all source blocks in the current buffer.
7291 Optional arguments START and END can be used to limit the range."
7292 (let ((start (or start (point-min)))
7293 (end (or end (point-max))))
7294 (save-excursion
7295 (goto-char start)
7296 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7297 (save-excursion
7298 (save-match-data
7299 (goto-char (match-beginning 0))
7300 (funcall function)))))))
7302 (defun org-hide-block-toggle-all ()
7303 "Toggle the visibility of all blocks in the current buffer."
7304 (org-block-map 'org-hide-block-toggle))
7306 (defun org-hide-block-all ()
7307 "Fold all blocks in the current buffer."
7308 (interactive)
7309 (org-show-block-all)
7310 (org-block-map 'org-hide-block-toggle-maybe))
7312 (defun org-show-block-all ()
7313 "Unfold all blocks in the current buffer."
7314 (interactive)
7315 (mapc #'delete-overlay org-hide-block-overlays)
7316 (setq org-hide-block-overlays nil))
7318 (defun org-hide-block-toggle-maybe ()
7319 "Toggle visibility of block at point.
7320 Unlike to `org-hide-block-toggle', this function does not throw
7321 an error. Return a non-nil value when toggling is successful."
7322 (interactive)
7323 (ignore-errors (org-hide-block-toggle)))
7325 (defun org-hide-block-toggle (&optional force)
7326 "Toggle the visibility of the current block.
7327 When optional argument FORCE is `off', make block visible. If it
7328 is non-nil, hide it unconditionally. Throw an error when not at
7329 a block. Return a non-nil value when toggling is successful."
7330 (interactive)
7331 (let ((element (org-element-at-point)))
7332 (unless (memq (org-element-type element)
7333 '(center-block comment-block dynamic-block example-block
7334 export-block quote-block special-block
7335 src-block verse-block))
7336 (user-error "Not at a block"))
7337 (let* ((start (save-excursion
7338 (goto-char (org-element-property :post-affiliated element))
7339 (line-end-position)))
7340 (end (save-excursion
7341 (goto-char (org-element-property :end element))
7342 (skip-chars-backward " \r\t\n")
7343 (line-end-position)))
7344 (overlays (overlays-at start)))
7345 (cond
7346 ;; Do nothing when not before or at the block opening line or
7347 ;; at the block closing line.
7348 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7349 ((and (not (eq force 'off))
7350 (not (memq t (mapcar
7351 (lambda (o)
7352 (eq (overlay-get o 'invisible) 'org-hide-block))
7353 overlays))))
7354 (let ((ov (make-overlay start end)))
7355 (overlay-put ov 'invisible 'org-hide-block)
7356 ;; Make the block accessible to `isearch'.
7357 (overlay-put
7358 ov 'isearch-open-invisible
7359 (lambda (ov)
7360 (when (memq ov org-hide-block-overlays)
7361 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7362 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7363 (delete-overlay ov))))
7364 (push ov org-hide-block-overlays)
7365 ;; When the block is hidden away, make sure point is left in
7366 ;; a visible part of the buffer.
7367 (when (> (line-beginning-position) start)
7368 (goto-char start)
7369 (beginning-of-line))
7370 ;; Signal successful toggling.
7372 ((or (not force) (eq force 'off))
7373 (dolist (ov overlays t)
7374 (when (memq ov org-hide-block-overlays)
7375 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7376 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7377 (delete-overlay ov))))))))
7379 ;; Remove overlays when changing major mode
7380 (add-hook 'org-mode-hook
7381 (lambda () (add-hook 'change-major-mode-hook
7382 'org-show-block-all 'append 'local)))
7384 ;;; Org-goto
7386 (defvar org-goto-window-configuration nil)
7387 (defvar org-goto-marker nil)
7388 (defvar org-goto-map)
7389 (defun org-goto-map ()
7390 "Set the keymap `org-goto'."
7391 (setq org-goto-map
7392 (let ((map (make-sparse-keymap)))
7393 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7394 mouse-drag-region universal-argument org-occur)))
7395 (dolist (cmd cmds)
7396 (substitute-key-definition cmd cmd map global-map)))
7397 (suppress-keymap map)
7398 (org-defkey map "\C-m" 'org-goto-ret)
7399 (org-defkey map [(return)] 'org-goto-ret)
7400 (org-defkey map [(left)] 'org-goto-left)
7401 (org-defkey map [(right)] 'org-goto-right)
7402 (org-defkey map [(control ?g)] 'org-goto-quit)
7403 (org-defkey map "\C-i" 'org-cycle)
7404 (org-defkey map [(tab)] 'org-cycle)
7405 (org-defkey map [(down)] 'outline-next-visible-heading)
7406 (org-defkey map [(up)] 'outline-previous-visible-heading)
7407 (if org-goto-auto-isearch
7408 (if (fboundp 'define-key-after)
7409 (define-key-after map [t] 'org-goto-local-auto-isearch)
7410 nil)
7411 (org-defkey map "q" 'org-goto-quit)
7412 (org-defkey map "n" 'outline-next-visible-heading)
7413 (org-defkey map "p" 'outline-previous-visible-heading)
7414 (org-defkey map "f" 'outline-forward-same-level)
7415 (org-defkey map "b" 'outline-backward-same-level)
7416 (org-defkey map "u" 'outline-up-heading))
7417 (org-defkey map "/" 'org-occur)
7418 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7419 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7420 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7421 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7422 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7423 map)))
7425 (defconst org-goto-help
7426 "Browse buffer copy, to find location or copy text.%s
7427 RET=jump to location C-g=quit and return to previous location
7428 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7430 (defvar org-goto-start-pos) ; dynamically scoped parameter
7432 (defun org-goto (&optional alternative-interface)
7433 "Look up a different location in the current file, keeping current visibility.
7435 When you want look-up or go to a different location in a
7436 document, the fastest way is often to fold the entire buffer and
7437 then dive into the tree. This method has the disadvantage, that
7438 the previous location will be folded, which may not be what you
7439 want.
7441 This command works around this by showing a copy of the current
7442 buffer in an indirect buffer, in overview mode. You can dive
7443 into the tree in that copy, use org-occur and incremental search
7444 to find a location. When pressing RET or `Q', the command
7445 returns to the original buffer in which the visibility is still
7446 unchanged. After RET it will also jump to the location selected
7447 in the indirect buffer and expose the headline hierarchy above.
7449 With a prefix argument, use the alternative interface: e.g., if
7450 `org-goto-interface' is `outline' use `outline-path-completion'."
7451 (interactive "P")
7452 (org-goto-map)
7453 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7454 (org-refile-use-outline-path t)
7455 (org-refile-target-verify-function nil)
7456 (interface
7457 (if (not alternative-interface)
7458 org-goto-interface
7459 (if (eq org-goto-interface 'outline)
7460 'outline-path-completion
7461 'outline)))
7462 (org-goto-start-pos (point))
7463 (selected-point
7464 (if (eq interface 'outline)
7465 (car (org-get-location (current-buffer) org-goto-help))
7466 (let ((pa (org-refile-get-location "Goto")))
7467 (org-refile-check-position pa)
7468 (nth 3 pa)))))
7469 (if selected-point
7470 (progn
7471 (org-mark-ring-push org-goto-start-pos)
7472 (goto-char selected-point)
7473 (when (or (org-invisible-p) (org-invisible-p2))
7474 (org-show-context 'org-goto)))
7475 (message "Quit"))))
7477 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7478 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7479 (defvar org-goto-local-auto-isearch-map) ; defined below
7481 (defun org-get-location (_buf help)
7482 "Let the user select a location in current buffer.
7483 This function uses a recursive edit. It returns the selected position
7484 or nil."
7485 (org-no-popups
7486 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7487 (isearch-hide-immediately nil)
7488 (isearch-search-fun-function
7489 (lambda () 'org-goto-local-search-headings))
7490 (org-goto-selected-point org-goto-exit-command))
7491 (save-excursion
7492 (save-window-excursion
7493 (delete-other-windows)
7494 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7495 (pop-to-buffer-same-window
7496 (condition-case nil
7497 (make-indirect-buffer (current-buffer) "*org-goto*")
7498 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7499 (with-output-to-temp-buffer "*Org Help*"
7500 (princ (format help (if org-goto-auto-isearch
7501 " Just type for auto-isearch."
7502 " n/p/f/b/u to navigate, q to quit."))))
7503 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7504 (setq buffer-read-only nil)
7505 (let ((org-startup-truncated t)
7506 (org-startup-folded nil)
7507 (org-startup-align-all-tables nil))
7508 (org-mode)
7509 (org-overview))
7510 (setq buffer-read-only t)
7511 (if (and (boundp 'org-goto-start-pos)
7512 (integer-or-marker-p org-goto-start-pos))
7513 (progn (goto-char org-goto-start-pos)
7514 (when (org-invisible-p)
7515 (org-show-set-visibility 'lineage)))
7516 (goto-char (point-min)))
7517 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7518 (message "Select location and press RET")
7519 (use-local-map org-goto-map)
7520 (recursive-edit)))
7521 (kill-buffer "*org-goto*")
7522 (cons org-goto-selected-point org-goto-exit-command))))
7524 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7525 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7526 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7527 (if (fboundp 'isearch-other-control-char)
7528 (progn
7529 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7530 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7531 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7532 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7533 (define-key org-goto-local-auto-isearch-map [return] nil))
7535 (defun org-goto-local-search-headings (string bound noerror)
7536 "Search and make sure that any matches are in headlines."
7537 (catch 'return
7538 (while (if isearch-forward
7539 (search-forward string bound noerror)
7540 (search-backward string bound noerror))
7541 (when (save-match-data
7542 (and (save-excursion
7543 (beginning-of-line)
7544 (looking-at org-complex-heading-regexp))
7545 (or (not (match-beginning 5))
7546 (< (point) (match-beginning 5)))))
7547 (throw 'return (point))))))
7549 (defun org-goto-local-auto-isearch ()
7550 "Start isearch."
7551 (interactive)
7552 (goto-char (point-min))
7553 (let ((keys (this-command-keys)))
7554 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7555 (isearch-mode t)
7556 (isearch-process-search-char (string-to-char keys)))))
7558 (defun org-goto-ret (&optional _arg)
7559 "Finish `org-goto' by going to the new location."
7560 (interactive "P")
7561 (setq org-goto-selected-point (point))
7562 (setq org-goto-exit-command 'return)
7563 (throw 'exit nil))
7565 (defun org-goto-left ()
7566 "Finish `org-goto' by going to the new location."
7567 (interactive)
7568 (if (org-at-heading-p)
7569 (progn
7570 (beginning-of-line 1)
7571 (setq org-goto-selected-point (point)
7572 org-goto-exit-command 'left)
7573 (throw 'exit nil))
7574 (user-error "Not on a heading")))
7576 (defun org-goto-right ()
7577 "Finish `org-goto' by going to the new location."
7578 (interactive)
7579 (if (org-at-heading-p)
7580 (progn
7581 (setq org-goto-selected-point (point)
7582 org-goto-exit-command 'right)
7583 (throw 'exit nil))
7584 (user-error "Not on a heading")))
7586 (defun org-goto-quit ()
7587 "Finish `org-goto' without cursor motion."
7588 (interactive)
7589 (setq org-goto-selected-point nil)
7590 (setq org-goto-exit-command 'quit)
7591 (throw 'exit nil))
7593 ;;; Indirect buffer display of subtrees
7595 (defvar org-indirect-dedicated-frame nil
7596 "This is the frame being used for indirect tree display.")
7597 (defvar org-last-indirect-buffer nil)
7599 (defun org-tree-to-indirect-buffer (&optional arg)
7600 "Create indirect buffer and narrow it to current subtree.
7602 With a numerical prefix ARG, go up to this level and then take that tree.
7603 If ARG is negative, go up that many levels.
7605 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7606 indirect buffer previously made with this command, to avoid proliferation of
7607 indirect buffers. However, when you call the command with a \
7608 `\\[universal-argument]' prefix, or
7609 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7610 so that you can work with several indirect buffers at the same time. If
7611 `org-indirect-buffer-display' is `dedicated-frame', the \
7612 `\\[universal-argument]' prefix also
7613 requests that a new frame be made for the new buffer, so that the dedicated
7614 frame is not changed."
7615 (interactive "P")
7616 (let ((cbuf (current-buffer))
7617 (cwin (selected-window))
7618 (pos (point))
7619 beg end level heading ibuf)
7620 (save-excursion
7621 (org-back-to-heading t)
7622 (when (numberp arg)
7623 (setq level (org-outline-level))
7624 (when (< arg 0) (setq arg (+ level arg)))
7625 (while (> (setq level (org-outline-level)) arg)
7626 (org-up-heading-safe)))
7627 (setq beg (point)
7628 heading (org-get-heading 'no-tags))
7629 (org-end-of-subtree t t)
7630 (when (org-at-heading-p) (backward-char 1))
7631 (setq end (point)))
7632 (when (and (buffer-live-p org-last-indirect-buffer)
7633 (not (eq org-indirect-buffer-display 'new-frame))
7634 (not arg))
7635 (kill-buffer org-last-indirect-buffer))
7636 (setq ibuf (org-get-indirect-buffer cbuf heading)
7637 org-last-indirect-buffer ibuf)
7638 (cond
7639 ((or (eq org-indirect-buffer-display 'new-frame)
7640 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7641 (select-frame (make-frame))
7642 (delete-other-windows)
7643 (pop-to-buffer-same-window ibuf)
7644 (org-set-frame-title heading))
7645 ((eq org-indirect-buffer-display 'dedicated-frame)
7646 (raise-frame
7647 (select-frame (or (and org-indirect-dedicated-frame
7648 (frame-live-p org-indirect-dedicated-frame)
7649 org-indirect-dedicated-frame)
7650 (setq org-indirect-dedicated-frame (make-frame)))))
7651 (delete-other-windows)
7652 (pop-to-buffer-same-window ibuf)
7653 (org-set-frame-title (concat "Indirect: " heading)))
7654 ((eq org-indirect-buffer-display 'current-window)
7655 (pop-to-buffer-same-window ibuf))
7656 ((eq org-indirect-buffer-display 'other-window)
7657 (pop-to-buffer ibuf))
7658 (t (error "Invalid value")))
7659 (narrow-to-region beg end)
7660 (outline-show-all)
7661 (goto-char pos)
7662 (run-hook-with-args 'org-cycle-hook 'all)
7663 (and (window-live-p cwin) (select-window cwin))))
7665 (defun org-get-indirect-buffer (&optional buffer heading)
7666 (setq buffer (or buffer (current-buffer)))
7667 (let ((n 1) (base (buffer-name buffer)) bname)
7668 (while (buffer-live-p
7669 (get-buffer
7670 (setq bname
7671 (concat base "-"
7672 (if heading (concat heading "-" (number-to-string n))
7673 (number-to-string n))))))
7674 (setq n (1+ n)))
7675 (condition-case nil
7676 (make-indirect-buffer buffer bname 'clone)
7677 (error (make-indirect-buffer buffer bname)))))
7679 (defun org-set-frame-title (title)
7680 "Set the title of the current frame to the string TITLE."
7681 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7683 ;;;; Structure editing
7685 ;;; Inserting headlines
7687 (defun org--line-empty-p (n)
7688 "Is the Nth next line empty?
7690 Counts the current line as N = 1 and the previous line as N = 0;
7691 see `beginning-of-line'."
7692 (save-excursion
7693 (and (not (bobp))
7694 (or (beginning-of-line n) t)
7695 (save-match-data
7696 (looking-at "[ \t]*$")))))
7698 (defun org-previous-line-empty-p ()
7699 "Is the previous line a blank line?
7700 When NEXT is non-nil, check the next line instead."
7701 (org--line-empty-p 0))
7703 (defun org-next-line-empty-p ()
7704 "Is the previous line a blank line?
7705 When NEXT is non-nil, check the next line instead."
7706 (org--line-empty-p 2))
7708 (defun org--blank-before-heading-p (&optional parent)
7709 "Non-nil when an empty line should precede a new heading here.
7710 When optional argument PARENT is non-nil, consider parent
7711 headline instead of current one."
7712 (pcase (assq 'heading org-blank-before-new-entry)
7713 (`(heading . auto)
7714 (save-excursion
7715 (org-with-limited-levels
7716 (unless (and (org-before-first-heading-p)
7717 (not (outline-next-heading)))
7718 (org-back-to-heading t)
7719 (when parent (org-up-heading-safe))
7720 (cond ((not (bobp))
7721 (org-previous-line-empty-p))
7722 ((outline-next-heading)
7723 (org-previous-line-empty-p))
7724 ;; Ignore trailing spaces on last buffer line.
7725 ((progn (skip-chars-backward " \t") (bolp))
7726 (org-previous-line-empty-p))
7727 (t nil))))))
7728 (`(heading . ,value) value)
7729 (_ nil)))
7731 (defun org-insert-heading (&optional arg invisible-ok top)
7732 "Insert a new heading or an item with the same depth at point.
7734 If point is at the beginning of a heading, insert a new heading
7735 or a new headline above the current one. When at the beginning
7736 of a regular line of text, turn it into a heading.
7738 If point is in the middle of a line, split it and create a new
7739 headline with the text in the current line after point (see
7740 `org-M-RET-may-split-line' on how to modify this behavior). As
7741 a special case, on a headline, splitting can only happen on the
7742 title itself. E.g., this excludes breaking stars or tags.
7744 With a `\\[universal-argument]' prefix, set \
7745 `org-insert-heading-respect-content' to
7746 a non-nil value for the duration of the command. This forces the
7747 insertion of a heading after the current subtree, independently
7748 on the location of point.
7750 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7751 insert the heading at the end of the tree
7752 above the current heading. For example, if point is within a
7753 2nd-level heading, then it will insert a 2nd-level heading at
7754 the end of the 1st-level parent subtree.
7756 When INVISIBLE-OK is set, stop at invisible headlines when going
7757 back. This is important for non-interactive uses of the
7758 command.
7760 When optional argument TOP is non-nil, insert a level 1 heading,
7761 unconditionally."
7762 (interactive "P")
7763 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7764 (level (org-current-level))
7765 (stars (make-string (if (and level (not top)) level 1) ?*)))
7766 (cond
7767 ((or org-insert-heading-respect-content
7768 (member arg '((4) (16)))
7769 (and (not invisible-ok)
7770 (invisible-p (max (1- (point)) (point-min)))))
7771 ;; Position point at the location of insertion.
7772 (if (not level) ;before first headline
7773 (org-with-limited-levels (outline-next-heading))
7774 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7775 ;; is nil.
7776 (org-with-limited-levels (org-back-to-heading invisible-ok))
7777 (cond ((equal arg '(16))
7778 (org-up-heading-safe)
7779 (org-end-of-subtree t t))
7781 (org-end-of-subtree t t))))
7782 (unless (bolp) (insert "\n")) ;ensure final newline
7783 (unless (and blank? (org-previous-line-empty-p))
7784 (org-N-empty-lines-before-current (if blank? 1 0)))
7785 (insert stars " \n")
7786 (forward-char -1))
7787 ;; At a headline...
7788 ((org-at-heading-p)
7789 (cond ((bolp)
7790 (when blank? (save-excursion (insert "\n")))
7791 (save-excursion (insert stars " \n"))
7792 (unless (and blank? (org-previous-line-empty-p))
7793 (org-N-empty-lines-before-current (if blank? 1 0)))
7794 (end-of-line))
7795 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7796 (org-match-line org-complex-heading-regexp)
7797 (org-pos-in-match-range (point) 4))
7798 ;; Grab the text that should moved to the new headline.
7799 ;; Preserve tags.
7800 (let ((split (delete-and-extract-region (point) (match-end 4))))
7801 (if (looking-at "[ \t]*$") (replace-match "")
7802 (org-set-tags nil t))
7803 (end-of-line)
7804 (when blank? (insert "\n"))
7805 (insert "\n" stars " ")
7806 (when (org-string-nw-p split) (insert split))
7807 (when (eobp) (save-excursion (insert "\n")))))
7809 (end-of-line)
7810 (when blank? (insert "\n"))
7811 (insert "\n" stars " ")
7812 (when (eobp) (save-excursion (insert "\n"))))))
7813 ;; On regular text, turn line into a headline or split, if
7814 ;; appropriate.
7815 ((bolp)
7816 (insert stars " ")
7817 (unless (and blank? (org-previous-line-empty-p))
7818 (org-N-empty-lines-before-current (if blank? 1 0))))
7820 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7821 (end-of-line))
7822 (insert "\n" stars " ")
7823 (unless (and blank? (org-previous-line-empty-p))
7824 (org-N-empty-lines-before-current (if blank? 1 0))))))
7825 (run-hooks 'org-insert-heading-hook))
7827 (defun org-N-empty-lines-before-current (n)
7828 "Make the number of empty lines before current exactly N.
7829 So this will delete or add empty lines."
7830 (let ((column (current-column)))
7831 (beginning-of-line)
7832 (unless (bobp)
7833 (let ((start (save-excursion
7834 (skip-chars-backward " \r\t\n")
7835 (line-end-position))))
7836 (delete-region start (line-end-position 0))))
7837 (insert (make-string n ?\n))
7838 (move-to-column column)))
7840 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7841 "Return the heading of the current entry, without the stars.
7842 When NO-TAGS is non-nil, don't include tags.
7843 When NO-TODO is non-nil, don't include TODO keywords.
7844 When NO-PRIORITY is non-nil, don't include priority cookie.
7845 When NO-COMMENT is non-nil, don't include COMMENT string."
7846 (save-excursion
7847 (org-back-to-heading t)
7848 (let ((case-fold-search nil))
7849 (looking-at org-complex-heading-regexp)
7850 (let ((todo (and (not no-todo) (match-string 2)))
7851 (priority (and (not no-priority) (match-string 3)))
7852 (headline (pcase (match-string 4)
7853 (`nil "")
7854 ((and (guard no-comment) h)
7855 (replace-regexp-in-string
7856 (eval-when-compile
7857 (format "\\`%s[ \t]+" org-comment-string))
7858 "" h))
7859 (h h)))
7860 (tags (and (not no-tags) (match-string 5))))
7861 (mapconcat #'identity
7862 (delq nil (list todo priority headline tags))
7863 " ")))))
7865 (defvar orgstruct-mode) ; defined below
7867 (defun org-heading-components ()
7868 "Return the components of the current heading.
7869 This is a list with the following elements:
7870 - the level as an integer
7871 - the reduced level, different if `org-odd-levels-only' is set.
7872 - the TODO keyword, or nil
7873 - the priority character, like ?A, or nil if no priority is given
7874 - the headline text itself, or the tags string if no headline text
7875 - the tags string, or nil."
7876 (save-excursion
7877 (org-back-to-heading t)
7878 (when (let (case-fold-search)
7879 (looking-at
7880 (if orgstruct-mode
7881 org-heading-regexp
7882 org-complex-heading-regexp)))
7883 (if orgstruct-mode
7884 (list (length (match-string 1))
7885 (org-reduced-level (length (match-string 1)))
7888 (match-string 2)
7889 nil)
7890 (list (length (match-string 1))
7891 (org-reduced-level (length (match-string 1)))
7892 (match-string-no-properties 2)
7893 (and (match-end 3) (aref (match-string 3) 2))
7894 (match-string-no-properties 4)
7895 (match-string-no-properties 5))))))
7897 (defun org-get-entry ()
7898 "Get the entry text, after heading, entire subtree."
7899 (save-excursion
7900 (org-back-to-heading t)
7901 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7903 (defun org-edit-headline (&optional heading)
7904 "Edit the current headline.
7905 Set it to HEADING when provided."
7906 (interactive)
7907 (org-with-wide-buffer
7908 (org-back-to-heading t)
7909 (let ((case-fold-search nil))
7910 (when (looking-at org-complex-heading-regexp)
7911 (let* ((old (match-string-no-properties 4))
7912 (new (save-match-data
7913 (org-trim (or heading (read-string "Edit: " old))))))
7914 (unless (equal old new)
7915 (if old (replace-match new t t nil 4)
7916 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7917 (insert " " new))
7918 (org-set-tags nil t)
7919 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7921 (defun org-insert-heading-after-current ()
7922 "Insert a new heading with same level as current, after current subtree."
7923 (interactive)
7924 (org-back-to-heading)
7925 (org-insert-heading)
7926 (org-move-subtree-down)
7927 (end-of-line 1))
7929 (defun org-insert-heading-respect-content (&optional invisible-ok)
7930 "Insert heading with `org-insert-heading-respect-content' set to t."
7931 (interactive)
7932 (org-insert-heading '(4) invisible-ok))
7934 (defun org-insert-todo-heading-respect-content (&optional force-state)
7935 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7936 (interactive)
7937 (org-insert-todo-heading force-state '(4)))
7939 (defun org-insert-todo-heading (arg &optional force-heading)
7940 "Insert a new heading with the same level and TODO state as current heading.
7942 If the heading has no TODO state, or if the state is DONE, use
7943 the first state (TODO by default). Also with one prefix arg,
7944 force first state. With two prefix args, force inserting at the
7945 end of the parent subtree.
7947 When called at a plain list item, insert a new item with an
7948 unchecked check box."
7949 (interactive "P")
7950 (when (or force-heading (not (org-insert-item 'checkbox)))
7951 (org-insert-heading (or (and (equal arg '(16)) '(16))
7952 force-heading))
7953 (save-excursion
7954 (org-back-to-heading)
7955 (outline-previous-heading)
7956 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7957 (let* ((new-mark-x
7958 (if (or (equal arg '(4))
7959 (not (match-beginning 2))
7960 (member (match-string 2) org-done-keywords))
7961 (car org-todo-keywords-1)
7962 (match-string 2)))
7963 (new-mark
7965 (run-hook-with-args-until-success
7966 'org-todo-get-default-hook new-mark-x nil)
7967 new-mark-x)))
7968 (beginning-of-line 1)
7969 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7970 (if org-treat-insert-todo-heading-as-state-change
7971 (org-todo new-mark)
7972 (insert new-mark " "))))
7973 (when org-provide-todo-statistics
7974 (org-update-parent-todo-statistics))))
7976 (defun org-insert-subheading (arg)
7977 "Insert a new subheading and demote it.
7978 Works for outline headings and for plain lists alike."
7979 (interactive "P")
7980 (org-insert-heading arg)
7981 (cond
7982 ((org-at-heading-p) (org-do-demote))
7983 ((org-at-item-p) (org-indent-item))))
7985 (defun org-insert-todo-subheading (arg)
7986 "Insert a new subheading with TODO keyword or checkbox and demote it.
7987 Works for outline headings and for plain lists alike."
7988 (interactive "P")
7989 (org-insert-todo-heading arg)
7990 (cond
7991 ((org-at-heading-p) (org-do-demote))
7992 ((org-at-item-p) (org-indent-item))))
7994 ;;; Promotion and Demotion
7996 (defvar org-after-demote-entry-hook nil
7997 "Hook run after an entry has been demoted.
7998 The cursor will be at the beginning of the entry.
7999 When a subtree is being demoted, the hook will be called for each node.")
8001 (defvar org-after-promote-entry-hook nil
8002 "Hook run after an entry has been promoted.
8003 The cursor will be at the beginning of the entry.
8004 When a subtree is being promoted, the hook will be called for each node.")
8006 (defun org-promote-subtree ()
8007 "Promote the entire subtree.
8008 See also `org-promote'."
8009 (interactive)
8010 (save-excursion
8011 (org-with-limited-levels (org-map-tree 'org-promote)))
8012 (org-fix-position-after-promote))
8014 (defun org-demote-subtree ()
8015 "Demote the entire subtree.
8016 See `org-demote' and `org-promote'."
8017 (interactive)
8018 (save-excursion
8019 (org-with-limited-levels (org-map-tree 'org-demote)))
8020 (org-fix-position-after-promote))
8022 (defun org-do-promote ()
8023 "Promote the current heading higher up the tree.
8024 If the region is active in `transient-mark-mode', promote all
8025 headings in the region."
8026 (interactive)
8027 (save-excursion
8028 (if (org-region-active-p)
8029 (org-map-region 'org-promote (region-beginning) (region-end))
8030 (org-promote)))
8031 (org-fix-position-after-promote))
8033 (defun org-do-demote ()
8034 "Demote the current heading lower down the tree.
8035 If the region is active in `transient-mark-mode', demote all
8036 headings in the region."
8037 (interactive)
8038 (save-excursion
8039 (if (org-region-active-p)
8040 (org-map-region 'org-demote (region-beginning) (region-end))
8041 (org-demote)))
8042 (org-fix-position-after-promote))
8044 (defun org-fix-position-after-promote ()
8045 "Fix cursor position and indentation after demoting/promoting."
8046 (let ((pos (point)))
8047 (when (save-excursion
8048 (beginning-of-line)
8049 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8050 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8051 (cond ((eobp) (insert " "))
8052 ((eolp) (insert " "))
8053 ((equal (char-after) ?\s) (forward-char 1))))))
8055 (defun org-current-level ()
8056 "Return the level of the current entry, or nil if before the first headline.
8057 The level is the number of stars at the beginning of the
8058 headline. Use `org-reduced-level' to remove the effect of
8059 `org-odd-levels'. Unlike to `org-outline-level', this function
8060 ignores inlinetasks."
8061 (let ((level (org-with-limited-levels (org-outline-level))))
8062 (and (> level 0) level)))
8064 (defun org-get-previous-line-level ()
8065 "Return the outline depth of the last headline before the current line.
8066 Returns 0 for the first headline in the buffer, and nil if before the
8067 first headline."
8068 (and (org-current-level)
8069 (or (and (/= (line-beginning-position) (point-min))
8070 (save-excursion (beginning-of-line 0) (org-current-level)))
8071 0)))
8073 (defun org-reduced-level (l)
8074 "Compute the effective level of a heading.
8075 This takes into account the setting of `org-odd-levels-only'."
8076 (cond
8077 ((zerop l) 0)
8078 (org-odd-levels-only (1+ (floor (/ l 2))))
8079 (t l)))
8081 (defun org-level-increment ()
8082 "Return the number of stars that will be added or removed at a
8083 time to headlines when structure editing, based on the value of
8084 `org-odd-levels-only'."
8085 (if org-odd-levels-only 2 1))
8087 (defun org-get-valid-level (level &optional change)
8088 "Rectify a level change under the influence of `org-odd-levels-only'.
8089 LEVEL is a current level, CHANGE is by how much the level should
8090 be modified. Even if CHANGE is nil, LEVEL may be returned
8091 modified because even level numbers will become the next higher
8092 odd number. Returns values greater than 0."
8093 (if org-odd-levels-only
8094 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8095 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8096 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8097 (max 1 (+ level (or change 0)))))
8099 (defun org-promote ()
8100 "Promote the current heading higher up the tree."
8101 (org-with-wide-buffer
8102 (org-back-to-heading t)
8103 (let* ((after-change-functions (remq 'flyspell-after-change-function
8104 after-change-functions))
8105 (level (save-match-data (funcall outline-level)))
8106 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8107 (diff (abs (- level (length up-head) -1))))
8108 (cond
8109 ((and (= level 1) org-allow-promoting-top-level-subtree)
8110 (replace-match "# " nil t))
8111 ((= level 1)
8112 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8113 (t (replace-match up-head nil t)))
8114 (unless (= level 1)
8115 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8116 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8117 (run-hooks 'org-after-promote-entry-hook))))
8119 (defun org-demote ()
8120 "Demote the current heading lower down the tree."
8121 (org-with-wide-buffer
8122 (org-back-to-heading t)
8123 (let* ((after-change-functions (remq 'flyspell-after-change-function
8124 after-change-functions))
8125 (level (save-match-data (funcall outline-level)))
8126 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8127 (diff (abs (- level (length down-head) -1))))
8128 (replace-match down-head nil t)
8129 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8130 (when org-adapt-indentation (org-fixup-indentation diff))
8131 (run-hooks 'org-after-demote-entry-hook))))
8133 (defun org-cycle-level ()
8134 "Cycle the level of an empty headline through possible states.
8135 This goes first to child, then to parent, level, then up the hierarchy.
8136 After top level, it switches back to sibling level."
8137 (interactive)
8138 (let ((org-adapt-indentation nil))
8139 (when (org-point-at-end-of-empty-headline)
8140 (setq this-command 'org-cycle-level) ; Only needed for caching
8141 (let ((cur-level (org-current-level))
8142 (prev-level (org-get-previous-line-level)))
8143 (cond
8144 ;; If first headline in file, promote to top-level.
8145 ((= prev-level 0)
8146 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8147 do (org-do-promote)))
8148 ;; If same level as prev, demote one.
8149 ((= prev-level cur-level)
8150 (org-do-demote))
8151 ;; If parent is top-level, promote to top level if not already.
8152 ((= prev-level 1)
8153 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8154 do (org-do-promote)))
8155 ;; If top-level, return to prev-level.
8156 ((= cur-level 1)
8157 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8158 do (org-do-demote)))
8159 ;; If less than prev-level, promote one.
8160 ((< cur-level prev-level)
8161 (org-do-promote))
8162 ;; If deeper than prev-level, promote until higher than
8163 ;; prev-level.
8164 ((> cur-level prev-level)
8165 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8166 do (org-do-promote))))
8167 t))))
8169 (defun org-map-tree (fun)
8170 "Call FUN for every heading underneath the current one."
8171 (org-back-to-heading t)
8172 (let ((level (funcall outline-level)))
8173 (save-excursion
8174 (funcall fun)
8175 (while (and (progn
8176 (outline-next-heading)
8177 (> (funcall outline-level) level))
8178 (not (eobp)))
8179 (funcall fun)))))
8181 (defun org-map-region (fun beg end)
8182 "Call FUN for every heading between BEG and END."
8183 (let ((org-ignore-region t))
8184 (save-excursion
8185 (setq end (copy-marker end))
8186 (goto-char beg)
8187 (when (and (re-search-forward org-outline-regexp-bol nil t)
8188 (< (point) end))
8189 (funcall fun))
8190 (while (and (progn
8191 (outline-next-heading)
8192 (< (point) end))
8193 (not (eobp)))
8194 (funcall fun)))))
8196 (defun org-fixup-indentation (diff)
8197 "Change the indentation in the current entry by DIFF.
8199 DIFF is an integer. Indentation is done according to the
8200 following rules:
8202 - Planning information and property drawers are always indented
8203 according to the new level of the headline;
8205 - Footnote definitions and their contents are ignored;
8207 - Inlinetasks' boundaries are not shifted;
8209 - Empty lines are ignored;
8211 - Other lines' indentation are shifted by DIFF columns, unless
8212 it would introduce a structural change in the document, in
8213 which case no shifting is done at all.
8215 Assume point is at a heading or an inlinetask beginning."
8216 (org-with-wide-buffer
8217 (narrow-to-region (line-beginning-position)
8218 (save-excursion
8219 (if (org-with-limited-levels (org-at-heading-p))
8220 (org-with-limited-levels (outline-next-heading))
8221 (org-inlinetask-goto-end))
8222 (point)))
8223 (forward-line)
8224 ;; Indent properly planning info and property drawer.
8225 (when (looking-at-p org-planning-line-re)
8226 (org-indent-line)
8227 (forward-line))
8228 (when (looking-at org-property-drawer-re)
8229 (goto-char (match-end 0))
8230 (forward-line)
8231 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8232 (catch 'no-shift
8233 (when (zerop diff) (throw 'no-shift nil))
8234 ;; If DIFF is negative, first check if a shift is possible at all
8235 ;; (e.g., it doesn't break structure). This can only happen if
8236 ;; some contents are not properly indented.
8237 (let ((case-fold-search t))
8238 (when (< diff 0)
8239 (let ((diff (- diff))
8240 (forbidden-re (concat org-outline-regexp
8241 "\\|"
8242 (substring org-footnote-definition-re 1))))
8243 (save-excursion
8244 (while (not (eobp))
8245 (cond
8246 ((looking-at-p "[ \t]*$") (forward-line))
8247 ((and (looking-at-p org-footnote-definition-re)
8248 (let ((e (org-element-at-point)))
8249 (and (eq (org-element-type e) 'footnote-definition)
8250 (goto-char (org-element-property :end e))))))
8251 ((looking-at-p org-outline-regexp) (forward-line))
8252 ;; Give up if shifting would move before column 0 or
8253 ;; if it would introduce a headline or a footnote
8254 ;; definition.
8256 (skip-chars-forward " \t")
8257 (let ((ind (current-column)))
8258 (when (or (< ind diff)
8259 (and (= ind diff) (looking-at-p forbidden-re)))
8260 (throw 'no-shift nil)))
8261 ;; Ignore contents of example blocks and source
8262 ;; blocks if their indentation is meant to be
8263 ;; preserved. Jump to block's closing line.
8264 (beginning-of-line)
8265 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8266 (let ((e (org-element-at-point)))
8267 (and (memq (org-element-type e)
8268 '(example-block src-block))
8269 (or org-src-preserve-indentation
8270 (org-element-property :preserve-indent e))
8271 (goto-char (org-element-property :end e))
8272 (progn (skip-chars-backward " \r\t\n")
8273 (beginning-of-line)
8274 t))))
8275 (forward-line))))))))
8276 ;; Shift lines but footnote definitions, inlinetasks boundaries
8277 ;; by DIFF. Also skip contents of source or example blocks
8278 ;; when indentation is meant to be preserved.
8279 (while (not (eobp))
8280 (cond
8281 ((and (looking-at-p org-footnote-definition-re)
8282 (let ((e (org-element-at-point)))
8283 (and (eq (org-element-type e) 'footnote-definition)
8284 (goto-char (org-element-property :end e))))))
8285 ((looking-at-p org-outline-regexp) (forward-line))
8286 ((looking-at-p "[ \t]*$") (forward-line))
8288 (indent-line-to (+ (org-get-indentation) diff))
8289 (beginning-of-line)
8290 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8291 (let ((e (org-element-at-point)))
8292 (and (memq (org-element-type e)
8293 '(example-block src-block))
8294 (or org-src-preserve-indentation
8295 (org-element-property :preserve-indent e))
8296 (goto-char (org-element-property :end e))
8297 (progn (skip-chars-backward " \r\t\n")
8298 (beginning-of-line)
8299 t))))
8300 (forward-line)))))))))
8302 (defun org-convert-to-odd-levels ()
8303 "Convert an Org file with all levels allowed to one with odd levels.
8304 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8305 level 5 etc."
8306 (interactive)
8307 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8308 (let ((outline-level 'org-outline-level)
8309 (org-odd-levels-only nil) n)
8310 (save-excursion
8311 (goto-char (point-min))
8312 (while (re-search-forward "^\\*\\*+ " nil t)
8313 (setq n (- (length (match-string 0)) 2))
8314 (while (>= (setq n (1- n)) 0)
8315 (org-demote))
8316 (end-of-line 1))))))
8318 (defun org-convert-to-oddeven-levels ()
8319 "Convert an Org file with only odd levels to one with odd/even levels.
8320 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8321 file contains a section with an even level, conversion would
8322 destroy the structure of the file. An error is signaled in this
8323 case."
8324 (interactive)
8325 (goto-char (point-min))
8326 ;; First check if there are no even levels
8327 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8328 (org-show-set-visibility 'canonical)
8329 (error "Not all levels are odd in this file. Conversion not possible"))
8330 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8331 (let ((outline-regexp org-outline-regexp)
8332 (outline-level 'org-outline-level)
8333 (org-odd-levels-only nil) n)
8334 (save-excursion
8335 (goto-char (point-min))
8336 (while (re-search-forward "^\\*\\*+ " nil t)
8337 (setq n (/ (1- (length (match-string 0))) 2))
8338 (while (>= (setq n (1- n)) 0)
8339 (org-promote))
8340 (end-of-line 1))))))
8342 (defun org-tr-level (n)
8343 "Make N odd if required."
8344 (if org-odd-levels-only (1+ (/ n 2)) n))
8346 ;;; Vertical tree motion, cutting and pasting of subtrees
8348 (defun org-move-subtree-up (&optional arg)
8349 "Move the current subtree up past ARG headlines of the same level."
8350 (interactive "p")
8351 (org-move-subtree-down (- (prefix-numeric-value arg))))
8353 (defun org-move-subtree-down (&optional arg)
8354 "Move the current subtree down past ARG headlines of the same level."
8355 (interactive "p")
8356 (setq arg (prefix-numeric-value arg))
8357 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8358 'org-get-last-sibling))
8359 (ins-point (make-marker))
8360 (cnt (abs arg))
8361 (col (current-column))
8362 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8363 ;; Select the tree
8364 (org-back-to-heading)
8365 (setq beg0 (point))
8366 (save-excursion
8367 (setq ne-beg (org-back-over-empty-lines))
8368 (setq beg (point)))
8369 (save-match-data
8370 (save-excursion (outline-end-of-heading)
8371 (setq folded (org-invisible-p)))
8372 (progn (org-end-of-subtree nil t)
8373 (unless (eobp) (backward-char))))
8374 (outline-next-heading)
8375 (setq ne-end (org-back-over-empty-lines))
8376 (setq end (point))
8377 (goto-char beg0)
8378 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8379 ;; include less whitespace
8380 (save-excursion
8381 (goto-char beg)
8382 (forward-line (- ne-beg ne-end))
8383 (setq beg (point))))
8384 ;; Find insertion point, with error handling
8385 (while (> cnt 0)
8386 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8387 (progn (goto-char beg0)
8388 (user-error "Cannot move past superior level or buffer limit")))
8389 (setq cnt (1- cnt)))
8390 (when (> arg 0)
8391 ;; Moving forward - still need to move over subtree
8392 (org-end-of-subtree t t)
8393 (save-excursion
8394 (org-back-over-empty-lines)
8395 (or (bolp) (newline))))
8396 (setq ne-ins (org-back-over-empty-lines))
8397 (move-marker ins-point (point))
8398 (setq txt (buffer-substring beg end))
8399 (org-save-markers-in-region beg end)
8400 (delete-region beg end)
8401 (org-remove-empty-overlays-at beg)
8402 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8403 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8404 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8405 (let ((bbb (point)))
8406 (insert-before-markers txt)
8407 (org-reinstall-markers-in-region bbb)
8408 (move-marker ins-point bbb))
8409 (or (bolp) (insert "\n"))
8410 (setq ins-end (point))
8411 (goto-char ins-point)
8412 (org-skip-whitespace)
8413 (when (and (< arg 0)
8414 (org-first-sibling-p)
8415 (> ne-ins ne-beg))
8416 ;; Move whitespace back to beginning
8417 (save-excursion
8418 (goto-char ins-end)
8419 (let ((kill-whole-line t))
8420 (kill-line (- ne-ins ne-beg)) (point)))
8421 (insert (make-string (- ne-ins ne-beg) ?\n)))
8422 (move-marker ins-point nil)
8423 (if folded
8424 (outline-hide-subtree)
8425 (org-show-entry)
8426 (org-show-children)
8427 (org-cycle-hide-drawers 'children))
8428 (org-clean-visibility-after-subtree-move)
8429 ;; move back to the initial column we were at
8430 (move-to-column col)))
8432 (defvar org-subtree-clip ""
8433 "Clipboard for cut and paste of subtrees.
8434 This is actually only a copy of the kill, because we use the normal kill
8435 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8437 (defvar org-subtree-clip-folded nil
8438 "Was the last copied subtree folded?
8439 This is used to fold the tree back after pasting.")
8441 (defun org-cut-subtree (&optional n)
8442 "Cut the current subtree into the clipboard.
8443 With prefix arg N, cut this many sequential subtrees.
8444 This is a short-hand for marking the subtree and then cutting it."
8445 (interactive "p")
8446 (org-copy-subtree n 'cut))
8448 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8449 "Copy the current subtree it in the clipboard.
8450 With prefix arg N, copy this many sequential subtrees.
8451 This is a short-hand for marking the subtree and then copying it.
8452 If CUT is non-nil, actually cut the subtree.
8453 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8454 of some markers in the region, even if CUT is non-nil. This is
8455 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8456 (interactive "p")
8457 (let (beg end folded (beg0 (point)))
8458 (if (called-interactively-p 'any)
8459 (org-back-to-heading nil) ; take what looks like a subtree
8460 (org-back-to-heading t)) ; take what is really there
8461 (setq beg (point))
8462 (skip-chars-forward " \t\r\n")
8463 (save-match-data
8464 (if nosubtrees
8465 (outline-next-heading)
8466 (save-excursion (outline-end-of-heading)
8467 (setq folded (org-invisible-p)))
8468 (ignore-errors (org-forward-heading-same-level (1- n) t))
8469 (org-end-of-subtree t t)))
8470 ;; Include the end of an inlinetask
8471 (when (and (featurep 'org-inlinetask)
8472 (looking-at-p (concat (org-inlinetask-outline-regexp)
8473 "END[ \t]*$")))
8474 (end-of-line))
8475 (setq end (point))
8476 (goto-char beg0)
8477 (when (> end beg)
8478 (setq org-subtree-clip-folded folded)
8479 (when (or cut force-store-markers)
8480 (org-save-markers-in-region beg end))
8481 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8482 (setq org-subtree-clip (current-kill 0))
8483 (message "%s: Subtree(s) with %d characters"
8484 (if cut "Cut" "Copied")
8485 (length org-subtree-clip)))))
8487 (defun org-paste-subtree (&optional level tree for-yank remove)
8488 "Paste the clipboard as a subtree, with modification of headline level.
8489 The entire subtree is promoted or demoted in order to match a new headline
8490 level.
8492 If the cursor is at the beginning of a headline, the same level as
8493 that headline is used to paste the tree.
8495 If not, the new level is derived from the *visible* headings
8496 before and after the insertion point, and taken to be the inferior headline
8497 level of the two. So if the previous visible heading is level 3 and the
8498 next is level 4 (or vice versa), level 4 will be used for insertion.
8499 This makes sure that the subtree remains an independent subtree and does
8500 not swallow low level entries.
8502 You can also force a different level, either by using a numeric prefix
8503 argument, or by inserting the heading marker by hand. For example, if the
8504 cursor is after \"*****\", then the tree will be shifted to level 5.
8506 If optional TREE is given, use this text instead of the kill ring.
8508 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8509 move back over whitespace before inserting, and move point to the end of
8510 the inserted text when done.
8512 When REMOVE is non-nil, remove the subtree from the clipboard."
8513 (interactive "P")
8514 (setq tree (or tree (and kill-ring (current-kill 0))))
8515 (unless (org-kill-is-subtree-p tree)
8516 (user-error "%s"
8517 (substitute-command-keys
8518 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8519 (org-with-limited-levels
8520 (let* ((visp (not (org-invisible-p)))
8521 (txt tree)
8522 (^re_ "\\(\\*+\\)[ \t]*")
8523 (old-level (if (string-match org-outline-regexp-bol txt)
8524 (- (match-end 0) (match-beginning 0) 1)
8525 -1))
8526 (force-level (cond (level (prefix-numeric-value level))
8527 ((and (looking-at "[ \t]*$")
8528 (string-match
8529 "^\\*+$" (buffer-substring
8530 (point-at-bol) (point))))
8531 (- (match-end 0) (match-beginning 0)))
8532 ((and (bolp)
8533 (looking-at org-outline-regexp))
8534 (- (match-end 0) (point) 1))))
8535 (previous-level (save-excursion
8536 (condition-case nil
8537 (progn
8538 (outline-previous-visible-heading 1)
8539 (if (looking-at ^re_)
8540 (- (match-end 0) (match-beginning 0) 1)
8542 (error 1))))
8543 (next-level (save-excursion
8544 (condition-case nil
8545 (progn
8546 (or (looking-at org-outline-regexp)
8547 (outline-next-visible-heading 1))
8548 (if (looking-at ^re_)
8549 (- (match-end 0) (match-beginning 0) 1)
8551 (error 1))))
8552 (new-level (or force-level (max previous-level next-level)))
8553 (shift (if (or (= old-level -1)
8554 (= new-level -1)
8555 (= old-level new-level))
8557 (- new-level old-level)))
8558 (delta (if (> shift 0) -1 1))
8559 (func (if (> shift 0) 'org-demote 'org-promote))
8560 (org-odd-levels-only nil)
8561 beg end newend)
8562 ;; Remove the forced level indicator
8563 (when force-level
8564 (delete-region (point-at-bol) (point)))
8565 ;; Paste
8566 (beginning-of-line (if (bolp) 1 2))
8567 (setq beg (point))
8568 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8569 (insert-before-markers txt)
8570 (unless (string-suffix-p "\n" txt) (insert "\n"))
8571 (setq newend (point))
8572 (org-reinstall-markers-in-region beg)
8573 (setq end (point))
8574 (goto-char beg)
8575 (skip-chars-forward " \t\n\r")
8576 (setq beg (point))
8577 (when (and (org-invisible-p) visp)
8578 (save-excursion (outline-show-heading)))
8579 ;; Shift if necessary
8580 (unless (= shift 0)
8581 (save-restriction
8582 (narrow-to-region beg end)
8583 (while (not (= shift 0))
8584 (org-map-region func (point-min) (point-max))
8585 (setq shift (+ delta shift)))
8586 (goto-char (point-min))
8587 (setq newend (point-max))))
8588 (when (or (called-interactively-p 'interactive) for-yank)
8589 (message "Clipboard pasted as level %d subtree" new-level))
8590 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8591 kill-ring
8592 (eq org-subtree-clip (current-kill 0))
8593 org-subtree-clip-folded)
8594 ;; The tree was folded before it was killed/copied
8595 (outline-hide-subtree))
8596 (and for-yank (goto-char newend))
8597 (and remove (setq kill-ring (cdr kill-ring))))))
8599 (defun org-kill-is-subtree-p (&optional txt)
8600 "Check if the current kill is an outline subtree, or a set of trees.
8601 Returns nil if kill does not start with a headline, or if the first
8602 headline level is not the largest headline level in the tree.
8603 So this will actually accept several entries of equal levels as well,
8604 which is OK for `org-paste-subtree'.
8605 If optional TXT is given, check this string instead of the current kill."
8606 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8607 (re (org-get-limited-outline-regexp))
8608 (^re (concat "^" re))
8609 (start-level (and kill
8610 (string-match
8611 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8612 kill)
8613 (- (match-end 2) (match-beginning 2) 1)))
8614 (start (1+ (or (match-beginning 2) -1))))
8615 (if (not start-level)
8616 (progn
8617 nil) ;; does not even start with a heading
8618 (catch 'exit
8619 (while (setq start (string-match ^re kill (1+ start)))
8620 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8621 (throw 'exit nil)))
8622 t))))
8624 (defvar org-markers-to-move nil
8625 "Markers that should be moved with a cut-and-paste operation.
8626 Those markers are stored together with their positions relative to
8627 the start of the region.")
8629 (defun org-save-markers-in-region (beg end)
8630 "Check markers in region.
8631 If these markers are between BEG and END, record their position relative
8632 to BEG, so that after moving the block of text, we can put the markers back
8633 into place.
8634 This function gets called just before an entry or tree gets cut from the
8635 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8636 called immediately, to move the markers with the entries."
8637 (setq org-markers-to-move nil)
8638 (when (featurep 'org-clock)
8639 (org-clock-save-markers-for-cut-and-paste beg end))
8640 (when (featurep 'org-agenda)
8641 (org-agenda-save-markers-for-cut-and-paste beg end)))
8643 (defun org-check-and-save-marker (marker beg end)
8644 "Check if MARKER is between BEG and END.
8645 If yes, remember the marker and the distance to BEG."
8646 (when (and (marker-buffer marker)
8647 (equal (marker-buffer marker) (current-buffer))
8648 (>= marker beg) (< marker end))
8649 (push (cons marker (- marker beg)) org-markers-to-move)))
8651 (defun org-reinstall-markers-in-region (beg)
8652 "Move all remembered markers to their position relative to BEG."
8653 (dolist (x org-markers-to-move)
8654 (move-marker (car x) (+ beg (cdr x))))
8655 (setq org-markers-to-move nil))
8657 (defun org-narrow-to-subtree ()
8658 "Narrow buffer to the current subtree."
8659 (interactive)
8660 (save-excursion
8661 (save-match-data
8662 (org-with-limited-levels
8663 (narrow-to-region
8664 (progn (org-back-to-heading t) (point))
8665 (progn (org-end-of-subtree t t)
8666 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8667 (point)))))))
8669 (defun org-narrow-to-block ()
8670 "Narrow buffer to the current block."
8671 (interactive)
8672 (let* ((case-fold-search t)
8673 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8674 "^[ \t]*#\\+end_.*")))
8675 (if blockp
8676 (narrow-to-region (car blockp) (cdr blockp))
8677 (user-error "Not in a block"))))
8679 (defun org-clone-subtree-with-time-shift (n &optional shift)
8680 "Clone the task (subtree) at point N times.
8681 The clones will be inserted as siblings.
8683 In interactive use, the user will be prompted for the number of
8684 clones to be produced. If the entry has a timestamp, the user
8685 will also be prompted for a time shift, which may be a repeater
8686 as used in time stamps, for example `+3d'. To disable this,
8687 you can call the function with a universal prefix argument.
8689 When a valid repeater is given and the entry contains any time
8690 stamps, the clones will become a sequence in time, with time
8691 stamps in the subtree shifted for each clone produced. If SHIFT
8692 is nil or the empty string, time stamps will be left alone. The
8693 ID property of the original subtree is removed.
8695 In each clone, all the CLOCK entries will be removed. This
8696 prevents Org from considering that the clocked times overlap.
8698 If the original subtree did contain time stamps with a repeater,
8699 the following will happen:
8700 - the repeater will be removed in each clone
8701 - an additional clone will be produced, with the current, unshifted
8702 date(s) in the entry.
8703 - the original entry will be placed *after* all the clones, with
8704 repeater intact.
8705 - the start days in the repeater in the original entry will be shifted
8706 to past the last clone.
8707 In this way you can spell out a number of instances of a repeating task,
8708 and still retain the repeater to cover future instances of the task.
8710 As described above, N+1 clones are produced when the original
8711 subtree has a repeater. Setting N to 0, then, can be used to
8712 remove the repeater from a subtree and create a shifted clone
8713 with the original repeater."
8714 (interactive "nNumber of clones to produce: ")
8715 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8716 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8717 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8718 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8719 (shift
8720 (or shift
8721 (if (and (not (equal current-prefix-arg '(4)))
8722 (save-excursion
8723 (goto-char beg)
8724 (re-search-forward org-ts-regexp-both end-of-tree t)))
8725 (read-from-minibuffer
8726 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8727 ""))) ;No time shift
8728 (doshift
8729 (and (org-string-nw-p shift)
8730 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8731 shift)
8732 (user-error "Invalid shift specification %s" shift)))))
8733 (goto-char end-of-tree)
8734 (unless (bolp) (insert "\n"))
8735 (let* ((end (point))
8736 (template (buffer-substring beg end))
8737 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8738 (shift-what (pcase (and doshift (match-string 2 shift))
8739 (`nil nil)
8740 ("d" 'day)
8741 ("w" (setq shift-n (* 7 shift-n)) 'day)
8742 ("m" 'month)
8743 ("y" 'year)
8744 (_ (error "Unsupported time unit"))))
8745 (nmin 1)
8746 (nmax n)
8747 (n-no-remove -1)
8748 (idprop (org-entry-get nil "ID")))
8749 (when (and doshift
8750 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8751 template))
8752 (delete-region beg end)
8753 (setq end beg)
8754 (setq nmin 0)
8755 (setq nmax (1+ nmax))
8756 (setq n-no-remove nmax))
8757 (goto-char end)
8758 (cl-loop for n from nmin to nmax do
8759 (insert
8760 ;; Prepare clone.
8761 (with-temp-buffer
8762 (insert template)
8763 (org-mode)
8764 (goto-char (point-min))
8765 (org-show-subtree)
8766 (and idprop (if org-clone-delete-id
8767 (org-entry-delete nil "ID")
8768 (org-id-get-create t)))
8769 (unless (= n 0)
8770 (while (re-search-forward org-clock-line-re nil t)
8771 (delete-region (line-beginning-position)
8772 (line-beginning-position 2)))
8773 (goto-char (point-min))
8774 (while (re-search-forward org-drawer-regexp nil t)
8775 (org-remove-empty-drawer-at (point))))
8776 (goto-char (point-min))
8777 (when doshift
8778 (while (re-search-forward org-ts-regexp-both nil t)
8779 (org-timestamp-change (* n shift-n) shift-what))
8780 (unless (= n n-no-remove)
8781 (goto-char (point-min))
8782 (while (re-search-forward org-ts-regexp nil t)
8783 (save-excursion
8784 (goto-char (match-beginning 0))
8785 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8786 (delete-region (match-beginning 1) (match-end 1)))))))
8787 (buffer-string)))))
8788 (goto-char beg)))
8790 ;;; Outline Sorting
8792 (defun org-sort (&optional with-case)
8793 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8794 Optional argument WITH-CASE means sort case-sensitively."
8795 (interactive "P")
8796 (org-call-with-arg
8797 (cond ((org-at-table-p) #'org-table-sort-lines)
8798 ((org-at-item-p) #'org-sort-list)
8799 (t #'org-sort-entries))
8800 with-case))
8802 (defun org-sort-remove-invisible (s)
8803 "Remove invisible part of links and emphasis markers from string S."
8804 (remove-text-properties 0 (length s) org-rm-props s)
8805 (replace-regexp-in-string
8806 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8807 (replace-regexp-in-string
8808 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8809 (org-link-display-format s)
8810 t t) t t))
8812 (defvar org-priority-regexp) ; defined later in the file
8814 (defvar org-after-sorting-entries-or-items-hook nil
8815 "Hook that is run after a bunch of entries or items have been sorted.
8816 When children are sorted, the cursor is in the parent line when this
8817 hook gets called. When a region or a plain list is sorted, the cursor
8818 will be in the first entry of the sorted region/list.")
8820 (defun org-sort-entries
8821 (&optional with-case sorting-type getkey-func compare-func property
8822 interactive?)
8823 "Sort entries on a certain level of an outline tree.
8824 If there is an active region, the entries in the region are sorted.
8825 Else, if the cursor is before the first entry, sort the top-level items.
8826 Else, the children of the entry at point are sorted.
8828 Sorting can be alphabetically, numerically, by date/time as given by
8829 a time stamp, by a property, by priority order, or by a custom function.
8831 The command prompts for the sorting type unless it has been given to the
8832 function through the SORTING-TYPE argument, which needs to be a character,
8833 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8834 the precise meaning of each character:
8836 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8837 c By creation time, which is assumed to be the first inactive time stamp
8838 at the beginning of a line.
8839 d By deadline date/time.
8840 k By clocking time.
8841 n Numerically, by converting the beginning of the entry/item to a number.
8842 o By order of TODO keywords.
8843 p By priority according to the cookie.
8844 r By the value of a property.
8845 s By scheduled date/time.
8846 t By date/time, either the first active time stamp in the entry, or, if
8847 none exist, by the first inactive one.
8849 Capital letters will reverse the sort order.
8851 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8852 called with point at the beginning of the record. It must return a
8853 value that is compatible with COMPARE-FUNC, the function used to
8854 compare entries.
8856 Comparing entries ignores case by default. However, with an optional argument
8857 WITH-CASE, the sorting considers case as well.
8859 Sorting is done against the visible part of the headlines, it ignores hidden
8860 links.
8862 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8864 A non-nil value for INTERACTIVE? is used to signal that this
8865 function is being called interactively."
8866 (interactive (list current-prefix-arg nil nil nil nil t))
8867 (let ((case-func (if with-case 'identity 'downcase))
8868 start beg end stars re re2
8869 txt what tmp)
8870 ;; Find beginning and end of region to sort
8871 (cond
8872 ((org-region-active-p)
8873 ;; we will sort the region
8874 (setq end (region-end)
8875 what "region")
8876 (goto-char (region-beginning))
8877 (unless (org-at-heading-p) (outline-next-heading))
8878 (setq start (point)))
8879 ((or (org-at-heading-p)
8880 (ignore-errors (progn (org-back-to-heading) t)))
8881 ;; we will sort the children of the current headline
8882 (org-back-to-heading)
8883 (setq start (point)
8884 end (progn (org-end-of-subtree t t)
8885 (or (bolp) (insert "\n"))
8886 (when (>= (org-back-over-empty-lines) 1)
8887 (forward-line 1))
8888 (point))
8889 what "children")
8890 (goto-char start)
8891 (outline-show-subtree)
8892 (outline-next-heading))
8894 ;; we will sort the top-level entries in this file
8895 (goto-char (point-min))
8896 (or (org-at-heading-p) (outline-next-heading))
8897 (setq start (point))
8898 (goto-char (point-max))
8899 (beginning-of-line 1)
8900 (when (looking-at ".*?\\S-")
8901 ;; File ends in a non-white line
8902 (end-of-line 1)
8903 (insert "\n"))
8904 (setq end (point-max))
8905 (setq what "top-level")
8906 (goto-char start)
8907 (outline-show-all)))
8909 (setq beg (point))
8910 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8912 (looking-at "\\(\\*+\\)")
8913 (setq stars (match-string 1)
8914 re (concat "^" (regexp-quote stars) " +")
8915 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8916 txt (buffer-substring beg end))
8917 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8918 (when (and (not (equal stars "*")) (string-match re2 txt))
8919 (user-error "Region to sort contains a level above the first entry"))
8921 (unless sorting-type
8922 (message
8923 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8924 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8925 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8926 what)
8927 (setq sorting-type (read-char-exclusive)))
8929 (unless getkey-func
8930 (and (= (downcase sorting-type) ?f)
8931 (setq getkey-func
8932 (or (and interactive?
8933 (org-read-function
8934 "Function for extracting keys: "))
8935 (error "Missing key extractor")))))
8937 (and (= (downcase sorting-type) ?r)
8938 (not property)
8939 (setq property
8940 (completing-read "Property: "
8941 (mapcar #'list (org-buffer-property-keys t))
8942 nil t)))
8944 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8945 (message "Sorting entries...")
8947 (save-restriction
8948 (narrow-to-region start end)
8949 (let ((restore-clock?
8950 ;; The clock marker is lost when using `sort-subr'; mark
8951 ;; the clock with temporary `:org-clock-marker-backup'
8952 ;; text property.
8953 (when (and (eq (org-clock-is-active) (current-buffer))
8954 (<= start (marker-position org-clock-marker))
8955 (>= end (marker-position org-clock-marker)))
8956 (org-with-silent-modifications
8957 (put-text-property (1- org-clock-marker) org-clock-marker
8958 :org-clock-marker-backup t))
8960 (dcst (downcase sorting-type))
8961 (case-fold-search nil)
8962 (now (current-time)))
8963 (sort-subr
8964 (/= dcst sorting-type)
8965 ;; This function moves to the beginning character of the "record" to
8966 ;; be sorted.
8967 (lambda nil
8968 (if (re-search-forward re nil t)
8969 (goto-char (match-beginning 0))
8970 (goto-char (point-max))))
8971 ;; This function moves to the last character of the "record" being
8972 ;; sorted.
8973 (lambda nil
8974 (save-match-data
8975 (condition-case nil
8976 (outline-forward-same-level 1)
8977 (error
8978 (goto-char (point-max))))))
8979 ;; This function returns the value that gets sorted against.
8980 (lambda nil
8981 (cond
8982 ((= dcst ?n)
8983 (if (looking-at org-complex-heading-regexp)
8984 (string-to-number (org-sort-remove-invisible (match-string 4)))
8985 nil))
8986 ((= dcst ?a)
8987 (if (looking-at org-complex-heading-regexp)
8988 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8989 nil))
8990 ((= dcst ?k)
8991 (or (get-text-property (point) :org-clock-minutes) 0))
8992 ((= dcst ?t)
8993 (let ((end (save-excursion (outline-next-heading) (point))))
8994 (if (or (re-search-forward org-ts-regexp end t)
8995 (re-search-forward org-ts-regexp-both end t))
8996 (org-time-string-to-seconds (match-string 0))
8997 (float-time now))))
8998 ((= dcst ?c)
8999 (let ((end (save-excursion (outline-next-heading) (point))))
9000 (if (re-search-forward
9001 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9002 end t)
9003 (org-time-string-to-seconds (match-string 0))
9004 (float-time now))))
9005 ((= dcst ?s)
9006 (let ((end (save-excursion (outline-next-heading) (point))))
9007 (if (re-search-forward org-scheduled-time-regexp end t)
9008 (org-time-string-to-seconds (match-string 1))
9009 (float-time now))))
9010 ((= dcst ?d)
9011 (let ((end (save-excursion (outline-next-heading) (point))))
9012 (if (re-search-forward org-deadline-time-regexp end t)
9013 (org-time-string-to-seconds (match-string 1))
9014 (float-time now))))
9015 ((= dcst ?p)
9016 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9017 (string-to-char (match-string 2))
9018 org-default-priority))
9019 ((= dcst ?r)
9020 (or (org-entry-get nil property) ""))
9021 ((= dcst ?o)
9022 (when (looking-at org-complex-heading-regexp)
9023 (let* ((m (match-string 2))
9024 (s (if (member m org-done-keywords) '- '+)))
9025 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9026 ((= dcst ?f)
9027 (if getkey-func
9028 (progn
9029 (setq tmp (funcall getkey-func))
9030 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9031 tmp)
9032 (error "Invalid key function `%s'" getkey-func)))
9033 (t (error "Invalid sorting type `%c'" sorting-type))))
9035 (cond
9036 ((= dcst ?a) 'string<)
9037 ((= dcst ?f)
9038 (or compare-func
9039 (and interactive?
9040 (org-read-function
9041 (concat "Function for comparing keys "
9042 "(empty for default `sort-subr' predicate): ")
9043 'allow-empty))))
9044 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9045 (when restore-clock?
9046 (move-marker org-clock-marker
9047 (1+ (next-single-property-change
9048 start :org-clock-marker-backup)))
9049 (remove-text-properties (1- org-clock-marker) org-clock-marker
9050 '(:org-clock-marker-backup t)))))
9051 (run-hooks 'org-after-sorting-entries-or-items-hook)
9052 (message "Sorting entries...done")))
9054 ;;; The orgstruct minor mode
9056 ;; Define a minor mode which can be used in other modes in order to
9057 ;; integrate the Org mode structure editing commands.
9059 ;; This is really a hack, because the Org mode structure commands use
9060 ;; keys which normally belong to the major mode. Here is how it
9061 ;; works: The minor mode defines all the keys necessary to operate the
9062 ;; structure commands, but wraps the commands into a function which
9063 ;; tests if the cursor is currently at a headline or a plain list
9064 ;; item. If that is the case, the structure command is used,
9065 ;; temporarily setting many Org mode variables like regular
9066 ;; expressions for filling etc. However, when any of those keys is
9067 ;; used at a different location, function uses `key-binding' to look
9068 ;; up if the key has an associated command in another currently active
9069 ;; keymap (minor modes, major mode, global), and executes that
9070 ;; command. There might be problems if any of the keys is otherwise
9071 ;; used as a prefix key.
9073 (defcustom orgstruct-heading-prefix-regexp ""
9074 "Regexp that matches the custom prefix of Org headlines in
9075 orgstruct(++)-mode."
9076 :group 'org
9077 :version "26.1"
9078 :package-version '(Org . "8.3")
9079 :type 'regexp)
9080 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9082 (defcustom orgstruct-setup-hook nil
9083 "Hook run after orgstruct-mode-map is filled."
9084 :group 'org
9085 :version "24.4"
9086 :package-version '(Org . "8.0")
9087 :type 'hook)
9089 (defvar orgstruct-initialized nil)
9091 (defvar org-local-vars nil
9092 "List of local variables, for use by `orgstruct-mode'.")
9094 ;;;###autoload
9095 (define-minor-mode orgstruct-mode
9096 "Toggle the minor mode `orgstruct-mode'.
9097 This mode is for using Org mode structure commands in other
9098 modes. The following keys behave as if Org mode were active, if
9099 the cursor is on a headline, or on a plain list item (both as
9100 defined by Org mode)."
9101 nil " OrgStruct" (make-sparse-keymap)
9102 (funcall (if orgstruct-mode
9103 'add-to-invisibility-spec
9104 'remove-from-invisibility-spec)
9105 '(outline . t))
9106 (when orgstruct-mode
9107 (org-load-modules-maybe)
9108 (unless orgstruct-initialized
9109 (orgstruct-setup)
9110 (setq orgstruct-initialized t))))
9112 ;;;###autoload
9113 (defun turn-on-orgstruct ()
9114 "Unconditionally turn on `orgstruct-mode'."
9115 (orgstruct-mode 1))
9117 (defvar-local orgstruct-is-++ nil
9118 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9119 (defvar-local org-fb-vars nil)
9120 (defun orgstruct++-mode (&optional arg)
9121 "Toggle `orgstruct-mode', the enhanced version of it.
9122 In addition to setting orgstruct-mode, this also exports all
9123 indentation and autofilling variables from Org mode into the
9124 buffer. It will also recognize item context in multiline items."
9125 (interactive "P")
9126 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9127 (if (< arg 1)
9128 (progn (orgstruct-mode -1)
9129 (dolist (v org-fb-vars)
9130 (set (make-local-variable (car v))
9131 (if (eq (car-safe (cadr v)) 'quote)
9132 (cl-cadadr v)
9133 (nth 1 v)))))
9134 (orgstruct-mode 1)
9135 (setq org-fb-vars nil)
9136 (unless org-local-vars
9137 (setq org-local-vars (org-get-local-variables)))
9138 (let (var val)
9139 (dolist (x org-local-vars)
9140 (when (string-match
9141 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9142 \\|fill-prefix\\|indent-\\)"
9143 (symbol-name (car x)))
9144 (setq var (car x) val (nth 1 x))
9145 (push (list var `(quote ,(eval var))) org-fb-vars)
9146 (set (make-local-variable var)
9147 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9148 (setq-local orgstruct-is-++ t))))
9150 ;;;###autoload
9151 (defun turn-on-orgstruct++ ()
9152 "Unconditionally turn on `orgstruct++-mode'."
9153 (orgstruct++-mode 1))
9155 (defun orgstruct-error ()
9156 "Error when there is no default binding for a structure key."
9157 (interactive)
9158 (funcall (if (fboundp 'user-error)
9159 'user-error
9160 'error)
9161 "This key has no function outside structure elements"))
9163 (defun orgstruct-setup ()
9164 "Setup orgstruct keymap."
9165 (dolist (cell '((org-demote . t)
9166 (org-metaleft . t)
9167 (org-metaright . t)
9168 (org-promote . t)
9169 (org-shiftmetaleft . t)
9170 (org-shiftmetaright . t)
9171 org-backward-element
9172 org-backward-heading-same-level
9173 org-ctrl-c-ret
9174 org-ctrl-c-minus
9175 org-ctrl-c-star
9176 org-cycle
9177 org-force-cycle-archived
9178 org-forward-heading-same-level
9179 org-insert-heading
9180 org-insert-heading-respect-content
9181 org-kill-note-or-show-branches
9182 org-mark-subtree
9183 org-meta-return
9184 org-metadown
9185 org-metaup
9186 org-narrow-to-subtree
9187 org-promote-subtree
9188 org-reveal
9189 org-shiftdown
9190 org-shiftleft
9191 org-shiftmetadown
9192 org-shiftmetaup
9193 org-shiftright
9194 org-shifttab
9195 org-shifttab
9196 org-shiftup
9197 org-show-children
9198 org-show-subtree
9199 org-sort
9200 org-up-element
9201 outline-demote
9202 outline-next-visible-heading
9203 outline-previous-visible-heading
9204 outline-promote
9205 outline-up-heading))
9206 (let ((f (or (car-safe cell) cell))
9207 (disable-when-heading-prefix (cdr-safe cell)))
9208 (when (fboundp f)
9209 (let ((new-bindings))
9210 (dolist (binding (nconc (where-is-internal f org-mode-map)
9211 (where-is-internal f outline-mode-map)))
9212 (push binding new-bindings)
9213 ;; TODO use local-function-key-map
9214 (dolist (rep '(("<tab>" . "TAB")
9215 ("<return>" . "RET")
9216 ("<escape>" . "ESC")
9217 ("<delete>" . "DEL")))
9218 (setq binding (read-kbd-macro
9219 (let ((case-fold-search))
9220 (replace-regexp-in-string
9221 (regexp-quote (cdr rep))
9222 (car rep)
9223 (key-description binding)))))
9224 (cl-pushnew binding new-bindings :test 'equal)))
9225 (dolist (binding new-bindings)
9226 (let ((key (lookup-key orgstruct-mode-map binding)))
9227 (when (or (not key) (numberp key))
9228 (ignore-errors
9229 (org-defkey orgstruct-mode-map
9230 binding
9231 (orgstruct-make-binding
9232 f binding disable-when-heading-prefix))))))))))
9233 (run-hooks 'orgstruct-setup-hook))
9235 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9236 "Create a function for binding in the structure minor mode.
9237 FUN is the command to call inside a table. KEY is the key that
9238 should be checked in for a command to execute outside of tables.
9239 Non-nil `disable-when-heading-prefix' means to disable the command
9240 if `orgstruct-heading-prefix-regexp' is not empty."
9241 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9242 (let ((nname name)
9243 (i 0))
9244 (while (fboundp (intern nname))
9245 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9246 (setq name (intern nname)))
9247 (eval
9248 (let ((bindings '((org-heading-regexp
9249 (concat "^"
9250 orgstruct-heading-prefix-regexp
9251 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9252 (org-outline-regexp
9253 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9254 (org-outline-regexp-bol
9255 (concat "^" org-outline-regexp))
9256 (outline-regexp org-outline-regexp)
9257 (outline-heading-end-regexp "\n")
9258 (outline-level 'org-outline-level)
9259 (outline-heading-alist))))
9260 `(defun ,name (arg)
9261 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9262 "Outside of structure, run the binding of `"
9263 (key-description key) "'."
9264 (when disable-when-heading-prefix
9265 (concat
9266 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9267 "back to the default binding due to limitations of Org's implementation of\n"
9268 "`" (symbol-name fun) "'.")))
9269 (interactive "p")
9270 (let* ((disable
9271 ,(and disable-when-heading-prefix
9272 '(not (string= orgstruct-heading-prefix-regexp ""))))
9273 (fallback
9274 (or disable
9275 (not
9276 (let* ,bindings
9277 (org-context-p 'headline 'item
9278 ,(when (memq fun
9279 '(org-insert-heading
9280 org-insert-heading-respect-content
9281 org-meta-return))
9282 '(when orgstruct-is-++
9283 'item-body))))))))
9284 (if fallback
9285 (let* ((orgstruct-mode)
9286 (binding
9287 (let ((key ,key))
9288 (catch 'exit
9289 (dolist
9290 (rep
9291 '(nil
9292 ("<\\([^>]*\\)tab>" . "\\1TAB")
9293 ("<\\([^>]*\\)return>" . "\\1RET")
9294 ("<\\([^>]*\\)escape>" . "\\1ESC")
9295 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9296 nil)
9297 (when rep
9298 (setq key (read-kbd-macro
9299 (let ((case-fold-search))
9300 (replace-regexp-in-string
9301 (car rep)
9302 (cdr rep)
9303 (key-description key))))))
9304 (when (key-binding key)
9305 (throw 'exit (key-binding key))))))))
9306 (if (keymapp binding)
9307 (org-set-transient-map binding)
9308 (let ((func (or binding
9309 (unless disable
9310 'orgstruct-error))))
9311 (when func
9312 (call-interactively func)))))
9313 (org-run-like-in-org-mode
9314 (lambda ()
9315 (interactive)
9316 (let* ,bindings
9317 (call-interactively ',fun)))))))))
9318 name))
9320 (defun org-contextualize-keys (alist contexts)
9321 "Return valid elements in ALIST depending on CONTEXTS.
9323 `org-agenda-custom-commands' or `org-capture-templates' are the
9324 values used for ALIST, and `org-agenda-custom-commands-contexts'
9325 or `org-capture-templates-contexts' are the associated contexts
9326 definitions."
9327 (let ((contexts
9328 ;; normalize contexts
9329 (mapcar
9330 (lambda(c) (cond ((listp (cadr c))
9331 (list (car c) (car c) (nth 1 c)))
9332 ((string= "" (cadr c))
9333 (list (car c) (car c) (nth 2 c)))
9334 (t c)))
9335 contexts))
9336 (a alist) r s)
9337 ;; loop over all commands or templates
9338 (dolist (c a)
9339 (let (vrules repl)
9340 (cond
9341 ((not (assoc (car c) contexts))
9342 (push c r))
9343 ((and (assoc (car c) contexts)
9344 (setq vrules (org-contextualize-validate-key
9345 (car c) contexts)))
9346 (mapc (lambda (vr)
9347 (unless (equal (car vr) (cadr vr))
9348 (setq repl vr)))
9349 vrules)
9350 (if (not repl) (push c r)
9351 (push (cadr repl) s)
9352 (push
9353 (cons (car c)
9354 (cdr (or (assoc (cadr repl) alist)
9355 (error "Undefined key `%s' as contextual replacement for `%s'"
9356 (cadr repl) (car c)))))
9357 r))))))
9358 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9359 (delq
9361 (delete-dups
9362 (mapcar (lambda (x)
9363 (let ((tpl (car x)))
9364 (unless (delq
9366 (mapcar (lambda (y)
9367 (equal y tpl))
9369 x)))
9370 (reverse r))))))
9372 (defun org-contextualize-validate-key (key contexts)
9373 "Check CONTEXTS for agenda or capture KEY."
9374 (let (res)
9375 (dolist (r contexts)
9376 (dolist (rr (car (last r)))
9377 (when
9378 (and (equal key (car r))
9379 (if (functionp rr) (funcall rr)
9380 (or (and (eq (car rr) 'in-file)
9381 (buffer-file-name)
9382 (string-match (cdr rr) (buffer-file-name)))
9383 (and (eq (car rr) 'in-mode)
9384 (string-match (cdr rr) (symbol-name major-mode)))
9385 (and (eq (car rr) 'in-buffer)
9386 (string-match (cdr rr) (buffer-name)))
9387 (when (and (eq (car rr) 'not-in-file)
9388 (buffer-file-name))
9389 (not (string-match (cdr rr) (buffer-file-name))))
9390 (when (eq (car rr) 'not-in-mode)
9391 (not (string-match (cdr rr) (symbol-name major-mode))))
9392 (when (eq (car rr) 'not-in-buffer)
9393 (not (string-match (cdr rr) (buffer-name)))))))
9394 (push r res))))
9395 (delete-dups (delq nil res))))
9397 (defun org-context-p (&rest contexts)
9398 "Check if local context is any of CONTEXTS.
9399 Possible values in the list of contexts are `table', `headline', and `item'."
9400 (let ((pos (point)))
9401 (goto-char (point-at-bol))
9402 (prog1 (or (and (memq 'table contexts)
9403 (looking-at "[ \t]*|"))
9404 (and (memq 'headline contexts)
9405 (looking-at org-outline-regexp))
9406 (and (memq 'item contexts)
9407 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9408 (and (memq 'item-body contexts)
9409 (org-in-item-p)))
9410 (goto-char pos))))
9412 ;;;###autoload
9413 (defun org-run-like-in-org-mode (cmd)
9414 "Run a command, pretending that the current buffer is in Org mode.
9415 This will temporarily bind local variables that are typically bound in
9416 Org mode to the values they have in Org mode, and then interactively
9417 call CMD."
9418 (org-load-modules-maybe)
9419 (unless org-local-vars
9420 (setq org-local-vars (org-get-local-variables)))
9421 (let (binds)
9422 (dolist (var org-local-vars)
9423 (when (or (not (boundp (car var)))
9424 (eq (symbol-value (car var))
9425 (default-value (car var))))
9426 (push (list (car var) `(quote ,(cadr var))) binds)))
9427 (eval `(let ,binds
9428 (call-interactively (quote ,cmd))))))
9430 (defun org-get-category (&optional pos force-refresh)
9431 "Get the category applying to position POS."
9432 (save-match-data
9433 (when force-refresh (org-refresh-category-properties))
9434 (let ((pos (or pos (point))))
9435 (or (get-text-property pos 'org-category)
9436 (progn (org-refresh-category-properties)
9437 (get-text-property pos 'org-category))))))
9439 ;;; Refresh properties
9441 (defun org-refresh-properties (dprop tprop)
9442 "Refresh buffer text properties.
9443 DPROP is the drawer property and TPROP is either the
9444 corresponding text property to set, or an alist with each element
9445 being a text property (as a symbol) and a function to apply to
9446 the value of the drawer property."
9447 (let* ((case-fold-search t)
9448 (inhibit-read-only t)
9449 (inherit? (org-property-inherit-p dprop))
9450 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9451 (global (and inherit? (org--property-global-value dprop nil))))
9452 (org-with-silent-modifications
9453 (org-with-point-at 1
9454 ;; Set global values (e.g., values defined through
9455 ;; "#+PROPERTY:" keywords) to the whole buffer.
9456 (when global (put-text-property (point-min) (point-max) tprop global))
9457 ;; Set local values.
9458 (while (re-search-forward property-re nil t)
9459 (when (org-at-property-p)
9460 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9461 (outline-next-heading))))))
9463 (defun org-refresh-property (tprop p &optional inherit)
9464 "Refresh the buffer text property TPROP from the drawer property P.
9465 The refresh happens only for the current headline, or the whole
9466 sub-tree if optional argument INHERIT is non-nil."
9467 (unless (org-before-first-heading-p)
9468 (save-excursion
9469 (org-back-to-heading t)
9470 (let ((start (point))
9471 (end (save-excursion
9472 (if inherit (org-end-of-subtree t t)
9473 (or (outline-next-heading) (point-max))))))
9474 (if (symbolp tprop)
9475 ;; TPROP is a text property symbol.
9476 (put-text-property start end tprop p)
9477 ;; TPROP is an alist with (property . function) elements.
9478 (pcase-dolist (`(,prop . ,f) tprop)
9479 (put-text-property start end prop (funcall f p))))))))
9481 (defun org-refresh-category-properties ()
9482 "Refresh category text properties in the buffer."
9483 (let ((case-fold-search t)
9484 (inhibit-read-only t)
9485 (default-category
9486 (cond ((null org-category)
9487 (if buffer-file-name
9488 (file-name-sans-extension
9489 (file-name-nondirectory buffer-file-name))
9490 "???"))
9491 ((symbolp org-category) (symbol-name org-category))
9492 (t org-category))))
9493 (org-with-silent-modifications
9494 (org-with-wide-buffer
9495 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9496 ;; This is the default category for the buffer. If none is
9497 ;; found, fall-back to `org-category' or buffer file name.
9498 (put-text-property
9499 (point-min) (point-max)
9500 'org-category
9501 (catch 'buffer-category
9502 (goto-char (point-max))
9503 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9504 (let ((element (org-element-at-point)))
9505 (when (eq (org-element-type element) 'keyword)
9506 (throw 'buffer-category
9507 (org-element-property :value element)))))
9508 default-category))
9509 ;; Set sub-tree specific categories.
9510 (goto-char (point-min))
9511 (let ((regexp (org-re-property "CATEGORY")))
9512 (while (re-search-forward regexp nil t)
9513 (let ((value (match-string-no-properties 3)))
9514 (when (org-at-property-p)
9515 (put-text-property
9516 (save-excursion (org-back-to-heading t) (point))
9517 (save-excursion (org-end-of-subtree t t) (point))
9518 'org-category
9519 value)))))))))
9521 (defun org-refresh-stats-properties ()
9522 "Refresh stats text properties in the buffer."
9523 (org-with-silent-modifications
9524 (org-with-point-at 1
9525 (let ((regexp (concat org-outline-regexp-bol
9526 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9527 (while (re-search-forward regexp nil t)
9528 (let* ((numerator (string-to-number (match-string 1)))
9529 (denominator (and (match-end 2)
9530 (string-to-number (match-string 2))))
9531 (stats (cond ((not denominator) numerator) ;percent
9532 ((= denominator 0) 0)
9533 (t (/ (* numerator 100) denominator)))))
9534 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9535 'org-stats stats)))))))
9537 (defun org-refresh-effort-properties ()
9538 "Refresh effort properties"
9539 (org-refresh-properties
9540 org-effort-property
9541 '((effort . identity)
9542 (effort-minutes . org-duration-to-minutes))))
9544 ;;;; Link Stuff
9546 ;;; Link abbreviations
9548 (defun org-link-expand-abbrev (link)
9549 "Apply replacements as defined in `org-link-abbrev-alist'."
9550 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9551 (let* ((key (match-string 1 link))
9552 (as (or (assoc key org-link-abbrev-alist-local)
9553 (assoc key org-link-abbrev-alist)))
9554 (tag (and (match-end 2) (match-string 3 link)))
9555 rpl)
9556 (if (not as)
9557 link
9558 (setq rpl (cdr as))
9559 (cond
9560 ((symbolp rpl) (funcall rpl tag))
9561 ((string-match "%(\\([^)]+\\))" rpl)
9562 (replace-match
9563 (save-match-data
9564 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9565 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9566 ((string-match "%h" rpl)
9567 (replace-match (url-hexify-string (or tag "")) t t rpl))
9568 (t (concat rpl tag)))))
9569 link))
9571 ;;; Storing and inserting links
9573 (defvar org-insert-link-history nil
9574 "Minibuffer history for links inserted with `org-insert-link'.")
9576 (defvar org-stored-links nil
9577 "Contains the links stored with `org-store-link'.")
9579 (defvar org-store-link-plist nil
9580 "Plist with info about the most recently link created with `org-store-link'.")
9582 (defun org-store-link-functions ()
9583 "Return a list of functions that are called to create and store a link.
9584 The functions defined in the :store property of
9585 `org-link-parameters'.
9587 Each function will be called in turn until one returns a non-nil
9588 value. Each function should check if it is responsible for
9589 creating this link (for example by looking at the major mode).
9590 If not, it must exit and return nil. If yes, it should return
9591 a non-nil value after calling `org-store-link-props' with a list
9592 of properties and values. Special properties are:
9594 :type The link prefix, like \"http\". This must be given.
9595 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9596 This is obligatory as well.
9597 :description Optional default description for the second pair
9598 of brackets in an Org mode link. The user can still change
9599 this when inserting this link into an Org mode buffer.
9601 In addition to these, any additional properties can be specified
9602 and then used in capture templates."
9603 (cl-loop for link in org-link-parameters
9604 with store-func
9605 do (setq store-func (org-link-get-parameter (car link) :store))
9606 if store-func
9607 collect store-func))
9609 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9610 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9612 ;;;###autoload
9613 (defun org-store-link (arg)
9614 "Store an org-link to the current location.
9615 \\<org-mode-map>
9616 This link is added to `org-stored-links' and can later be inserted
9617 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9619 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9620 A single
9621 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9622 `org-gnus-prefer-web-links' for links to Usenet articles.
9624 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9625 skipping storing functions that are not
9626 part of Org core.
9628 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9629 prefix ARG forces storing a link for each line in the
9630 active region."
9631 (interactive "P")
9632 (org-load-modules-maybe)
9633 (if (and (equal arg '(64)) (org-region-active-p))
9634 (save-excursion
9635 (let ((end (region-end)))
9636 (goto-char (region-beginning))
9637 (set-mark (point))
9638 (while (< (point-at-eol) end)
9639 (move-end-of-line 1) (activate-mark)
9640 (let (current-prefix-arg)
9641 (call-interactively 'org-store-link))
9642 (move-beginning-of-line 2)
9643 (set-mark (point)))))
9644 (setq org-store-link-plist nil)
9645 (let (link cpltxt desc description search
9646 txt custom-id agenda-link sfuns sfunsn)
9647 (cond
9649 ;; Store a link using an external link type
9650 ((and (not (equal arg '(16)))
9651 (setq sfuns
9652 (delq
9653 nil (mapcar (lambda (f)
9654 (let (fs) (if (funcall f) (push f fs))))
9655 (org-store-link-functions)))
9656 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9657 (or (and (cdr sfuns)
9658 (funcall (intern
9659 (completing-read
9660 "Which function for creating the link? "
9661 sfunsn nil t (car sfunsn)))))
9662 (funcall (caar sfuns)))
9663 (setq link (plist-get org-store-link-plist :link)
9664 desc (or (plist-get org-store-link-plist
9665 :description)
9666 link))))
9668 ;; Store a link from a source code buffer.
9669 ((org-src-edit-buffer-p)
9670 (let ((coderef-format (org-src-coderef-format)))
9671 (cond ((save-excursion
9672 (beginning-of-line)
9673 (looking-at (org-src-coderef-regexp coderef-format)))
9674 (setq link (format "(%s)" (match-string-no-properties 3))))
9675 ((called-interactively-p 'any)
9676 (let ((label (read-string "Code line label: ")))
9677 (end-of-line)
9678 (setq link (format coderef-format label))
9679 (let ((gc (- 79 (length link))))
9680 (if (< (current-column) gc)
9681 (org-move-to-column gc t)
9682 (insert " ")))
9683 (insert link)
9684 (setq link (concat "(" label ")"))
9685 (setq desc nil)))
9686 (t (setq link nil)))))
9688 ;; We are in the agenda, link to referenced location
9689 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9690 (let ((m (or (get-text-property (point) 'org-hd-marker)
9691 (get-text-property (point) 'org-marker))))
9692 (when m
9693 (org-with-point-at m
9694 (setq agenda-link
9695 (if (called-interactively-p 'any)
9696 (call-interactively 'org-store-link)
9697 (org-store-link nil)))))))
9699 ((eq major-mode 'calendar-mode)
9700 (let ((cd (calendar-cursor-to-date)))
9701 (setq link
9702 (format-time-string
9703 (car org-time-stamp-formats)
9704 (apply 'encode-time
9705 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9706 nil nil nil))))
9707 (org-store-link-props :type "calendar" :date cd)))
9709 ((eq major-mode 'help-mode)
9710 (setq link (concat "help:" (save-excursion
9711 (goto-char (point-min))
9712 (looking-at "^[^ ]+")
9713 (match-string 0))))
9714 (org-store-link-props :type "help"))
9716 ((eq major-mode 'w3-mode)
9717 (setq cpltxt (if (and (buffer-name)
9718 (not (string-match "Untitled" (buffer-name))))
9719 (buffer-name)
9720 (url-view-url t))
9721 link (url-view-url t))
9722 (org-store-link-props :type "w3" :url (url-view-url t)))
9724 ((eq major-mode 'image-mode)
9725 (setq cpltxt (concat "file:"
9726 (abbreviate-file-name buffer-file-name))
9727 link cpltxt)
9728 (org-store-link-props :type "image" :file buffer-file-name))
9730 ;; In dired, store a link to the file of the current line
9731 ((derived-mode-p 'dired-mode)
9732 (let ((file (dired-get-filename nil t)))
9733 (setq file (if file
9734 (abbreviate-file-name
9735 (expand-file-name (dired-get-filename nil t)))
9736 ;; otherwise, no file so use current directory.
9737 default-directory))
9738 (setq cpltxt (concat "file:" file)
9739 link cpltxt)))
9741 ((setq search (run-hook-with-args-until-success
9742 'org-create-file-search-functions))
9743 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9744 "::" search))
9745 (setq cpltxt (or description link)))
9747 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9748 (org-with-limited-levels
9749 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9750 (cond
9751 ;; Store a link using the target at point
9752 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9753 (setq cpltxt
9754 (concat "file:"
9755 (abbreviate-file-name
9756 (buffer-file-name (buffer-base-buffer)))
9757 "::" (match-string 1))
9758 link cpltxt))
9759 ((and (featurep 'org-id)
9760 (or (eq org-id-link-to-org-use-id t)
9761 (and (called-interactively-p 'any)
9762 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9763 (and (eq org-id-link-to-org-use-id
9764 'create-if-interactive-and-no-custom-id)
9765 (not custom-id))))
9766 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9767 ;; Store a link using the ID at point
9768 (setq link (condition-case nil
9769 (prog1 (org-id-store-link)
9770 (setq desc (or (plist-get org-store-link-plist
9771 :description)
9772 "")))
9773 (error
9774 ;; Probably before first headline, link only to file
9775 (concat "file:"
9776 (abbreviate-file-name
9777 (buffer-file-name (buffer-base-buffer))))))))
9779 ;; Just link to current headline
9780 (setq cpltxt (concat "file:"
9781 (abbreviate-file-name
9782 (buffer-file-name (buffer-base-buffer)))))
9783 ;; Add a context search string
9784 (when (org-xor org-context-in-file-links
9785 (equal arg '(4)))
9786 (let* ((element (org-element-at-point))
9787 (name (org-element-property :name element)))
9788 (setq txt (cond
9789 ((org-at-heading-p) nil)
9790 (name)
9791 ((org-region-active-p)
9792 (buffer-substring (region-beginning) (region-end)))))
9793 (when (or (null txt) (string-match "\\S-" txt))
9794 (setq cpltxt
9795 (concat cpltxt "::"
9796 (condition-case nil
9797 (org-make-org-heading-search-string txt)
9798 (error "")))
9799 desc (or name
9800 (nth 4 (ignore-errors (org-heading-components)))
9801 "NONE")))))
9802 (when (string-match "::\\'" cpltxt)
9803 (setq cpltxt (substring cpltxt 0 -2)))
9804 (setq link cpltxt)))))
9806 ((buffer-file-name (buffer-base-buffer))
9807 ;; Just link to this file here.
9808 (setq cpltxt (concat "file:"
9809 (abbreviate-file-name
9810 (buffer-file-name (buffer-base-buffer)))))
9811 ;; Add a context string.
9812 (when (org-xor org-context-in-file-links
9813 (equal arg '(4)))
9814 (setq txt (if (org-region-active-p)
9815 (buffer-substring (region-beginning) (region-end))
9816 (buffer-substring (point-at-bol) (point-at-eol))))
9817 ;; Only use search option if there is some text.
9818 (when (string-match "\\S-" txt)
9819 (setq cpltxt
9820 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9821 desc "NONE")))
9822 (setq link cpltxt))
9824 ((called-interactively-p 'interactive)
9825 (user-error "No method for storing a link from this buffer"))
9827 (t (setq link nil)))
9829 ;; We're done setting link and desc, clean up
9830 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9831 (setq link (or link cpltxt)
9832 desc (or desc cpltxt))
9833 (cond ((not desc))
9834 ((equal desc "NONE") (setq desc nil))
9835 (t (setq desc
9836 (replace-regexp-in-string
9837 org-bracket-link-analytic-regexp
9838 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9839 desc))))
9840 ;; Return the link
9841 (if (not (and (or (called-interactively-p 'any)
9842 executing-kbd-macro)
9843 link))
9844 (or agenda-link (and link (org-make-link-string link desc)))
9845 (push (list link desc) org-stored-links)
9846 (message "Stored: %s" (or desc link))
9847 (when custom-id
9848 (setq link (concat "file:" (abbreviate-file-name
9849 (buffer-file-name)) "::#" custom-id))
9850 (push (list link desc) org-stored-links))
9851 (car org-stored-links)))))
9853 (defun org-store-link-props (&rest plist)
9854 "Store link properties, extract names, addresses and dates."
9855 (let ((x (plist-get plist :from)))
9856 (when x
9857 (let ((adr (mail-extract-address-components x)))
9858 (setq plist (plist-put plist :fromname (car adr)))
9859 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9860 (let ((x (plist-get plist :to)))
9861 (when x
9862 (let ((adr (mail-extract-address-components x)))
9863 (setq plist (plist-put plist :toname (car adr)))
9864 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9865 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9866 (when x
9867 (setq plist (plist-put plist :date-timestamp
9868 (format-time-string
9869 (org-time-stamp-format t) x)))
9870 (setq plist (plist-put plist :date-timestamp-inactive
9871 (format-time-string
9872 (org-time-stamp-format t t) x)))))
9873 (let ((from (plist-get plist :from))
9874 (to (plist-get plist :to)))
9875 (when (and from to org-from-is-user-regexp)
9876 (setq plist
9877 (plist-put plist :fromto
9878 (if (string-match org-from-is-user-regexp from)
9879 (concat "to %t")
9880 (concat "from %f"))))))
9881 (setq org-store-link-plist plist))
9883 (defun org-add-link-props (&rest plist)
9884 "Add these properties to the link property list."
9885 (let (key value)
9886 (while plist
9887 (setq key (pop plist) value (pop plist))
9888 (setq org-store-link-plist
9889 (plist-put org-store-link-plist key value)))))
9891 (defun org-email-link-description (&optional fmt)
9892 "Return the description part of an email link.
9893 This takes information from `org-store-link-plist' and formats it
9894 according to FMT (default from `org-email-link-description-format')."
9895 (setq fmt (or fmt org-email-link-description-format))
9896 (let* ((p org-store-link-plist)
9897 (to (plist-get p :toaddress))
9898 (from (plist-get p :fromaddress))
9899 (table
9900 (list
9901 (cons "%c" (plist-get p :fromto))
9902 (cons "%F" (plist-get p :from))
9903 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9904 (cons "%T" (plist-get p :to))
9905 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9906 (cons "%s" (plist-get p :subject))
9907 (cons "%d" (plist-get p :date))
9908 (cons "%m" (plist-get p :message-id)))))
9909 (when (string-match "%c" fmt)
9910 ;; Check if the user wrote this message
9911 (if (and org-from-is-user-regexp from to
9912 (save-match-data (string-match org-from-is-user-regexp from)))
9913 (setq fmt (replace-match "to %t" t t fmt))
9914 (setq fmt (replace-match "from %f" t t fmt))))
9915 (org-replace-escapes fmt table)))
9917 (defun org-make-org-heading-search-string (&optional string)
9918 "Make search string for the current headline or STRING."
9919 (let ((s (or string
9920 (and (derived-mode-p 'org-mode)
9921 (save-excursion
9922 (org-back-to-heading t)
9923 (org-element-property :raw-value (org-element-at-point))))))
9924 (lines org-context-in-file-links))
9925 (unless string (setq s (concat "*" s))) ;Add * for headlines
9926 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9927 (when (and string (integerp lines) (> lines 0))
9928 (let ((slines (org-split-string s "\n")))
9929 (when (< lines (length slines))
9930 (setq s (mapconcat
9931 'identity
9932 (reverse (nthcdr (- (length slines) lines)
9933 (reverse slines))) "\n")))))
9934 (mapconcat #'identity (split-string s) " ")))
9936 (defun org-make-link-string (link &optional description)
9937 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9938 (unless (org-string-nw-p link) (error "Empty link"))
9939 (let ((uri (cond ((string-match org-link-types-re link)
9940 (concat (match-string 1 link)
9941 (org-link-escape (substring link (match-end 1)))))
9942 ;; For readability, url-encode internal links only
9943 ;; when absolutely needed (i.e, when they contain
9944 ;; square brackets). File links however, are
9945 ;; encoded since, e.g., spaces are significant.
9946 ((or (file-name-absolute-p link)
9947 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9948 (org-link-escape link))
9949 (t link)))
9950 (description
9951 (and (org-string-nw-p description)
9952 ;; Remove brackets from description, as they are fatal.
9953 (replace-regexp-in-string
9954 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9955 (org-trim description)))))
9956 (format "[[%s]%s]"
9958 (if description (format "[%s]" description) ""))))
9960 (defconst org-link-escape-chars
9961 ;;%20 %5B %5D %25
9962 '(?\s ?\[ ?\] ?%)
9963 "List of characters that should be escaped in a link when stored to Org.
9964 This is the list that is used for internal purposes.")
9966 (defun org-link-escape (text &optional table merge)
9967 "Return percent escaped representation of TEXT.
9968 TEXT is a string with the text to escape.
9969 Optional argument TABLE is a list with characters that should be
9970 escaped. When nil, `org-link-escape-chars' is used.
9971 If optional argument MERGE is set, merge TABLE into
9972 `org-link-escape-chars'."
9973 (let ((characters-to-encode
9974 (cond ((null table) org-link-escape-chars)
9975 (merge (append org-link-escape-chars table))
9976 (t table))))
9977 (mapconcat
9978 (lambda (c)
9979 (if (or (memq c characters-to-encode)
9980 (and org-url-hexify-p (or (< c 32) (> c 126))))
9981 (mapconcat (lambda (e) (format "%%%.2X" e))
9982 (or (encode-coding-char c 'utf-8)
9983 (error "Unable to percent escape character: %c" c))
9985 (char-to-string c)))
9986 text "")))
9988 (defun org-link-unescape (str)
9989 "Unhex hexified Unicode parts in string STR.
9990 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9991 reciprocal of `org-link-escape', which see."
9992 (if (org-string-nw-p str)
9993 (replace-regexp-in-string
9994 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9995 str))
9997 (defun org-link-unescape-compound (hex)
9998 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9999 Note: this function also decodes single byte encodings like
10000 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10001 (save-match-data
10002 (let* ((bytes (cdr (split-string hex "%")))
10003 (ret "")
10004 (eat 0)
10005 (sum 0))
10006 (while bytes
10007 (let* ((val (string-to-number (pop bytes) 16))
10008 (shift-xor
10009 (if (= 0 eat)
10010 (cond
10011 ((>= val 252) (cons 6 252))
10012 ((>= val 248) (cons 5 248))
10013 ((>= val 240) (cons 4 240))
10014 ((>= val 224) (cons 3 224))
10015 ((>= val 192) (cons 2 192))
10016 (t (cons 0 0)))
10017 (cons 6 128))))
10018 (when (>= val 192) (setq eat (car shift-xor)))
10019 (setq val (logxor val (cdr shift-xor)))
10020 (setq sum (+ (lsh sum (car shift-xor)) val))
10021 (when (> eat 0) (setq eat (- eat 1)))
10022 (cond
10023 ((= 0 eat) ;multi byte
10024 (setq ret (concat ret (char-to-string sum)))
10025 (setq sum 0))
10026 ((not bytes) ; single byte(s)
10027 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10028 ret)))
10030 (defun org-link-unescape-single-byte-sequence (hex)
10031 "Unhexify hex-encoded single byte character sequences."
10032 (mapconcat (lambda (byte)
10033 (char-to-string (string-to-number byte 16)))
10034 (cdr (split-string hex "%")) ""))
10036 (defun org-xor (a b)
10037 "Exclusive or."
10038 (if a (not b) b))
10040 (defun org-fixup-message-id-for-http (s)
10041 "Replace special characters in a message id, so it can be used in an http query."
10042 (when (string-match "%" s)
10043 (setq s (mapconcat (lambda (c)
10044 (if (eq c ?%)
10045 "%25"
10046 (char-to-string c)))
10047 s "")))
10048 (while (string-match "<" s)
10049 (setq s (replace-match "%3C" t t s)))
10050 (while (string-match ">" s)
10051 (setq s (replace-match "%3E" t t s)))
10052 (while (string-match "@" s)
10053 (setq s (replace-match "%40" t t s)))
10056 (defun org-link-prettify (link)
10057 "Return a human-readable representation of LINK.
10058 The car of LINK must be a raw link.
10059 The cdr of LINK must be either a link description or nil."
10060 (let ((desc (or (cadr link) "<no description>")))
10061 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10062 "<" (car link) ">")))
10064 ;;;###autoload
10065 (defun org-insert-link-global ()
10066 "Insert a link like Org mode does.
10067 This command can be called in any mode to insert a link in Org syntax."
10068 (interactive)
10069 (org-load-modules-maybe)
10070 (org-run-like-in-org-mode 'org-insert-link))
10072 (defun org-insert-all-links (arg &optional pre post)
10073 "Insert all links in `org-stored-links'.
10074 When a universal prefix, do not delete the links from `org-stored-links'.
10075 When `ARG' is a number, insert the last N link(s).
10076 `PRE' and `POST' are optional arguments to define a string to
10077 prepend or to append."
10078 (interactive "P")
10079 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10080 (links (copy-sequence org-stored-links))
10081 (pr (or pre "- "))
10082 (po (or post "\n"))
10083 (cnt 1) l)
10084 (if (null org-stored-links)
10085 (message "No link to insert")
10086 (while (and (or (listp arg) (>= arg cnt))
10087 (setq l (if (listp arg)
10088 (pop links)
10089 (pop org-stored-links))))
10090 (setq cnt (1+ cnt))
10091 (insert pr)
10092 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10093 (insert po)))))
10095 (defun org-insert-last-stored-link (arg)
10096 "Insert the last link stored in `org-stored-links'."
10097 (interactive "p")
10098 (org-insert-all-links arg "" "\n"))
10100 (defun org-link-fontify-links-to-this-file ()
10101 "Fontify links to the current file in `org-stored-links'."
10102 (let ((f (buffer-file-name)) a b)
10103 (setq a (mapcar (lambda(l)
10104 (let ((ll (car l)))
10105 (when (and (string-match "^file:\\(.+\\)::" ll)
10106 (equal f (expand-file-name (match-string 1 ll))))
10107 ll)))
10108 org-stored-links))
10109 (when (featurep 'org-id)
10110 (setq b (mapcar (lambda(l)
10111 (let ((ll (car l)))
10112 (when (and (string-match "^id:\\(.+\\)$" ll)
10113 (equal f (expand-file-name
10114 (or (org-id-find-id-file
10115 (match-string 1 ll)) ""))))
10116 ll)))
10117 org-stored-links)))
10118 (mapcar (lambda(l)
10119 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10120 (delq nil (append a b)))))
10122 (defvar org--links-history nil)
10123 (defun org-insert-link (&optional complete-file link-location default-description)
10124 "Insert a link. At the prompt, enter the link.
10126 Completion can be used to insert any of the link protocol prefixes in use.
10128 The history can be used to select a link previously stored with
10129 `org-store-link'. When the empty string is entered (i.e. if you just
10130 press `RET' at the prompt), the link defaults to the most recently
10131 stored link. As `SPC' triggers completion in the minibuffer, you need to
10132 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10134 You will also be prompted for a description, and if one is given, it will
10135 be displayed in the buffer instead of the link.
10137 If there is already a link at point, this command will allow you to edit
10138 link and description parts.
10140 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10141 file name can be
10142 selected using completion. The path to the file will be relative to the
10143 current directory if the file is in the current directory or a subdirectory.
10144 Otherwise, the link will be the absolute path as completed in the minibuffer
10145 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10146 option `org-link-file-path-type'.
10148 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10149 absolute path even if the file is in
10150 the current directory or below.
10152 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10153 prefix negates `org-keep-stored-link-after-insertion'.
10155 If `org-make-link-description-function' is non-nil, this function will be
10156 called with the link target, and the result will be the default
10157 link description.
10159 If the LINK-LOCATION parameter is non-nil, this value will be used as
10160 the link location instead of reading one interactively.
10162 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10163 as the default description."
10164 (interactive "P")
10165 (let* ((wcf (current-window-configuration))
10166 (origbuf (current-buffer))
10167 (region (when (org-region-active-p)
10168 (buffer-substring (region-beginning) (region-end))))
10169 (remove (and region (list (region-beginning) (region-end))))
10170 (desc region)
10171 (link link-location)
10172 (abbrevs org-link-abbrev-alist-local)
10173 entry all-prefixes auto-desc)
10174 (cond
10175 (link-location) ; specified by arg, just use it.
10176 ((org-in-regexp org-bracket-link-regexp 1)
10177 ;; We do have a link at point, and we are going to edit it.
10178 (setq remove (list (match-beginning 0) (match-end 0)))
10179 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10180 (setq link (read-string "Link: "
10181 (org-link-unescape
10182 (match-string-no-properties 1)))))
10183 ((or (org-in-regexp org-angle-link-re)
10184 (org-in-regexp org-plain-link-re))
10185 ;; Convert to bracket link
10186 (setq remove (list (match-beginning 0) (match-end 0))
10187 link (read-string "Link: "
10188 (org-unbracket-string "<" ">" (match-string 0)))))
10189 ((member complete-file '((4) (16)))
10190 ;; Completing read for file names.
10191 (setq link (org-file-complete-link complete-file)))
10193 ;; Read link, with completion for stored links.
10194 (org-link-fontify-links-to-this-file)
10195 (org-switch-to-buffer-other-window "*Org Links*")
10196 (with-current-buffer "*Org Links*"
10197 (erase-buffer)
10198 (insert "Insert a link.
10199 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10200 (when org-stored-links
10201 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10202 (insert (mapconcat 'org-link-prettify
10203 (reverse org-stored-links) "\n")))
10204 (goto-char (point-min)))
10205 (let ((cw (selected-window)))
10206 (select-window (get-buffer-window "*Org Links*" 'visible))
10207 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10208 (unless (pos-visible-in-window-p (point-max))
10209 (org-fit-window-to-buffer))
10210 (and (window-live-p cw) (select-window cw)))
10211 (setq all-prefixes (append (mapcar 'car abbrevs)
10212 (mapcar 'car org-link-abbrev-alist)
10213 (org-link-types)))
10214 (unwind-protect
10215 ;; Fake a link history, containing the stored links.
10216 (let ((org--links-history
10217 (append (mapcar #'car org-stored-links)
10218 org-insert-link-history)))
10219 (setq link
10220 (org-completing-read
10221 "Link: "
10222 (append
10223 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10224 (mapcar #'car org-stored-links))
10225 nil nil nil
10226 'org--links-history
10227 (caar org-stored-links)))
10228 (unless (org-string-nw-p link) (user-error "No link selected"))
10229 (dolist (l org-stored-links)
10230 (when (equal link (cadr l))
10231 (setq link (car l))
10232 (setq auto-desc t)))
10233 (when (or (member link all-prefixes)
10234 (and (equal ":" (substring link -1))
10235 (member (substring link 0 -1) all-prefixes)
10236 (setq link (substring link 0 -1))))
10237 (setq link (with-current-buffer origbuf
10238 (org-link-try-special-completion link)))))
10239 (set-window-configuration wcf)
10240 (kill-buffer "*Org Links*"))
10241 (setq entry (assoc link org-stored-links))
10242 (or entry (push link org-insert-link-history))
10243 (setq desc (or desc (nth 1 entry)))))
10245 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10246 (not org-keep-stored-link-after-insertion))
10247 (setq org-stored-links (delq (assoc link org-stored-links)
10248 org-stored-links)))
10250 (when (and (string-match org-plain-link-re link)
10251 (not (string-match org-ts-regexp link)))
10252 ;; URL-like link, normalize the use of angular brackets.
10253 (setq link (org-unbracket-string "<" ">" link)))
10255 ;; Check if we are linking to the current file with a search
10256 ;; option If yes, simplify the link by using only the search
10257 ;; option.
10258 (when (and buffer-file-name
10259 (let ((case-fold-search nil))
10260 (string-match "\\`file:\\(.+?\\)::" link)))
10261 (let ((path (match-string-no-properties 1 link))
10262 (search (substring-no-properties link (match-end 0))))
10263 (save-match-data
10264 (when (equal (file-truename buffer-file-name) (file-truename path))
10265 ;; We are linking to this same file, with a search option
10266 (setq link search)))))
10268 ;; Check if we can/should use a relative path. If yes, simplify the link
10269 (let ((case-fold-search nil))
10270 (when (string-match "\\`\\(file\\|docview\\):" link)
10271 (let* ((type (match-string-no-properties 0 link))
10272 (path (substring-no-properties link (match-end 0)))
10273 (origpath path))
10274 (cond
10275 ((or (eq org-link-file-path-type 'absolute)
10276 (equal complete-file '(16)))
10277 (setq path (abbreviate-file-name (expand-file-name path))))
10278 ((eq org-link-file-path-type 'noabbrev)
10279 (setq path (expand-file-name path)))
10280 ((eq org-link-file-path-type 'relative)
10281 (setq path (file-relative-name path)))
10283 (save-match-data
10284 (if (string-match (concat "^" (regexp-quote
10285 (expand-file-name
10286 (file-name-as-directory
10287 default-directory))))
10288 (expand-file-name path))
10289 ;; We are linking a file with relative path name.
10290 (setq path (substring (expand-file-name path)
10291 (match-end 0)))
10292 (setq path (abbreviate-file-name (expand-file-name path)))))))
10293 (setq link (concat type path))
10294 (when (equal desc origpath)
10295 (setq desc path)))))
10297 (if org-make-link-description-function
10298 (setq desc
10299 (or (condition-case nil
10300 (funcall org-make-link-description-function link desc)
10301 (error (progn (message "Can't get link description from `%s'"
10302 (symbol-name org-make-link-description-function))
10303 (sit-for 2) nil)))
10304 (read-string "Description: " default-description)))
10305 (if default-description (setq desc default-description)
10306 (setq desc (or (and auto-desc desc)
10307 (read-string "Description: " desc)))))
10309 (unless (string-match "\\S-" desc) (setq desc nil))
10310 (when remove (apply 'delete-region remove))
10311 (insert (org-make-link-string link desc))
10312 ;; Redisplay so as the new link has proper invisible characters.
10313 (sit-for 0)))
10315 (defun org-link-try-special-completion (type)
10316 "If there is completion support for link type TYPE, offer it."
10317 (let ((fun (org-link-get-parameter type :complete)))
10318 (if (functionp fun)
10319 (funcall fun)
10320 (read-string "Link (no completion support): " (concat type ":")))))
10322 (defun org-file-complete-link (&optional arg)
10323 "Create a file link using completion."
10324 (let ((file (read-file-name "File: "))
10325 (pwd (file-name-as-directory (expand-file-name ".")))
10326 (pwd1 (file-name-as-directory (abbreviate-file-name
10327 (expand-file-name ".")))))
10328 (cond ((equal arg '(16))
10329 (concat "file:"
10330 (abbreviate-file-name (expand-file-name file))))
10331 ((string-match
10332 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10333 (concat "file:" (match-string 1 file)))
10334 ((string-match
10335 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10336 (expand-file-name file))
10337 (concat "file:"
10338 (match-string 1 (expand-file-name file))))
10339 (t (concat "file:" file)))))
10341 (defun org-completing-read (&rest args)
10342 "Completing-read with SPACE being a normal character."
10343 (let ((enable-recursive-minibuffers t)
10344 (minibuffer-local-completion-map
10345 (copy-keymap minibuffer-local-completion-map)))
10346 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10347 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10348 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10349 'org-time-stamp-inactive)
10350 (apply #'completing-read args)))
10352 ;;; Opening/following a link
10354 (defvar org-link-search-failed nil)
10356 (defvar org-open-link-functions nil
10357 "Hook for functions finding a plain text link.
10358 These functions must take a single argument, the link content.
10359 They will be called for links that look like [[link text][description]]
10360 when LINK TEXT does not have a protocol like \"http:\" and does not look
10361 like a filename (e.g. \"./blue.png\").
10363 These functions will be called *before* Org attempts to resolve the
10364 link by doing text searches in the current buffer - so if you want a
10365 link \"[[target]]\" to still find \"<<target>>\", your function should
10366 handle this as a special case.
10368 When the function does handle the link, it must return a non-nil value.
10369 If it decides that it is not responsible for this link, it must return
10370 nil to indicate that that Org can continue with other options like
10371 exact and fuzzy text search.")
10373 (defun org-next-link (&optional search-backward)
10374 "Move forward to the next link.
10375 If the link is in hidden text, expose it."
10376 (interactive "P")
10377 (when (and org-link-search-failed (eq this-command last-command))
10378 (goto-char (point-min))
10379 (message "Link search wrapped back to beginning of buffer"))
10380 (setq org-link-search-failed nil)
10381 (let* ((pos (point))
10382 (ct (org-context))
10383 (a (assq :link ct))
10384 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10385 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10386 ((looking-at org-any-link-re)
10387 ;; Don't stay stuck at link without an org-link face
10388 (forward-char (if search-backward -1 1))))
10389 (if (funcall srch-fun org-any-link-re nil t)
10390 (progn
10391 (goto-char (match-beginning 0))
10392 (when (org-invisible-p) (org-show-context)))
10393 (goto-char pos)
10394 (setq org-link-search-failed t)
10395 (message "No further link found"))))
10397 (defun org-previous-link ()
10398 "Move backward to the previous link.
10399 If the link is in hidden text, expose it."
10400 (interactive)
10401 (funcall 'org-next-link t))
10403 (defun org-translate-link (s)
10404 "Translate a link string if a translation function has been defined."
10405 (with-temp-buffer
10406 (insert (org-trim s))
10407 (org-trim (org-element-interpret-data (org-element-context)))))
10409 (defun org-translate-link-from-planner (type path)
10410 "Translate a link from Emacs Planner syntax so that Org can follow it.
10411 This is still an experimental function, your mileage may vary."
10412 (cond
10413 ((member type '("http" "https" "news" "ftp"))
10414 ;; standard Internet links are the same.
10415 nil)
10416 ((and (equal type "irc") (string-match "^//" path))
10417 ;; Planner has two / at the beginning of an irc link, we have 1.
10418 ;; We should have zero, actually....
10419 (setq path (substring path 1)))
10420 ((and (equal type "lisp") (string-match "^/" path))
10421 ;; Planner has a slash, we do not.
10422 (setq type "elisp" path (substring path 1)))
10423 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10424 ;; A typical message link. Planner has the id after the final slash,
10425 ;; we separate it with a hash mark
10426 (setq path (concat (match-string 1 path) "#"
10427 (org-unbracket-string "<" ">" (match-string 2 path))))))
10428 (cons type path))
10430 (defun org-find-file-at-mouse (ev)
10431 "Open file link or URL at mouse."
10432 (interactive "e")
10433 (mouse-set-point ev)
10434 (org-open-at-point 'in-emacs))
10436 (defun org-open-at-mouse (ev)
10437 "Open file link or URL at mouse.
10438 See the docstring of `org-open-file' for details."
10439 (interactive "e")
10440 (mouse-set-point ev)
10441 (when (eq major-mode 'org-agenda-mode)
10442 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10443 (org-open-at-point))
10445 (defvar org-window-config-before-follow-link nil
10446 "The window configuration before following a link.
10447 This is saved in case the need arises to restore it.")
10449 ;;;###autoload
10450 (defun org-open-at-point-global ()
10451 "Follow a link or time-stamp like Org mode does.
10452 This command can be called in any mode to follow an external link
10453 or a time-stamp that has Org mode syntax. Its behavior is
10454 undefined when called on internal links (e.g., fuzzy links).
10455 Raise an error when there is nothing to follow. "
10456 (interactive)
10457 (cond ((org-in-regexp org-any-link-re)
10458 (org-open-link-from-string (match-string-no-properties 0)))
10459 ((or (org-in-regexp org-ts-regexp-both nil t)
10460 (org-in-regexp org-tsr-regexp-both nil t))
10461 (org-follow-timestamp-link))
10462 (t (user-error "No link found"))))
10464 ;;;###autoload
10465 (defun org-open-link-from-string (s &optional arg reference-buffer)
10466 "Open a link in the string S, as if it was in Org mode."
10467 (interactive "sLink: \nP")
10468 (let ((reference-buffer (or reference-buffer (current-buffer))))
10469 (with-temp-buffer
10470 (let ((org-inhibit-startup (not reference-buffer)))
10471 (org-mode)
10472 (insert s)
10473 (goto-char (point-min))
10474 (when reference-buffer
10475 (setq org-link-abbrev-alist-local
10476 (with-current-buffer reference-buffer
10477 org-link-abbrev-alist-local)))
10478 (org-open-at-point arg reference-buffer)))))
10480 (defvar org-open-at-point-functions nil
10481 "Hook that is run when following a link at point.
10483 Functions in this hook must return t if they identify and follow
10484 a link at point. If they don't find anything interesting at point,
10485 they must return nil.")
10487 (defvar org-link-search-inhibit-query nil)
10488 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10489 (defun org--open-doi-link (path)
10490 "Open a \"doi\" type link.
10491 PATH is a the path to search for, as a string."
10492 (browse-url (url-encode-url (concat org-doi-server-url path))))
10494 (defun org--open-elisp-link (path)
10495 "Open a \"elisp\" type link.
10496 PATH is the sexp to evaluate, as a string."
10497 (let ((cmd path))
10498 (if (or (and (org-string-nw-p
10499 org-confirm-elisp-link-not-regexp)
10500 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10501 (not org-confirm-elisp-link-function)
10502 (funcall org-confirm-elisp-link-function
10503 (format "Execute \"%s\" as elisp? "
10504 (org-add-props cmd nil 'face 'org-warning))))
10505 (message "%s => %s" cmd
10506 (if (eq (string-to-char cmd) ?\()
10507 (eval (read cmd))
10508 (call-interactively (read cmd))))
10509 (user-error "Abort"))))
10511 (defun org--open-help-link (path)
10512 "Open a \"help\" type link.
10513 PATH is a symbol name, as a string."
10514 (pcase (intern path)
10515 ((and (pred fboundp) variable) (describe-function variable))
10516 ((and (pred boundp) function) (describe-variable function))
10517 (name (user-error "Unknown function or variable: %s" name))))
10519 (defun org--open-shell-link (path)
10520 "Open a \"shell\" type link.
10521 PATH is the command to execute, as a string."
10522 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10523 (cmd path))
10524 (if (or (and (org-string-nw-p
10525 org-confirm-shell-link-not-regexp)
10526 (string-match
10527 org-confirm-shell-link-not-regexp cmd))
10528 (not org-confirm-shell-link-function)
10529 (funcall org-confirm-shell-link-function
10530 (format "Execute \"%s\" in shell? "
10531 (org-add-props cmd nil
10532 'face 'org-warning))))
10533 (progn
10534 (message "Executing %s" cmd)
10535 (shell-command cmd buf)
10536 (when (featurep 'midnight)
10537 (setq clean-buffer-list-kill-buffer-names
10538 (cons (buffer-name buf)
10539 clean-buffer-list-kill-buffer-names))))
10540 (user-error "Abort"))))
10542 (defun org-open-at-point (&optional arg reference-buffer)
10543 "Open link, timestamp, footnote or tags at point.
10545 When point is on a link, follow it. Normally, files will be
10546 opened by an appropriate application. If the optional prefix
10547 argument ARG is non-nil, Emacs will visit the file. With
10548 a double prefix argument, try to open outside of Emacs, in the
10549 application the system uses for this file type.
10551 When point is on a timestamp, open the agenda at the day
10552 specified.
10554 When point is a footnote definition, move to the first reference
10555 found. If it is on a reference, move to the associated
10556 definition.
10558 When point is on a headline, display a list of every link in the
10559 entry, so it is possible to pick one, or all, of them. If point
10560 is on a tag, call `org-tags-view' instead.
10562 When optional argument REFERENCE-BUFFER is non-nil, it should
10563 specify a buffer from where the link search should happen. This
10564 is used internally by `org-open-link-from-string'.
10566 On top of syntactically correct links, this function will also
10567 try to open links and time-stamps in comments, example
10568 blocks... i.e., whenever point is on something looking like
10569 a timestamp or a link."
10570 (interactive "P")
10571 ;; On a code block, open block's results.
10572 (unless (call-interactively 'org-babel-open-src-block-result)
10573 (org-load-modules-maybe)
10574 (setq org-window-config-before-follow-link (current-window-configuration))
10575 (org-remove-occur-highlights nil nil t)
10576 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10577 (let* ((context
10578 ;; Only consider supported types, even if they are not
10579 ;; the closest one.
10580 (org-element-lineage
10581 (org-element-context)
10582 '(clock footnote-definition footnote-reference headline
10583 inlinetask link timestamp)
10585 (type (org-element-type context))
10586 (value (org-element-property :value context)))
10587 (cond
10588 ;; On a headline or an inlinetask, but not on a timestamp,
10589 ;; a link, a footnote reference.
10590 ((memq type '(headline inlinetask))
10591 (org-match-line org-complex-heading-regexp)
10592 (if (and (match-beginning 5)
10593 (>= (point) (match-beginning 5))
10594 (< (point) (match-end 5)))
10595 ;; On tags.
10596 (org-tags-view arg (substring (match-string 5) 0 -1))
10597 ;; Not on tags.
10598 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10599 (`(nil . ,_)
10600 (require 'org-attach)
10601 (org-attach-reveal 'if-exists))
10602 (`(,links . ,links-end)
10603 (dolist (link (if (stringp links) (list links) links))
10604 (search-forward link nil links-end)
10605 (goto-char (match-beginning 0))
10606 (org-open-at-point))))))
10607 ;; On a footnote reference or at definition's label.
10608 ((or (eq type 'footnote-reference)
10609 (and (eq type 'footnote-definition)
10610 (save-excursion
10611 ;; Do not validate action when point is on the
10612 ;; spaces right after the footnote label, in
10613 ;; order to be on par with behaviour on links.
10614 (skip-chars-forward " \t")
10615 (let ((begin
10616 (org-element-property :contents-begin context)))
10617 (if begin (< (point) begin)
10618 (= (org-element-property :post-affiliated context)
10619 (line-beginning-position)))))))
10620 (org-footnote-action))
10621 ;; No valid context. Ignore catch-all types like `headline'.
10622 ;; If point is on something looking like a link or
10623 ;; a time-stamp, try opening it. It may be useful in
10624 ;; comments, example blocks...
10625 ((memq type '(footnote-definition headline inlinetask nil))
10626 (call-interactively #'org-open-at-point-global))
10627 ;; On a clock line, make sure point is on the timestamp
10628 ;; before opening it.
10629 ((and (eq type 'clock)
10630 value
10631 (>= (point) (org-element-property :begin value))
10632 (<= (point) (org-element-property :end value)))
10633 (org-follow-timestamp-link))
10634 ;; Do nothing on white spaces after an object.
10635 ((>= (point)
10636 (save-excursion
10637 (goto-char (org-element-property :end context))
10638 (skip-chars-backward " \t")
10639 (point)))
10640 (user-error "No link found"))
10641 ((eq type 'timestamp) (org-follow-timestamp-link))
10642 ((eq type 'link)
10643 (let ((type (org-element-property :type context))
10644 (path (org-link-unescape (org-element-property :path context))))
10645 ;; Switch back to REFERENCE-BUFFER needed when called in
10646 ;; a temporary buffer through `org-open-link-from-string'.
10647 (with-current-buffer (or reference-buffer (current-buffer))
10648 (cond
10649 ((equal type "file")
10650 (if (string-match "[*?{]" (file-name-nondirectory path))
10651 (dired path)
10652 ;; Look into `org-link-parameters' in order to find
10653 ;; a DEDICATED-FUNCTION to open file. The function
10654 ;; will be applied on raw link instead of parsed
10655 ;; link due to the limitation in `org-add-link-type'
10656 ;; ("open" function called with a single argument).
10657 ;; If no such function is found, fallback to
10658 ;; `org-open-file'.
10659 (let* ((option (org-element-property :search-option context))
10660 (app (org-element-property :application context))
10661 (dedicated-function
10662 (org-link-get-parameter
10663 (if app (concat type "+" app) type)
10664 :follow)))
10665 (if dedicated-function
10666 (funcall dedicated-function
10667 (concat path
10668 (and option (concat "::" option))))
10669 (apply #'org-open-file
10670 path
10671 (cond (arg)
10672 ((equal app "emacs") 'emacs)
10673 ((equal app "sys") 'system))
10674 (cond ((not option) nil)
10675 ((string-match-p "\\`[0-9]+\\'" option)
10676 (list (string-to-number option)))
10677 (t (list nil
10678 (org-link-unescape option)))))))))
10679 ((functionp (org-link-get-parameter type :follow))
10680 (funcall (org-link-get-parameter type :follow) path))
10681 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10682 (unless (run-hook-with-args-until-success
10683 'org-open-link-functions path)
10684 (if (not arg) (org-mark-ring-push)
10685 (switch-to-buffer-other-window
10686 (org-get-buffer-for-internal-link (current-buffer))))
10687 (let ((destination
10688 (org-with-wide-buffer
10689 (if (equal type "radio")
10690 (org-search-radio-target
10691 (org-element-property :path context))
10692 (org-link-search
10693 (if (member type '("custom-id" "coderef"))
10694 (org-element-property :raw-link context)
10695 path)
10696 ;; Prevent fuzzy links from matching
10697 ;; themselves.
10698 (and (equal type "fuzzy")
10699 (+ 2 (org-element-property :begin context)))))
10700 (point))))
10701 (unless (and (<= (point-min) destination)
10702 (>= (point-max) destination))
10703 (widen))
10704 (goto-char destination))))
10705 (t (browse-url-at-point))))))
10706 (t (user-error "No link found")))))
10707 (run-hook-with-args 'org-follow-link-hook)))
10709 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10710 "Offer links in the current entry and return the selected link.
10711 If there is only one link, return it.
10712 If NTH is an integer, return the NTH link found.
10713 If ZERO is a string, check also this string for a link, and if
10714 there is one, return it."
10715 (with-current-buffer buffer
10716 (org-with-wide-buffer
10717 (goto-char marker)
10718 (let ((cnt ?0)
10719 have-zero end links link c)
10720 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10721 (push (match-string 0 zero) links)
10722 (setq cnt (1- cnt) have-zero t))
10723 (save-excursion
10724 (org-back-to-heading t)
10725 (setq end (save-excursion (outline-next-heading) (point)))
10726 (while (re-search-forward org-any-link-re end t)
10727 (push (match-string 0) links))
10728 (setq links (org-uniquify (reverse links))))
10729 (cond
10730 ((null links)
10731 (message "No links"))
10732 ((equal (length links) 1)
10733 (setq link (car links)))
10734 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10735 (setq link (nth (if have-zero nth (1- nth)) links)))
10736 (t ; we have to select a link
10737 (save-excursion
10738 (save-window-excursion
10739 (delete-other-windows)
10740 (with-output-to-temp-buffer "*Select Link*"
10741 (dolist (l links)
10742 (cond
10743 ((not (string-match org-bracket-link-regexp l))
10744 (princ (format "[%c] %s\n" (cl-incf cnt)
10745 (org-unbracket-string "<" ">" l))))
10746 ((match-end 3)
10747 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10748 (match-string 3 l) (match-string 1 l))))
10749 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10750 (match-string 1 l)))))))
10751 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10752 (message "Select link to open, RET to open all:")
10753 (setq c (read-char-exclusive))
10754 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10755 (when (equal c ?q) (user-error "Abort"))
10756 (if (equal c ?\C-m)
10757 (setq link links)
10758 (setq nth (- c ?0))
10759 (when have-zero (setq nth (1+ nth)))
10760 (unless (and (integerp nth) (>= (length links) nth))
10761 (user-error "Invalid link selection"))
10762 (setq link (nth (1- nth) links)))))
10763 (cons link end)))))
10765 ;; TODO: These functions are deprecated since `org-open-at-point'
10766 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10767 (defun org-open-file-with-system (path)
10768 "Open file at PATH using the system way of opening it."
10769 (org-open-file path 'system))
10770 (defun org-open-file-with-emacs (path)
10771 "Open file at PATH in Emacs."
10772 (org-open-file path 'emacs))
10775 ;;; File search
10777 (defvar org-create-file-search-functions nil
10778 "List of functions to construct the right search string for a file link.
10779 These functions are called in turn with point at the location to
10780 which the link should point.
10782 A function in the hook should first test if it would like to
10783 handle this file type, for example by checking the `major-mode'
10784 or the file extension. If it decides not to handle this file, it
10785 should just return nil to give other functions a chance. If it
10786 does handle the file, it must return the search string to be used
10787 when following the link. The search string will be part of the
10788 file link, given after a double colon, and `org-open-at-point'
10789 will automatically search for it. If special measures must be
10790 taken to make the search successful, another function should be
10791 added to the companion hook `org-execute-file-search-functions',
10792 which see.
10794 A function in this hook may also use `setq' to set the variable
10795 `description' to provide a suggestion for the descriptive text to
10796 be used for this link when it gets inserted into an Org buffer
10797 with \\[org-insert-link].")
10799 (defvar org-execute-file-search-functions nil
10800 "List of functions to execute a file search triggered by a link.
10802 Functions added to this hook must accept a single argument, the
10803 search string that was part of the file link, the part after the
10804 double colon. The function must first check if it would like to
10805 handle this search, for example by checking the `major-mode' or
10806 the file extension. If it decides not to handle this search, it
10807 should just return nil to give other functions a chance. If it
10808 does handle the search, it must return a non-nil value to keep
10809 other functions from trying.
10811 Each function can access the current prefix argument through the
10812 variable `current-prefix-arg'. Note that a single prefix is used
10813 to force opening a link in Emacs, so it may be good to only use a
10814 numeric or double prefix to guide the search function.
10816 In case this is needed, a function in this hook can also restore
10817 the window configuration before `org-open-at-point' was called using:
10819 (set-window-configuration org-window-config-before-follow-link)")
10821 (defun org-search-radio-target (target)
10822 "Search a radio target matching TARGET in current buffer.
10823 White spaces are not significant."
10824 (let ((re (format "<<<%s>>>"
10825 (mapconcat #'regexp-quote
10826 (split-string target)
10827 "[ \t]+\\(?:\n[ \t]*\\)?")))
10828 (origin (point)))
10829 (goto-char (point-min))
10830 (catch :radio-match
10831 (while (re-search-forward re nil t)
10832 (backward-char)
10833 (let ((object (org-element-context)))
10834 (when (eq (org-element-type object) 'radio-target)
10835 (goto-char (org-element-property :begin object))
10836 (org-show-context 'link-search)
10837 (throw :radio-match nil))))
10838 (goto-char origin)
10839 (user-error "No match for radio target: %s" target))))
10841 (defun org-link-search (s &optional avoid-pos stealth)
10842 "Search for a search string S.
10844 If S starts with \"#\", it triggers a custom ID search.
10846 If S is enclosed within parenthesis, it initiates a coderef
10847 search.
10849 If S is surrounded by forward slashes, it is interpreted as
10850 a regular expression. In Org mode files, this will create an
10851 `org-occur' sparse tree. In ordinary files, `occur' will be used
10852 to list matches. If the current buffer is in `dired-mode', grep
10853 will be used to search in all files.
10855 When AVOID-POS is given, ignore matches near that position.
10857 When optional argument STEALTH is non-nil, do not modify
10858 visibility around point, thus ignoring `org-show-context-detail'
10859 variable.
10861 Search is case-insensitive and ignores white spaces. Return type
10862 of matched result, which is either `dedicated' or `fuzzy'."
10863 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10864 (let* ((case-fold-search t)
10865 (origin (point))
10866 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10867 (starred (eq (string-to-char normalized) ?*))
10868 (words (split-string (if starred (substring s 1) s)))
10869 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10870 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10871 type)
10872 (cond
10873 ;; Check if there are any special search functions.
10874 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10875 ((eq (string-to-char s) ?#)
10876 ;; Look for a custom ID S if S starts with "#".
10877 (let* ((id (substring normalized 1))
10878 (match (org-find-property "CUSTOM_ID" id)))
10879 (if match (progn (goto-char match) (setf type 'dedicated))
10880 (error "No match for custom ID: %s" id))))
10881 ((string-match "\\`(\\(.*\\))\\'" normalized)
10882 ;; Look for coderef targets if S is enclosed within parenthesis.
10883 (let ((coderef (match-string-no-properties 1 normalized))
10884 (re (substring s-single-re 1 -1)))
10885 (goto-char (point-min))
10886 (catch :coderef-match
10887 (while (re-search-forward re nil t)
10888 (let ((element (org-element-at-point)))
10889 (when (and (memq (org-element-type element)
10890 '(example-block src-block))
10891 ;; Build proper regexp according to current
10892 ;; block's label format.
10893 (let ((label-fmt
10894 (regexp-quote
10895 (or (org-element-property :label-fmt element)
10896 org-coderef-label-format))))
10897 (save-excursion
10898 (beginning-of-line)
10899 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10900 (format label-fmt coderef))))))
10901 (setq type 'dedicated)
10902 (goto-char (match-beginning 1))
10903 (throw :coderef-match nil))))
10904 (goto-char origin)
10905 (error "No match for coderef: %s" coderef))))
10906 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10907 ;; Look for a regular expression.
10908 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10909 (match-string 1 s)))
10910 ;; From here, we handle fuzzy links.
10912 ;; Look for targets, only if not in a headline search.
10913 ((and (not starred)
10914 (let ((target (format "<<%s>>" s-multi-re)))
10915 (catch :target-match
10916 (goto-char (point-min))
10917 (while (re-search-forward target nil t)
10918 (backward-char)
10919 (let ((context (org-element-context)))
10920 (when (eq (org-element-type context) 'target)
10921 (setq type 'dedicated)
10922 (goto-char (org-element-property :begin context))
10923 (throw :target-match t))))
10924 nil))))
10925 ;; Look for elements named after S, only if not in a headline
10926 ;; search.
10927 ((and (not starred)
10928 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10929 (catch :name-match
10930 (goto-char (point-min))
10931 (while (re-search-forward name nil t)
10932 (let ((element (org-element-at-point)))
10933 (when (equal words
10934 (split-string
10935 (org-element-property :name element)))
10936 (setq type 'dedicated)
10937 (beginning-of-line)
10938 (throw :name-match t))))
10939 nil))))
10940 ;; Regular text search. Prefer headlines in Org mode buffers.
10941 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10942 ;; statistics cookies and tags.
10943 ((and (derived-mode-p 'org-mode)
10944 (let ((title-re
10945 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10946 org-outline-regexp-bol
10947 org-comment-string
10948 (mapconcat #'regexp-quote words ".+")))
10949 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10950 (comment-re (eval-when-compile
10951 (format "\\`%s[ \t]+" org-comment-string))))
10952 (goto-char (point-min))
10953 (catch :found
10954 (while (re-search-forward title-re nil t)
10955 (when (equal words
10956 (split-string
10957 (replace-regexp-in-string
10958 cookie-re ""
10959 (replace-regexp-in-string
10960 comment-re "" (org-get-heading t t t)))))
10961 (throw :found t)))
10962 nil)))
10963 (beginning-of-line)
10964 (setq type 'dedicated))
10965 ;; Offer to create non-existent headline depending on
10966 ;; `org-link-search-must-match-exact-headline'.
10967 ((and (derived-mode-p 'org-mode)
10968 (not org-link-search-inhibit-query)
10969 (eq org-link-search-must-match-exact-headline 'query-to-create)
10970 (yes-or-no-p "No match - create this as a new heading? "))
10971 (goto-char (point-max))
10972 (unless (bolp) (newline))
10973 (org-insert-heading nil t t)
10974 (insert s "\n")
10975 (beginning-of-line 0))
10976 ;; Only headlines are looked after. No need to process
10977 ;; further: throw an error.
10978 ((and (derived-mode-p 'org-mode)
10979 (or starred org-link-search-must-match-exact-headline))
10980 (goto-char origin)
10981 (error "No match for fuzzy expression: %s" normalized))
10982 ;; Regular text search.
10983 ((catch :fuzzy-match
10984 (goto-char (point-min))
10985 (while (re-search-forward s-multi-re nil t)
10986 ;; Skip match if it contains AVOID-POS or it is included in
10987 ;; a link with a description but outside the description.
10988 (unless (or (and avoid-pos
10989 (<= (match-beginning 0) avoid-pos)
10990 (> (match-end 0) avoid-pos))
10991 (and (save-match-data
10992 (org-in-regexp org-bracket-link-regexp))
10993 (match-beginning 3)
10994 (or (> (match-beginning 3) (point))
10995 (<= (match-end 3) (point)))
10996 (org-element-lineage
10997 (save-match-data (org-element-context))
10998 '(link) t)))
10999 (goto-char (match-beginning 0))
11000 (setq type 'fuzzy)
11001 (throw :fuzzy-match t)))
11002 nil))
11003 ;; All failed. Throw an error.
11004 (t (goto-char origin)
11005 (error "No match for fuzzy expression: %s" normalized)))
11006 ;; Disclose surroundings of match, if appropriate.
11007 (when (and (derived-mode-p 'org-mode) (not stealth))
11008 (org-show-context 'link-search))
11009 type))
11011 (defun org-get-buffer-for-internal-link (buffer)
11012 "Return a buffer to be used for displaying the link target of internal links."
11013 (cond
11014 ((not org-display-internal-link-with-indirect-buffer)
11015 buffer)
11016 ((string-suffix-p "(Clone)" (buffer-name buffer))
11017 (message "Buffer is already a clone, not making another one")
11018 ;; we also do not modify visibility in this case
11019 buffer)
11020 (t ; make a new indirect buffer for displaying the link
11021 (let* ((bn (buffer-name buffer))
11022 (ibn (concat bn "(Clone)"))
11023 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11024 (with-current-buffer ib (org-overview))
11025 ib))))
11027 (defun org-do-occur (regexp &optional cleanup)
11028 "Call the Emacs command `occur'.
11029 If CLEANUP is non-nil, remove the printout of the regular expression
11030 in the *Occur* buffer. This is useful if the regex is long and not useful
11031 to read."
11032 (occur regexp)
11033 (when cleanup
11034 (let ((cwin (selected-window)) win beg end)
11035 (when (setq win (get-buffer-window "*Occur*"))
11036 (select-window win))
11037 (goto-char (point-min))
11038 (when (re-search-forward "match[a-z]+" nil t)
11039 (setq beg (match-end 0))
11040 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11041 (setq end (1- (match-beginning 0)))))
11042 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11043 (goto-char (point-min))
11044 (select-window cwin))))
11046 ;;; The mark ring for links jumps
11048 (defvar org-mark-ring nil
11049 "Mark ring for positions before jumps in Org mode.")
11050 (defvar org-mark-ring-last-goto nil
11051 "Last position in the mark ring used to go back.")
11052 ;; Fill and close the ring
11053 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11054 (dotimes (_ org-mark-ring-length)
11055 (push (make-marker) org-mark-ring))
11056 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11057 org-mark-ring)
11059 (defun org-mark-ring-push (&optional pos buffer)
11060 "Put the current position or POS into the mark ring and rotate it."
11061 (interactive)
11062 (setq pos (or pos (point)))
11063 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11064 (move-marker (car org-mark-ring)
11065 (or pos (point))
11066 (or buffer (current-buffer)))
11067 (message "%s"
11068 (substitute-command-keys
11069 "Position saved to mark ring, go back with \
11070 `\\[org-mark-ring-goto]'.")))
11072 (defun org-mark-ring-goto (&optional n)
11073 "Jump to the previous position in the mark ring.
11074 With prefix arg N, jump back that many stored positions. When
11075 called several times in succession, walk through the entire ring.
11076 Org mode commands jumping to a different position in the current file,
11077 or to another Org file, automatically push the old position onto the ring."
11078 (interactive "p")
11079 (let (p m)
11080 (if (eq last-command this-command)
11081 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11082 (setq p org-mark-ring))
11083 (setq org-mark-ring-last-goto p)
11084 (setq m (car p))
11085 (pop-to-buffer-same-window (marker-buffer m))
11086 (goto-char m)
11087 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11089 (defun org-add-angle-brackets (s)
11090 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11091 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11094 ;;; Following specific links
11096 (defvar org-agenda-buffer-tmp-name)
11097 (defvar org-agenda-start-on-weekday)
11098 (defun org-follow-timestamp-link ()
11099 "Open an agenda view for the time-stamp date/range at point."
11100 (cond
11101 ((org-at-date-range-p t)
11102 (let ((org-agenda-start-on-weekday)
11103 (t1 (match-string 1))
11104 (t2 (match-string 2)) tt1 tt2)
11105 (setq tt1 (time-to-days (org-time-string-to-time t1))
11106 tt2 (time-to-days (org-time-string-to-time t2)))
11107 (let ((org-agenda-buffer-tmp-name
11108 (format "*Org Agenda(a:%s)"
11109 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11110 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11111 ((org-at-timestamp-p 'lax)
11112 (let ((org-agenda-buffer-tmp-name
11113 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11114 (org-agenda-list nil (time-to-days (org-time-string-to-time
11115 (substring (match-string 1) 0 10)))
11116 1)))
11117 (t (error "This should not happen"))))
11120 ;;; Following file links
11121 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11122 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11123 (declare-function mailcap-mime-info
11124 "mailcap" (string &optional request no-decode))
11125 (defvar org-wait nil)
11126 (defun org-open-file (path &optional in-emacs line search)
11127 "Open the file at PATH.
11128 First, this expands any special file name abbreviations. Then the
11129 configuration variable `org-file-apps' is checked if it contains an
11130 entry for this file type, and if yes, the corresponding command is launched.
11132 If no application is found, Emacs simply visits the file.
11134 With optional prefix argument IN-EMACS, Emacs will visit the file.
11135 With a double \\[universal-argument] \\[universal-argument] \
11136 prefix arg, Org tries to avoid opening in Emacs
11137 and to use an external application to visit the file.
11139 Optional LINE specifies a line to go to, optional SEARCH a string
11140 to search for. If LINE or SEARCH is given, the file will be
11141 opened in Emacs, unless an entry from org-file-apps that makes
11142 use of groups in a regexp matches.
11144 If you want to change the way frames are used when following a
11145 link, please customize `org-link-frame-setup'.
11147 If the file does not exist, an error is thrown."
11148 (let* ((file (if (equal path "")
11149 buffer-file-name
11150 (substitute-in-file-name (expand-file-name path))))
11151 (file-apps (append org-file-apps (org-default-apps)))
11152 (apps (cl-remove-if
11153 'org-file-apps-entry-match-against-dlink-p file-apps))
11154 (apps-dlink (cl-remove-if-not
11155 'org-file-apps-entry-match-against-dlink-p file-apps))
11156 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11157 (dirp (unless remp (file-directory-p file)))
11158 (file (if (and dirp org-open-directory-means-index-dot-org)
11159 (concat (file-name-as-directory file) "index.org")
11160 file))
11161 (a-m-a-p (assq 'auto-mode apps))
11162 (dfile (downcase file))
11163 ;; Reconstruct the original link from the PATH, LINE and
11164 ;; SEARCH args.
11165 (link (cond (line (concat file "::" (number-to-string line)))
11166 (search (concat file "::" search))
11167 (t file)))
11168 (dlink (downcase link))
11169 (ext
11170 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11171 (match-string 1 dfile)))
11172 (save-position-maybe
11173 (let ((old-buffer (current-buffer))
11174 (old-pos (point))
11175 (old-mode major-mode))
11176 (lambda ()
11177 (and (derived-mode-p 'org-mode)
11178 (eq old-mode 'org-mode)
11179 (or (not (eq old-buffer (current-buffer)))
11180 (not (eq old-pos (point))))
11181 (org-mark-ring-push old-pos old-buffer)))))
11182 cmd link-match-data)
11183 (cond
11184 ((member in-emacs '((16) system))
11185 (setq cmd (cdr (assq 'system apps))))
11186 (in-emacs (setq cmd 'emacs))
11188 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11189 (and dirp (cdr (assq 'directory apps)))
11190 ;; First, try matching against apps-dlink if we
11191 ;; get a match here, store the match data for
11192 ;; later.
11193 (let ((match (assoc-default dlink apps-dlink
11194 'string-match)))
11195 (if match
11196 (progn (setq link-match-data (match-data))
11197 match)
11198 (progn (setq in-emacs (or in-emacs line search))
11199 nil))) ; if we have no match in apps-dlink,
11200 ; always open the file in emacs if line or search
11201 ; is given (for backwards compatibility)
11202 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11203 'string-match)
11204 (cdr (assoc ext apps))
11205 (cdr (assq t apps))))))
11206 (when (eq cmd 'system)
11207 (setq cmd (cdr (assq 'system apps))))
11208 (when (eq cmd 'default)
11209 (setq cmd (cdr (assoc t apps))))
11210 (when (eq cmd 'mailcap)
11211 (require 'mailcap)
11212 (mailcap-parse-mailcaps)
11213 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11214 (command (mailcap-mime-info mime-type)))
11215 (if (stringp command)
11216 (setq cmd command)
11217 (setq cmd 'emacs))))
11218 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11219 (not (file-exists-p file))
11220 (not org-open-non-existing-files))
11221 (user-error "No such file: %s" file))
11222 (cond
11223 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11224 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11225 (while (string-match "['\"]%s['\"]" cmd)
11226 (setq cmd (replace-match "%s" t t cmd)))
11227 (setq cmd (replace-regexp-in-string
11228 "%s"
11229 (shell-quote-argument (convert-standard-filename file))
11231 nil t))
11233 ;; Replace "%1", "%2" etc. in command with group matches from regex
11234 (save-match-data
11235 (let ((match-index 1)
11236 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11237 (set-match-data link-match-data)
11238 (while (<= match-index number-of-groups)
11239 (let ((regex (concat "%" (number-to-string match-index)))
11240 (replace-with (match-string match-index dlink)))
11241 (while (string-match regex cmd)
11242 (setq cmd (replace-match replace-with t t cmd))))
11243 (setq match-index (+ match-index 1)))))
11245 (save-window-excursion
11246 (message "Running %s...done" cmd)
11247 (start-process-shell-command cmd nil cmd)
11248 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11249 ((or (stringp cmd)
11250 (eq cmd 'emacs))
11251 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11252 (widen)
11253 (cond (line (org-goto-line line)
11254 (when (derived-mode-p 'org-mode) (org-reveal)))
11255 (search (condition-case err
11256 (org-link-search search)
11257 ;; Save position before error-ing out so user
11258 ;; can easily move back to the original buffer.
11259 (error (funcall save-position-maybe)
11260 (error (nth 1 err)))))))
11261 ((functionp cmd)
11262 (save-match-data
11263 (set-match-data link-match-data)
11264 (condition-case nil
11265 (funcall cmd file link)
11266 ;; FIXME: Remove this check when most default installations
11267 ;; of Emacs have at least Org 9.0.
11268 ((debug wrong-number-of-arguments wrong-type-argument
11269 invalid-function)
11270 (user-error "Please see Org News for version 9.0 about \
11271 `org-file-apps'--Lisp error: %S" cmd)))))
11272 ((consp cmd)
11273 ;; FIXME: Remove this check when most default installations of
11274 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11275 ;; fall back to `org-link-frame-setup' for an old usage of
11276 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11277 (user-error "Please see Org News for version 9.0 about \
11278 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11279 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11280 (funcall save-position-maybe)))
11282 (defun org-file-apps-entry-match-against-dlink-p (entry)
11283 "This function returns non-nil if `entry' uses a regular
11284 expression which should be matched against the whole link by
11285 org-open-file.
11287 It assumes that is the case when the entry uses a regular
11288 expression which has at least one grouping construct and the
11289 action is either a lisp form or a command string containing
11290 `%1', i.e. using at least one subexpression match as a
11291 parameter."
11292 (let ((selector (car entry))
11293 (action (cdr entry)))
11294 (if (stringp selector)
11295 (and (> (regexp-opt-depth selector) 0)
11296 (or (and (stringp action)
11297 (string-match "%[0-9]" action))
11298 (consp action)))
11299 nil)))
11301 (defun org-default-apps ()
11302 "Return the default applications for this operating system."
11303 (cond
11304 ((eq system-type 'darwin)
11305 org-file-apps-defaults-macosx)
11306 ((eq system-type 'windows-nt)
11307 org-file-apps-defaults-windowsnt)
11308 (t org-file-apps-defaults-gnu)))
11310 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11311 "Convert extensions to regular expressions in the cars of LIST.
11312 Also, weed out any non-string entries, because the return value is used
11313 only for regexp matching.
11314 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11315 point to the symbol `emacs', indicating that the file should
11316 be opened in Emacs."
11317 (append
11318 (delq nil
11319 (mapcar (lambda (x)
11320 (unless (not (stringp (car x)))
11321 (if (string-match "\\W" (car x))
11323 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11324 list))
11325 (when add-auto-mode
11326 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11328 (defvar ange-ftp-name-format)
11329 (defun org-file-remote-p (file)
11330 "Test whether FILE specifies a location on a remote system.
11331 Return non-nil if the location is indeed remote.
11333 For example, the filename \"/user@host:/foo\" specifies a location
11334 on the system \"/user@host:\"."
11335 (cond ((fboundp 'file-remote-p)
11336 (file-remote-p file))
11337 ((fboundp 'tramp-handle-file-remote-p)
11338 (tramp-handle-file-remote-p file))
11339 ((and (boundp 'ange-ftp-name-format)
11340 (string-match (car ange-ftp-name-format) file))
11341 t)))
11344 ;;;; Refiling
11346 (defun org-get-org-file ()
11347 "Read a filename, with default directory `org-directory'."
11348 (let ((default (or org-default-notes-file remember-data-file)))
11349 (read-file-name (format "File name [%s]: " default)
11350 (file-name-as-directory org-directory)
11351 default)))
11353 (defun org-notes-order-reversed-p ()
11354 "Check if the current file should receive notes in reversed order."
11355 (cond
11356 ((not org-reverse-note-order) nil)
11357 ((eq t org-reverse-note-order) t)
11358 ((not (listp org-reverse-note-order)) nil)
11359 (t (catch 'exit
11360 (dolist (entry org-reverse-note-order)
11361 (when (string-match (car entry) buffer-file-name)
11362 (throw 'exit (cdr entry))))))))
11364 (defvar org-refile-target-table nil
11365 "The list of refile targets, created by `org-refile'.")
11367 (defvar org-agenda-new-buffers nil
11368 "Buffers created to visit agenda files.")
11370 (defvar org-refile-cache nil
11371 "Cache for refile targets.")
11373 (defvar org-refile-markers nil
11374 "All the markers used for caching refile locations.")
11376 (defun org-refile-marker (pos)
11377 "Get a new refile marker, but only if caching is in use."
11378 (if (not org-refile-use-cache)
11380 (let ((m (make-marker)))
11381 (move-marker m pos)
11382 (push m org-refile-markers)
11383 m)))
11385 (defun org-refile-cache-clear ()
11386 "Clear the refile cache and disable all the markers."
11387 (dolist (m org-refile-markers) (move-marker m nil))
11388 (setq org-refile-markers nil)
11389 (setq org-refile-cache nil)
11390 (message "Refile cache has been cleared"))
11392 (defun org-refile-cache-check-set (set)
11393 "Check if all the markers in the cache still have live buffers."
11394 (let (marker)
11395 (catch 'exit
11396 (while (and set (setq marker (nth 3 (pop set))))
11397 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11398 (when (and marker (null (marker-buffer marker)))
11399 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11400 (sit-for 3)
11401 (throw 'exit nil)))
11402 t)))
11404 (defun org-refile-cache-put (set &rest identifiers)
11405 "Push the refile targets SET into the cache, under IDENTIFIERS."
11406 (let* ((key (sha1 (prin1-to-string identifiers)))
11407 (entry (assoc key org-refile-cache)))
11408 (if entry
11409 (setcdr entry set)
11410 (push (cons key set) org-refile-cache))))
11412 (defun org-refile-cache-get (&rest identifiers)
11413 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11414 (cond
11415 ((not org-refile-cache) nil)
11416 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11418 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11419 org-refile-cache))))
11420 (and set (org-refile-cache-check-set set) set)))))
11422 (defvar org-outline-path-cache nil
11423 "Alist between buffer positions and outline paths.
11424 It value is an alist (POSITION . PATH) where POSITION is the
11425 buffer position at the beginning of an entry and PATH is a list
11426 of strings describing the outline path for that entry, in reverse
11427 order.")
11429 (defun org-refile-get-targets (&optional default-buffer)
11430 "Produce a table with refile targets."
11431 (let ((case-fold-search nil)
11432 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11433 (entries (or org-refile-targets '((nil . (:level . 1)))))
11434 targets tgs files desc descre)
11435 (message "Getting targets...")
11436 (with-current-buffer (or default-buffer (current-buffer))
11437 (dolist (entry entries)
11438 (setq files (car entry) desc (cdr entry))
11439 (cond
11440 ((null files) (setq files (list (current-buffer))))
11441 ((eq files 'org-agenda-files)
11442 (setq files (org-agenda-files 'unrestricted)))
11443 ((and (symbolp files) (fboundp files))
11444 (setq files (funcall files)))
11445 ((and (symbolp files) (boundp files))
11446 (setq files (symbol-value files))))
11447 (when (stringp files) (setq files (list files)))
11448 (cond
11449 ((eq (car desc) :tag)
11450 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11451 ((eq (car desc) :todo)
11452 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11453 ((eq (car desc) :regexp)
11454 (setq descre (cdr desc)))
11455 ((eq (car desc) :level)
11456 (setq descre (concat "^\\*\\{" (number-to-string
11457 (if org-odd-levels-only
11458 (1- (* 2 (cdr desc)))
11459 (cdr desc)))
11460 "\\}[ \t]")))
11461 ((eq (car desc) :maxlevel)
11462 (setq descre (concat "^\\*\\{1," (number-to-string
11463 (if org-odd-levels-only
11464 (1- (* 2 (cdr desc)))
11465 (cdr desc)))
11466 "\\}[ \t]")))
11467 (t (error "Bad refiling target description %s" desc)))
11468 (dolist (f files)
11469 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11471 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11472 (progn
11473 (when (bufferp f)
11474 (setq f (buffer-file-name (buffer-base-buffer f))))
11475 (setq f (and f (expand-file-name f)))
11476 (when (eq org-refile-use-outline-path 'file)
11477 (push (list (file-name-nondirectory f) f nil nil) tgs))
11478 (when (eq org-refile-use-outline-path 'buffer-name)
11479 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11480 (when (eq org-refile-use-outline-path 'full-file-path)
11481 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11482 (org-with-wide-buffer
11483 (goto-char (point-min))
11484 (setq org-outline-path-cache nil)
11485 (while (re-search-forward descre nil t)
11486 (beginning-of-line)
11487 (let ((case-fold-search nil))
11488 (looking-at org-complex-heading-regexp))
11489 (let ((begin (point))
11490 (heading (match-string-no-properties 4)))
11491 (unless (or (and
11492 org-refile-target-verify-function
11493 (not
11494 (funcall org-refile-target-verify-function)))
11495 (not heading))
11496 (let ((re (format org-complex-heading-regexp-format
11497 (regexp-quote heading)))
11498 (target
11499 (if (not org-refile-use-outline-path) heading
11500 (mapconcat
11501 #'identity
11502 (append
11503 (pcase org-refile-use-outline-path
11504 (`file (list (file-name-nondirectory
11505 (buffer-file-name
11506 (buffer-base-buffer)))))
11507 (`full-file-path
11508 (list (buffer-file-name
11509 (buffer-base-buffer))))
11510 (`buffer-name
11511 (list (buffer-name
11512 (buffer-base-buffer))))
11513 (_ nil))
11514 (mapcar (lambda (s) (replace-regexp-in-string
11515 "/" "\\/" s nil t))
11516 (org-get-outline-path t t)))
11517 "/"))))
11518 (push (list target f re (org-refile-marker (point)))
11519 tgs)))
11520 (when (= (point) begin)
11521 ;; Verification function has not moved point.
11522 (end-of-line)))))))
11523 (when org-refile-use-cache
11524 (org-refile-cache-put tgs (buffer-file-name) descre))
11525 (setq targets (append tgs targets))))))
11526 (message "Getting targets...done")
11527 (delete-dups (nreverse targets))))
11529 (defun org--get-outline-path-1 (&optional use-cache)
11530 "Return outline path to current headline.
11532 Outline path is a list of strings, in reverse order. When
11533 optional argument USE-CACHE is non-nil, make use of a cache. See
11534 `org-get-outline-path' for details.
11536 Assume buffer is widened and point is on a headline."
11537 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11538 (let ((p (point))
11539 (heading (let ((case-fold-search nil))
11540 (looking-at org-complex-heading-regexp)
11541 (if (not (match-end 4)) ""
11542 ;; Remove statistics cookies.
11543 (org-trim
11544 (org-link-display-format
11545 (replace-regexp-in-string
11546 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11547 (match-string-no-properties 4))))))))
11548 (if (org-up-heading-safe)
11549 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11550 (when use-cache
11551 (push (cons p path) org-outline-path-cache))
11552 path)
11553 ;; This is a new root node. Since we assume we are moving
11554 ;; forward, we can drop previous cache so as to limit number
11555 ;; of associations there.
11556 (let ((path (list heading)))
11557 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11558 path)))))
11560 (defun org-get-outline-path (&optional with-self use-cache)
11561 "Return the outline path to the current entry.
11563 An outline path is a list of ancestors for current headline, as
11564 a list of strings. Statistics cookies are removed and links are
11565 replaced with their description, if any, or their path otherwise.
11567 When optional argument WITH-SELF is non-nil, the path also
11568 includes the current headline.
11570 When optional argument USE-CACHE is non-nil, cache outline paths
11571 between calls to this function so as to avoid backtracking. This
11572 argument is useful when planning to find more than one outline
11573 path in the same document. In that case, there are two
11574 conditions to satisfy:
11575 - `org-outline-path-cache' is set to nil before starting the
11576 process;
11577 - outline paths are computed by increasing buffer positions."
11578 (org-with-wide-buffer
11579 (and (or (and with-self (org-back-to-heading t))
11580 (org-up-heading-safe))
11581 (reverse (org--get-outline-path-1 use-cache)))))
11583 (defun org-format-outline-path (path &optional width prefix separator)
11584 "Format the outline path PATH for display.
11585 WIDTH is the maximum number of characters that is available.
11586 PREFIX is a prefix to be included in the returned string,
11587 such as the file name.
11588 SEPARATOR is inserted between the different parts of the path,
11589 the default is \"/\"."
11590 (setq width (or width 79))
11591 (setq path (delq nil path))
11592 (unless (> width 0)
11593 (user-error "Argument `width' must be positive"))
11594 (setq separator (or separator "/"))
11595 (let* ((org-odd-levels-only nil)
11596 (fpath (concat
11597 prefix (and prefix path separator)
11598 (mapconcat
11599 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11600 (cl-loop for head in path
11601 for n from 0
11602 collect (org-add-props
11603 head nil 'face
11604 (nth (% n org-n-level-faces) org-level-faces)))
11605 separator))))
11606 (when (> (length fpath) width)
11607 (if (< width 7)
11608 ;; It's unlikely that `width' will be this small, but don't
11609 ;; waste characters by adding ".." if it is.
11610 (setq fpath (substring fpath 0 width))
11611 (setf (substring fpath (- width 2)) "..")))
11612 fpath))
11614 (defun org-display-outline-path (&optional file current separator just-return-string)
11615 "Display the current outline path in the echo area.
11617 If FILE is non-nil, prepend the output with the file name.
11618 If CURRENT is non-nil, append the current heading to the output.
11619 SEPARATOR is passed through to `org-format-outline-path'. It separates
11620 the different parts of the path and defaults to \"/\".
11621 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11622 (interactive "P")
11623 (let* (case-fold-search
11624 (bfn (buffer-file-name (buffer-base-buffer)))
11625 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11626 res)
11627 (when current (setq path (append path
11628 (save-excursion
11629 (org-back-to-heading t)
11630 (when (looking-at org-complex-heading-regexp)
11631 (list (match-string 4)))))))
11632 (setq res
11633 (org-format-outline-path
11634 path
11635 (1- (frame-width))
11636 (and file bfn (concat (file-name-nondirectory bfn) separator))
11637 separator))
11638 (if just-return-string
11639 (org-no-properties res)
11640 (org-unlogged-message "%s" res))))
11642 (defvar org-refile-history nil
11643 "History for refiling operations.")
11645 (defvar org-after-refile-insert-hook nil
11646 "Hook run after `org-refile' has inserted its stuff at the new location.
11647 Note that this is still *before* the stuff will be removed from
11648 the *old* location.")
11650 (defvar org-capture-last-stored-marker)
11651 (defvar org-refile-keep nil
11652 "Non-nil means `org-refile' will copy instead of refile.")
11654 (defun org-copy ()
11655 "Like `org-refile', but copy."
11656 (interactive)
11657 (let ((org-refile-keep t))
11658 (funcall 'org-refile nil nil nil "Copy")))
11660 (defun org-refile (&optional arg default-buffer rfloc msg)
11661 "Move the entry or entries at point to another heading.
11663 The list of target headings is compiled using the information in
11664 `org-refile-targets', which see.
11666 At the target location, the entry is filed as a subitem of the
11667 target heading. Depending on `org-reverse-note-order', the new
11668 subitem will either be the first or the last subitem.
11670 If there is an active region, all entries in that region will be
11671 refiled. However, the region must fulfill the requirement that
11672 the first heading sets the top-level of the moved text.
11674 With a `\\[universal-argument]' ARG, the command will only visit the target \
11675 location
11676 and not actually move anything.
11678 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11679 location where the last
11680 refiling operation has put the subtree.
11682 With a numeric prefix argument of `2', refile to the running clock.
11684 With a numeric prefix argument of `3', emulate `org-refile-keep'
11685 being set to t and copy to the target location, don't move it.
11686 Beware that keeping refiled entries may result in duplicated ID
11687 properties.
11689 RFLOC can be a refile location obtained in a different way.
11691 MSG is a string to replace \"Refile\" in the default prompt with
11692 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11694 See also `org-refile-use-outline-path'.
11696 If you are using target caching (see `org-refile-use-cache'), you
11697 have to clear the target cache in order to find new targets.
11698 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11699 prefix argument (`C-u C-u C-u C-c C-w')."
11700 (interactive "P")
11701 (if (member arg '(0 (64)))
11702 (org-refile-cache-clear)
11703 (let* ((actionmsg (cond (msg msg)
11704 ((equal arg 3) "Refile (and keep)")
11705 (t "Refile")))
11706 (regionp (org-region-active-p))
11707 (region-start (and regionp (region-beginning)))
11708 (region-end (and regionp (region-end)))
11709 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11710 pos it nbuf file level reversed)
11711 (setq last-command nil)
11712 (when regionp
11713 (goto-char region-start)
11714 (or (bolp) (goto-char (point-at-bol)))
11715 (setq region-start (point))
11716 (unless (or (org-kill-is-subtree-p
11717 (buffer-substring region-start region-end))
11718 (prog1 org-refile-active-region-within-subtree
11719 (let ((s (point-at-eol)))
11720 (org-toggle-heading)
11721 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11722 (user-error "The region is not a (sequence of) subtree(s)")))
11723 (if (equal arg '(16))
11724 (org-refile-goto-last-stored)
11725 (when (or
11726 (and (equal arg 2)
11727 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11728 (prog1
11729 (setq it (list (or org-clock-heading "running clock")
11730 (buffer-file-name
11731 (marker-buffer org-clock-hd-marker))
11733 (marker-position org-clock-hd-marker)))
11734 (setq arg nil)))
11735 (setq it
11736 (or rfloc
11737 (let (heading-text)
11738 (save-excursion
11739 (unless (and arg (listp arg))
11740 (org-back-to-heading t)
11741 (setq heading-text
11742 (replace-regexp-in-string
11743 org-bracket-link-regexp
11744 "\\3"
11745 (or (nth 4 (org-heading-components))
11746 ""))))
11747 (org-refile-get-location
11748 (cond ((and arg (listp arg)) "Goto")
11749 (regionp (concat actionmsg " region to"))
11750 (t (concat actionmsg " subtree \""
11751 heading-text "\" to")))
11752 default-buffer
11753 (and (not (equal '(4) arg))
11754 org-refile-allow-creating-parent-nodes)))))))
11755 (setq file (nth 1 it)
11756 pos (nth 3 it))
11757 (when (and (not arg)
11759 (equal (buffer-file-name) file)
11760 (if regionp
11761 (and (>= pos region-start)
11762 (<= pos region-end))
11763 (and (>= pos (point))
11764 (< pos (save-excursion
11765 (org-end-of-subtree t t))))))
11766 (error "Cannot refile to position inside the tree or region"))
11767 (setq nbuf (or (find-buffer-visiting file)
11768 (find-file-noselect file)))
11769 (if (and arg (not (equal arg 3)))
11770 (progn
11771 (pop-to-buffer-same-window nbuf)
11772 (goto-char (cond (pos)
11773 ((org-notes-order-reversed-p) (point-min))
11774 (t (point-max))))
11775 (org-show-context 'org-goto))
11776 (if regionp
11777 (progn
11778 (org-kill-new (buffer-substring region-start region-end))
11779 (org-save-markers-in-region region-start region-end))
11780 (org-copy-subtree 1 nil t))
11781 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11782 (find-file-noselect file)))
11783 (setq reversed (org-notes-order-reversed-p))
11784 (org-with-wide-buffer
11785 (if pos
11786 (progn
11787 (goto-char pos)
11788 (setq level (org-get-valid-level (funcall outline-level) 1))
11789 (goto-char
11790 (if reversed
11791 (or (outline-next-heading) (point-max))
11792 (or (save-excursion (org-get-next-sibling))
11793 (org-end-of-subtree t t)
11794 (point-max)))))
11795 (setq level 1)
11796 (if (not reversed)
11797 (goto-char (point-max))
11798 (goto-char (point-min))
11799 (or (outline-next-heading) (goto-char (point-max)))))
11800 (unless (bolp) (newline))
11801 (org-paste-subtree level nil nil t)
11802 (when org-log-refile
11803 (org-add-log-setup 'refile nil nil org-log-refile)
11804 (unless (eq org-log-refile 'note)
11805 (save-excursion (org-add-log-note))))
11806 (and org-auto-align-tags
11807 (let ((org-loop-over-headlines-in-active-region nil))
11808 (org-set-tags nil t)))
11809 (let ((bookmark-name (plist-get org-bookmark-names-plist
11810 :last-refile)))
11811 (when bookmark-name
11812 (with-demoted-errors
11813 (bookmark-set bookmark-name))))
11814 ;; If we are refiling for capture, make sure that the
11815 ;; last-capture pointers point here
11816 (when (bound-and-true-p org-capture-is-refiling)
11817 (let ((bookmark-name (plist-get org-bookmark-names-plist
11818 :last-capture-marker)))
11819 (when bookmark-name
11820 (with-demoted-errors
11821 (bookmark-set bookmark-name))))
11822 (move-marker org-capture-last-stored-marker (point)))
11823 (when (fboundp 'deactivate-mark) (deactivate-mark))
11824 (run-hooks 'org-after-refile-insert-hook)))
11825 (unless org-refile-keep
11826 (if regionp
11827 (delete-region (point) (+ (point) (- region-end region-start)))
11828 (delete-region
11829 (and (org-back-to-heading t) (point))
11830 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11831 (when (featurep 'org-inlinetask)
11832 (org-inlinetask-remove-END-maybe))
11833 (setq org-markers-to-move nil)
11834 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11836 (defun org-refile-goto-last-stored ()
11837 "Go to the location where the last refile was stored."
11838 (interactive)
11839 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11840 (message "This is the location of the last refile"))
11842 (defun org-refile--get-location (refloc tbl)
11843 "When user refile to REFLOC, find the associated target in TBL.
11844 Also check `org-refile-target-table'."
11845 (car (delq
11847 (mapcar
11848 (lambda (r) (or (assoc r tbl)
11849 (assoc r org-refile-target-table)))
11850 (list (replace-regexp-in-string "/$" "" refloc)
11851 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11853 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11854 "Prompt the user for a refile location, using PROMPT.
11855 PROMPT should not be suffixed with a colon and a space, because
11856 this function appends the default value from
11857 `org-refile-history' automatically, if that is not empty."
11858 (let ((org-refile-targets org-refile-targets)
11859 (org-refile-use-outline-path org-refile-use-outline-path))
11860 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11861 (unless org-refile-target-table
11862 (user-error "No refile targets"))
11863 (let* ((cbuf (current-buffer))
11864 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11865 (cfunc (if (and org-refile-use-outline-path
11866 org-outline-path-complete-in-steps)
11867 #'org-olpath-completing-read
11868 #'completing-read))
11869 (extra (if org-refile-use-outline-path "/" ""))
11870 (cbnex (concat (buffer-name) extra))
11871 (filename (and cfn (expand-file-name cfn)))
11872 (tbl (mapcar
11873 (lambda (x)
11874 (if (and (not (member org-refile-use-outline-path
11875 '(file full-file-path)))
11876 (not (equal filename (nth 1 x))))
11877 (cons (concat (car x) extra " ("
11878 (file-name-nondirectory (nth 1 x)) ")")
11879 (cdr x))
11880 (cons (concat (car x) extra) (cdr x))))
11881 org-refile-target-table))
11882 (completion-ignore-case t)
11883 cdef
11884 (prompt (concat prompt
11885 (or (and (car org-refile-history)
11886 (concat " (default " (car org-refile-history) ")"))
11887 (and (assoc cbnex tbl) (setq cdef cbnex)
11888 (concat " (default " cbnex ")"))) ": "))
11889 pa answ parent-target child parent old-hist)
11890 (setq old-hist org-refile-history)
11891 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11892 nil 'org-refile-history (or cdef (car org-refile-history))))
11893 (if (setq pa (org-refile--get-location answ tbl))
11894 (progn
11895 (org-refile-check-position pa)
11896 (when (or (not org-refile-history)
11897 (not (eq old-hist org-refile-history))
11898 (not (equal (car pa) (car org-refile-history))))
11899 (setq org-refile-history
11900 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11901 org-refile-history
11902 (cdr org-refile-history))))
11903 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11904 (pop org-refile-history)))
11906 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11907 (progn
11908 (setq parent (match-string 1 answ)
11909 child (match-string 2 answ))
11910 (setq parent-target (org-refile--get-location parent tbl))
11911 (when (and parent-target
11912 (or (eq new-nodes t)
11913 (and (eq new-nodes 'confirm)
11914 (y-or-n-p (format "Create new node \"%s\"? "
11915 child)))))
11916 (org-refile-new-child parent-target child)))
11917 (user-error "Invalid target location")))))
11919 (declare-function org-string-nw-p "org-macs" (s))
11920 (defun org-refile-check-position (refile-pointer)
11921 "Check if the refile pointer matches the headline to which it points."
11922 (let* ((file (nth 1 refile-pointer))
11923 (re (nth 2 refile-pointer))
11924 (pos (nth 3 refile-pointer))
11925 buffer)
11926 (if (and (not (markerp pos)) (not file))
11927 (user-error "Please indicate a target file in the refile path")
11928 (when (org-string-nw-p re)
11929 (setq buffer (if (markerp pos)
11930 (marker-buffer pos)
11931 (or (find-buffer-visiting file)
11932 (find-file-noselect file))))
11933 (with-current-buffer buffer
11934 (org-with-wide-buffer
11935 (goto-char pos)
11936 (beginning-of-line 1)
11937 (unless (looking-at-p re)
11938 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11940 (defun org-refile-new-child (parent-target child)
11941 "Use refile target PARENT-TARGET to add new CHILD below it."
11942 (unless parent-target
11943 (error "Cannot find parent for new node"))
11944 (let ((file (nth 1 parent-target))
11945 (pos (nth 3 parent-target))
11946 level)
11947 (with-current-buffer (or (find-buffer-visiting file)
11948 (find-file-noselect file))
11949 (org-with-wide-buffer
11950 (if pos
11951 (goto-char pos)
11952 (goto-char (point-max))
11953 (unless (bolp) (newline)))
11954 (when (looking-at org-outline-regexp)
11955 (setq level (funcall outline-level))
11956 (org-end-of-subtree t t))
11957 (org-back-over-empty-lines)
11958 (insert "\n" (make-string
11959 (if pos (org-get-valid-level level 1) 1) ?*)
11960 " " child "\n")
11961 (beginning-of-line 0)
11962 (list (concat (car parent-target) "/" child) file "" (point))))))
11964 (defun org-olpath-completing-read (prompt collection &rest args)
11965 "Read an outline path like a file name."
11966 (let ((thetable collection))
11967 (apply #'completing-read
11968 prompt
11969 (lambda (string predicate &optional flag)
11970 (cond
11971 ((eq flag nil) (try-completion string thetable))
11972 ((eq flag t)
11973 (let ((l (length string)))
11974 (mapcar (lambda (x)
11975 (let ((r (substring x l))
11976 (f (if (string-match " ([^)]*)$" x)
11977 (match-string 0 x)
11978 "")))
11979 (if (string-match "/" r)
11980 (concat string (substring r 0 (match-end 0)) f)
11981 x)))
11982 (all-completions string thetable predicate))))
11983 ;; Exact match?
11984 ((eq flag 'lambda) (assoc string thetable))))
11985 args)))
11987 ;;;; Dynamic blocks
11989 (defun org-find-dblock (name)
11990 "Find the first dynamic block with name NAME in the buffer.
11991 If not found, stay at current position and return nil."
11992 (let ((case-fold-search t) pos)
11993 (save-excursion
11994 (goto-char (point-min))
11995 (setq pos (and (re-search-forward
11996 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11997 (match-beginning 0))))
11998 (when pos (goto-char pos))
11999 pos))
12001 (defun org-create-dblock (plist)
12002 "Create a dynamic block section, with parameters taken from PLIST.
12003 PLIST must contain a :name entry which is used as the name of the block."
12004 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12005 (end-of-line 1)
12006 (newline))
12007 (let ((col (current-column))
12008 (name (plist-get plist :name)))
12009 (insert "#+BEGIN: " name)
12010 (while plist
12011 (if (eq (car plist) :name)
12012 (setq plist (cddr plist))
12013 (insert " " (prin1-to-string (pop plist)))))
12014 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12015 (beginning-of-line -2)))
12017 (defun org-prepare-dblock ()
12018 "Prepare dynamic block for refresh.
12019 This empties the block, puts the cursor at the insert position and returns
12020 the property list including an extra property :name with the block name."
12021 (unless (looking-at org-dblock-start-re)
12022 (user-error "Not at a dynamic block"))
12023 (let* ((begdel (1+ (match-end 0)))
12024 (name (org-no-properties (match-string 1)))
12025 (params (append (list :name name)
12026 (read (concat "(" (match-string 3) ")")))))
12027 (save-excursion
12028 (beginning-of-line 1)
12029 (skip-chars-forward " \t")
12030 (setq params (plist-put params :indentation-column (current-column))))
12031 (unless (re-search-forward org-dblock-end-re nil t)
12032 (error "Dynamic block not terminated"))
12033 (setq params
12034 (append params
12035 (list :content (buffer-substring
12036 begdel (match-beginning 0)))))
12037 (delete-region begdel (match-beginning 0))
12038 (goto-char begdel)
12039 (open-line 1)
12040 params))
12042 (defun org-map-dblocks (&optional command)
12043 "Apply COMMAND to all dynamic blocks in the current buffer.
12044 If COMMAND is not given, use `org-update-dblock'."
12045 (let ((cmd (or command 'org-update-dblock)))
12046 (save-excursion
12047 (goto-char (point-min))
12048 (while (re-search-forward org-dblock-start-re nil t)
12049 (goto-char (match-beginning 0))
12050 (save-excursion
12051 (condition-case nil
12052 (funcall cmd)
12053 (error (message "Error during update of dynamic block"))))
12054 (unless (re-search-forward org-dblock-end-re nil t)
12055 (error "Dynamic block not terminated"))))))
12057 (defun org-dblock-update (&optional arg)
12058 "User command for updating dynamic blocks.
12059 Update the dynamic block at point. With prefix ARG, update all dynamic
12060 blocks in the buffer."
12061 (interactive "P")
12062 (if arg
12063 (org-update-all-dblocks)
12064 (or (looking-at org-dblock-start-re)
12065 (org-beginning-of-dblock))
12066 (org-update-dblock)))
12068 (defun org-update-dblock ()
12069 "Update the dynamic block at point.
12070 This means to empty the block, parse for parameters and then call
12071 the correct writing function."
12072 (interactive)
12073 (save-excursion
12074 (let* ((win (selected-window))
12075 (pos (point))
12076 (line (org-current-line))
12077 (params (org-prepare-dblock))
12078 (name (plist-get params :name))
12079 (indent (plist-get params :indentation-column))
12080 (cmd (intern (concat "org-dblock-write:" name))))
12081 (message "Updating dynamic block `%s' at line %d..." name line)
12082 (funcall cmd params)
12083 (message "Updating dynamic block `%s' at line %d...done" name line)
12084 (goto-char pos)
12085 (when (and indent (> indent 0))
12086 (setq indent (make-string indent ?\ ))
12087 (save-excursion
12088 (select-window win)
12089 (org-beginning-of-dblock)
12090 (forward-line 1)
12091 (while (not (looking-at org-dblock-end-re))
12092 (insert indent)
12093 (beginning-of-line 2))
12094 (when (looking-at org-dblock-end-re)
12095 (and (looking-at "[ \t]+")
12096 (replace-match ""))
12097 (insert indent)))))))
12099 (defun org-beginning-of-dblock ()
12100 "Find the beginning of the dynamic block at point.
12101 Error if there is no such block at point."
12102 (let ((pos (point))
12103 beg)
12104 (end-of-line 1)
12105 (if (and (re-search-backward org-dblock-start-re nil t)
12106 (setq beg (match-beginning 0))
12107 (re-search-forward org-dblock-end-re nil t)
12108 (> (match-end 0) pos))
12109 (goto-char beg)
12110 (goto-char pos)
12111 (error "Not in a dynamic block"))))
12113 (defun org-update-all-dblocks ()
12114 "Update all dynamic blocks in the buffer.
12115 This function can be used in a hook."
12116 (interactive)
12117 (when (derived-mode-p 'org-mode)
12118 (org-map-dblocks 'org-update-dblock)))
12121 ;;;; Completion
12123 (declare-function org-export-backend-options "ox" (cl-x) t)
12124 (defun org-get-export-keywords ()
12125 "Return a list of all currently understood export keywords.
12126 Export keywords include options, block names, attributes and
12127 keywords relative to each registered export back-end."
12128 (let (keywords)
12129 (dolist (backend
12130 (bound-and-true-p org-export-registered-backends)
12131 (delq nil keywords))
12132 ;; Back-end name (for keywords, like #+LATEX:)
12133 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12134 (dolist (option-entry (org-export-backend-options backend))
12135 ;; Back-end options.
12136 (push (nth 1 option-entry) keywords)))))
12138 (defconst org-options-keywords
12139 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12140 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12141 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12142 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12143 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12145 (defcustom org-structure-template-alist
12146 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12147 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12148 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12149 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12150 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12151 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12152 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12153 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12154 ("L" "#+LaTeX: ")
12155 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12156 ("H" "#+HTML: ")
12157 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12158 ("A" "#+ASCII: ")
12159 ("i" "#+INDEX: ?")
12160 ("I" "#+INCLUDE: %file ?"))
12161 "Structure completion elements.
12162 This is a list of abbreviation keys and values. The value gets inserted
12163 if you type `<' followed by the key and then press the completion key,
12164 usually `TAB'. %file will be replaced by a file name after prompting
12165 for the file using completion. The cursor will be placed at the position
12166 of the `?' in the template.
12167 There are two templates for each key, the first uses the original Org syntax,
12168 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12169 the default when the /org-mtags.el/ module has been loaded. See also the
12170 variable `org-mtags-prefer-muse-templates'."
12171 :group 'org-completion
12172 :type '(repeat
12173 (list
12174 (string :tag "Key")
12175 (string :tag "Template")))
12176 :version "26.1"
12177 :package-version '(Org . "8.3"))
12179 (defun org-try-structure-completion ()
12180 "Try to complete a structure template before point.
12181 This looks for strings like \"<e\" on an otherwise empty line and
12182 expands them."
12183 (let ((l (buffer-substring (point-at-bol) (point)))
12185 (when (and (looking-at "[ \t]*$")
12186 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12187 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12188 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12189 (match-beginning 1)) a)
12190 t)))
12192 (defun org-complete-expand-structure-template (start cell)
12193 "Expand a structure template."
12194 (let ((rpl (nth 1 cell))
12195 (ind ""))
12196 (delete-region start (point))
12197 (when (string-match "\\`[ \t]*#\\+" rpl)
12198 (cond
12199 ((bolp))
12200 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12201 (setq ind (buffer-substring (point-at-bol) (point))))
12202 (t (newline))))
12203 (setq start (point))
12204 (when (string-match "%file" rpl)
12205 (setq rpl (replace-match
12206 (concat
12207 "\""
12208 (save-match-data
12209 (abbreviate-file-name (read-file-name "Include file: ")))
12210 "\"")
12211 t t rpl)))
12212 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12213 (concat "\n" ind)))
12214 (insert rpl)
12215 (when (re-search-backward "\\?" start t) (delete-char 1))))
12217 ;;;; TODO, DEADLINE, Comments
12219 (defun org-toggle-comment ()
12220 "Change the COMMENT state of an entry."
12221 (interactive)
12222 (save-excursion
12223 (org-back-to-heading)
12224 (let ((case-fold-search nil))
12225 (looking-at org-complex-heading-regexp))
12226 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12227 (skip-chars-forward " \t")
12228 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12229 (if (org-in-commented-heading-p t)
12230 (delete-region (point)
12231 (progn (search-forward " " (line-end-position) 'move)
12232 (skip-chars-forward " \t")
12233 (point)))
12234 (insert org-comment-string)
12235 (unless (eolp) (insert " ")))))
12237 (defvar org-last-todo-state-is-todo nil
12238 "This is non-nil when the last TODO state change led to a TODO state.
12239 If the last change removed the TODO tag or switched to DONE, then
12240 this is nil.")
12242 (defvar org-setting-tags nil) ; dynamically skipped
12244 (defvar org-todo-setup-filter-hook nil
12245 "Hook for functions that pre-filter todo specs.
12246 Each function takes a todo spec and returns either nil or the spec
12247 transformed into canonical form." )
12249 (defvar org-todo-get-default-hook nil
12250 "Hook for functions that get a default item for todo.
12251 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12252 nil or a string to be used for the todo mark." )
12254 (defvar org-agenda-headline-snapshot-before-repeat)
12256 (defun org-current-effective-time ()
12257 "Return current time adjusted for `org-extend-today-until' variable."
12258 (let* ((ct (org-current-time))
12259 (dct (decode-time ct))
12260 (ct1
12261 (cond
12262 (org-use-last-clock-out-time-as-effective-time
12263 (or (org-clock-get-last-clock-out-time) ct))
12264 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12265 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12266 (t ct))))
12267 ct1))
12269 (defun org-todo-yesterday (&optional arg)
12270 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12271 (interactive "P")
12272 (if (eq major-mode 'org-agenda-mode)
12273 (apply 'org-agenda-todo-yesterday arg)
12274 (let* ((org-use-effective-time t)
12275 (hour (nth 2 (decode-time (org-current-time))))
12276 (org-extend-today-until (1+ hour)))
12277 (org-todo arg))))
12279 (defvar org-block-entry-blocking ""
12280 "First entry preventing the TODO state change.")
12282 (defun org-cancel-repeater ()
12283 "Cancel a repeater by setting its numeric value to zero."
12284 (interactive)
12285 (save-excursion
12286 (org-back-to-heading t)
12287 (let ((bound1 (point))
12288 (bound0 (save-excursion (outline-next-heading) (point))))
12289 (when (and (re-search-forward
12290 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12291 org-deadline-time-regexp "\\)\\|\\("
12292 org-ts-regexp "\\)")
12293 bound0 t)
12294 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12295 bound1 t))
12296 (replace-match "0" t nil nil 1)))))
12298 (defvar org-state)
12299 (defvar org-blocked-by-checkboxes)
12300 (defun org-todo (&optional arg)
12301 "Change the TODO state of an item.
12303 The state of an item is given by a keyword at the start of the heading,
12304 like
12305 *** TODO Write paper
12306 *** DONE Call mom
12308 The different keywords are specified in the variable `org-todo-keywords'.
12309 By default the available states are \"TODO\" and \"DONE\". So, for this
12310 example: when the item starts with TODO, it is changed to DONE.
12311 When it starts with DONE, the DONE is removed. And when neither TODO nor
12312 DONE are present, add TODO at the beginning of the heading.
12314 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12315 state.
12316 With numeric prefix ARG, switch to that state.
12317 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12318 next set of TODO \
12319 keywords (nextset).
12320 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12321 prefix, circumvent any state blocking.
12322 With a numeric prefix arg of 0, inhibit note taking for the change.
12323 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12325 When called through ELisp, arg is also interpreted in the following way:
12326 `none' -> empty state
12327 \"\" -> switch to empty state
12328 `done' -> switch to DONE
12329 `nextset' -> switch to the next set of keywords
12330 `previousset' -> switch to the previous set of keywords
12331 \"WAITING\" -> switch to the specified keyword, but only if it
12332 really is a member of `org-todo-keywords'."
12333 (interactive "P")
12334 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12335 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12336 'region-start-level 'region))
12337 org-loop-over-headlines-in-active-region)
12338 (org-map-entries
12339 `(org-todo ,arg)
12340 org-loop-over-headlines-in-active-region
12341 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12342 (when (equal arg '(16)) (setq arg 'nextset))
12343 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12344 (let ((org-blocker-hook org-blocker-hook)
12345 commentp
12346 case-fold-search)
12347 (when (equal arg '(64))
12348 (setq arg nil org-blocker-hook nil))
12349 (when (and org-blocker-hook
12350 (or org-inhibit-blocking
12351 (org-entry-get nil "NOBLOCKING")))
12352 (setq org-blocker-hook nil))
12353 (save-excursion
12354 (catch 'exit
12355 (org-back-to-heading t)
12356 (when (org-in-commented-heading-p t)
12357 (org-toggle-comment)
12358 (setq commentp t))
12359 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12360 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12361 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12362 (let* ((match-data (match-data))
12363 (startpos (point-at-bol))
12364 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12365 (org-log-done org-log-done)
12366 (org-log-repeat org-log-repeat)
12367 (org-todo-log-states org-todo-log-states)
12368 (org-inhibit-logging
12369 (if (equal arg 0)
12370 (progn (setq arg nil) 'note) org-inhibit-logging))
12371 (this (match-string 1))
12372 (hl-pos (match-beginning 0))
12373 (head (org-get-todo-sequence-head this))
12374 (ass (assoc head org-todo-kwd-alist))
12375 (interpret (nth 1 ass))
12376 (done-word (nth 3 ass))
12377 (final-done-word (nth 4 ass))
12378 (org-last-state (or this ""))
12379 (completion-ignore-case t)
12380 (member (member this org-todo-keywords-1))
12381 (tail (cdr member))
12382 (org-state (cond
12383 ((and org-todo-key-trigger
12384 (or (and (equal arg '(4))
12385 (eq org-use-fast-todo-selection 'prefix))
12386 (and (not arg) org-use-fast-todo-selection
12387 (not (eq org-use-fast-todo-selection
12388 'prefix)))))
12389 ;; Use fast selection.
12390 (org-fast-todo-selection))
12391 ((and (equal arg '(4))
12392 (or (not org-use-fast-todo-selection)
12393 (not org-todo-key-trigger)))
12394 ;; Read a state with completion.
12395 (completing-read
12396 "State: " (mapcar #'list org-todo-keywords-1)
12397 nil t))
12398 ((eq arg 'right)
12399 (if this
12400 (if tail (car tail) nil)
12401 (car org-todo-keywords-1)))
12402 ((eq arg 'left)
12403 (unless (equal member org-todo-keywords-1)
12404 (if this
12405 (nth (- (length org-todo-keywords-1)
12406 (length tail) 2)
12407 org-todo-keywords-1)
12408 (org-last org-todo-keywords-1))))
12409 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12410 (setq arg nil))) ;hack to fall back to cycling
12411 (arg
12412 ;; User or caller requests a specific state.
12413 (cond
12414 ((equal arg "") nil)
12415 ((eq arg 'none) nil)
12416 ((eq arg 'done) (or done-word (car org-done-keywords)))
12417 ((eq arg 'nextset)
12418 (or (car (cdr (member head org-todo-heads)))
12419 (car org-todo-heads)))
12420 ((eq arg 'previousset)
12421 (let ((org-todo-heads (reverse org-todo-heads)))
12422 (or (car (cdr (member head org-todo-heads)))
12423 (car org-todo-heads))))
12424 ((car (member arg org-todo-keywords-1)))
12425 ((stringp arg)
12426 (user-error "State `%s' not valid in this file" arg))
12427 ((nth (1- (prefix-numeric-value arg))
12428 org-todo-keywords-1))))
12429 ((null member) (or head (car org-todo-keywords-1)))
12430 ((equal this final-done-word) nil) ;-> make empty
12431 ((null tail) nil) ;-> first entry
12432 ((memq interpret '(type priority))
12433 (if (eq this-command last-command)
12434 (car tail)
12435 (if (> (length tail) 0)
12436 (or done-word (car org-done-keywords))
12437 nil)))
12439 (car tail))))
12440 (org-state (or
12441 (run-hook-with-args-until-success
12442 'org-todo-get-default-hook org-state org-last-state)
12443 org-state))
12444 (next (if org-state (concat " " org-state " ") " "))
12445 (change-plist (list :type 'todo-state-change :from this :to org-state
12446 :position startpos))
12447 dolog now-done-p)
12448 (when org-blocker-hook
12449 (let (org-blocked-by-checkboxes block-reason)
12450 (setq org-last-todo-state-is-todo
12451 (not (member this org-done-keywords)))
12452 (unless (save-excursion
12453 (save-match-data
12454 (org-with-wide-buffer
12455 (run-hook-with-args-until-failure
12456 'org-blocker-hook change-plist))))
12457 (setq block-reason (if org-blocked-by-checkboxes
12458 "contained checkboxes"
12459 (format "\"%s\"" org-block-entry-blocking)))
12460 (if (called-interactively-p 'interactive)
12461 (user-error "TODO state change from %s to %s blocked (by %s)"
12462 this org-state block-reason)
12463 ;; Fail silently.
12464 (message "TODO state change from %s to %s blocked (by %s)"
12465 this org-state block-reason)
12466 (throw 'exit nil)))))
12467 (store-match-data match-data)
12468 (replace-match next t t)
12469 (cond ((equal this org-state)
12470 (message "TODO state was already %s" (org-trim next)))
12471 ((not (pos-visible-in-window-p hl-pos))
12472 (message "TODO state changed to %s" (org-trim next))))
12473 (unless head
12474 (setq head (org-get-todo-sequence-head org-state)
12475 ass (assoc head org-todo-kwd-alist)
12476 interpret (nth 1 ass)
12477 done-word (nth 3 ass)
12478 final-done-word (nth 4 ass)))
12479 (when (memq arg '(nextset previousset))
12480 (message "Keyword-Set %d/%d: %s"
12481 (- (length org-todo-sets) -1
12482 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12483 (length org-todo-sets)
12484 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12485 (setq org-last-todo-state-is-todo
12486 (not (member org-state org-done-keywords)))
12487 (setq now-done-p (and (member org-state org-done-keywords)
12488 (not (member this org-done-keywords))))
12489 (and logging (org-local-logging logging))
12490 (when (and (or org-todo-log-states org-log-done)
12491 (not (eq org-inhibit-logging t))
12492 (not (memq arg '(nextset previousset))))
12493 ;; We need to look at recording a time and note.
12494 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12495 (nth 2 (assoc this org-todo-log-states))))
12496 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12497 (setq dolog 'time))
12498 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12499 (and org-state
12500 (member org-state org-not-done-keywords)
12501 (not (member this org-not-done-keywords))))
12502 ;; This is now a todo state and was not one before
12503 ;; If there was a CLOSED time stamp, get rid of it.
12504 (org-add-planning-info nil nil 'closed))
12505 (when (and now-done-p org-log-done)
12506 ;; It is now done, and it was not done before.
12507 (org-add-planning-info 'closed (org-current-effective-time))
12508 (when (and (not dolog) (eq 'note org-log-done))
12509 (org-add-log-setup 'done org-state this 'note)))
12510 (when (and org-state dolog)
12511 ;; This is a non-nil state, and we need to log it.
12512 (org-add-log-setup 'state org-state this dolog)))
12513 ;; Fixup tag positioning.
12514 (org-todo-trigger-tag-changes org-state)
12515 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12516 (when org-provide-todo-statistics
12517 (org-update-parent-todo-statistics))
12518 (run-hooks 'org-after-todo-state-change-hook)
12519 (when (and arg (not (member org-state org-done-keywords)))
12520 (setq head (org-get-todo-sequence-head org-state)))
12521 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12522 ;; Do we need to trigger a repeat?
12523 (when now-done-p
12524 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12525 ;; This is for the agenda, take a snapshot of the headline.
12526 (save-match-data
12527 (setq org-agenda-headline-snapshot-before-repeat
12528 (org-get-heading))))
12529 (org-auto-repeat-maybe org-state))
12530 ;; Fixup cursor location if close to the keyword.
12531 (when (and (outline-on-heading-p)
12532 (not (bolp))
12533 (save-excursion (beginning-of-line 1)
12534 (looking-at org-todo-line-regexp))
12535 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12536 (goto-char (or (match-end 2) (match-end 1)))
12537 (and (looking-at " ") (just-one-space)))
12538 (when org-trigger-hook
12539 (save-excursion
12540 (run-hook-with-args 'org-trigger-hook change-plist)))
12541 (when commentp (org-toggle-comment))))))))
12543 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12544 "Block turning an entry into a TODO, using the hierarchy.
12545 This checks whether the current task should be blocked from state
12546 changes. Such blocking occurs when:
12548 1. The task has children which are not all in a completed state.
12550 2. A task has a parent with the property :ORDERED:, and there
12551 are siblings prior to the current task with incomplete
12552 status.
12554 3. The parent of the task is blocked because it has siblings that should
12555 be done first, or is child of a block grandparent TODO entry."
12557 (if (not org-enforce-todo-dependencies)
12558 t ; if locally turned off don't block
12559 (catch 'dont-block
12560 ;; If this is not a todo state change, or if this entry is already DONE,
12561 ;; do not block
12562 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12563 (member (plist-get change-plist :from)
12564 (cons 'done org-done-keywords))
12565 (member (plist-get change-plist :to)
12566 (cons 'todo org-not-done-keywords))
12567 (not (plist-get change-plist :to)))
12568 (throw 'dont-block t))
12569 ;; If this task has children, and any are undone, it's blocked
12570 (save-excursion
12571 (org-back-to-heading t)
12572 (let ((this-level (funcall outline-level)))
12573 (outline-next-heading)
12574 (let ((child-level (funcall outline-level)))
12575 (while (and (not (eobp))
12576 (> child-level this-level))
12577 ;; this todo has children, check whether they are all
12578 ;; completed
12579 (when (and (not (org-entry-is-done-p))
12580 (org-entry-is-todo-p))
12581 (setq org-block-entry-blocking (org-get-heading))
12582 (throw 'dont-block nil))
12583 (outline-next-heading)
12584 (setq child-level (funcall outline-level))))))
12585 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12586 ;; any previous siblings are undone, it's blocked
12587 (save-excursion
12588 (org-back-to-heading t)
12589 (let* ((pos (point))
12590 (parent-pos (and (org-up-heading-safe) (point)))
12591 (case-fold-search nil))
12592 (unless parent-pos (throw 'dont-block t)) ; no parent
12593 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12594 (forward-line 1)
12595 (re-search-forward org-not-done-heading-regexp pos t))
12596 (setq org-block-entry-blocking (match-string 0))
12597 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12598 ;; Search further up the hierarchy, to see if an ancestor is blocked
12599 (while t
12600 (goto-char parent-pos)
12601 (unless (looking-at org-not-done-heading-regexp)
12602 (throw 'dont-block t)) ; do not block, parent is not a TODO
12603 (setq pos (point))
12604 (setq parent-pos (and (org-up-heading-safe) (point)))
12605 (unless parent-pos (throw 'dont-block t)) ; no parent
12606 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12607 (forward-line 1)
12608 (re-search-forward org-not-done-heading-regexp pos t)
12609 (setq org-block-entry-blocking (org-get-heading)))
12610 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12612 (defcustom org-track-ordered-property-with-tag nil
12613 "Should the ORDERED property also be shown as a tag?
12614 The ORDERED property decides if an entry should require subtasks to be
12615 completed in sequence. Since a property is not very visible, setting
12616 this option means that toggling the ORDERED property with the command
12617 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12618 not relevant for the behavior, but it makes things more visible.
12620 Note that toggling the tag with tags commands will not change the property
12621 and therefore not influence behavior!
12623 This can be t, meaning the tag ORDERED should be used, It can also be a
12624 string to select a different tag for this task."
12625 :group 'org-todo
12626 :type '(choice
12627 (const :tag "No tracking" nil)
12628 (const :tag "Track with ORDERED tag" t)
12629 (string :tag "Use other tag")))
12631 (defun org-toggle-ordered-property ()
12632 "Toggle the ORDERED property of the current entry.
12633 For better visibility, you can track the value of this property with a tag.
12634 See variable `org-track-ordered-property-with-tag'."
12635 (interactive)
12636 (let* ((t1 org-track-ordered-property-with-tag)
12637 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12638 (save-excursion
12639 (org-back-to-heading)
12640 (if (org-entry-get nil "ORDERED")
12641 (progn
12642 (org-delete-property "ORDERED")
12643 (and tag (org-toggle-tag tag 'off))
12644 (message "Subtasks can be completed in arbitrary order"))
12645 (org-entry-put nil "ORDERED" "t")
12646 (and tag (org-toggle-tag tag 'on))
12647 (message "Subtasks must be completed in sequence")))))
12649 (defun org-block-todo-from-checkboxes (change-plist)
12650 "Block turning an entry into a TODO, using checkboxes.
12651 This checks whether the current task should be blocked from state
12652 changes because there are unchecked boxes in this entry."
12653 (if (not org-enforce-todo-checkbox-dependencies)
12654 t ; if locally turned off don't block
12655 (catch 'dont-block
12656 ;; If this is not a todo state change, or if this entry is already DONE,
12657 ;; do not block
12658 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12659 (member (plist-get change-plist :from)
12660 (cons 'done org-done-keywords))
12661 (member (plist-get change-plist :to)
12662 (cons 'todo org-not-done-keywords))
12663 (not (plist-get change-plist :to)))
12664 (throw 'dont-block t))
12665 ;; If this task has checkboxes that are not checked, it's blocked
12666 (save-excursion
12667 (org-back-to-heading t)
12668 (let ((beg (point)) end)
12669 (outline-next-heading)
12670 (setq end (point))
12671 (goto-char beg)
12672 (when (org-list-search-forward
12673 (concat (org-item-beginning-re)
12674 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12675 "\\[[- ]\\]")
12676 end t)
12677 (when (boundp 'org-blocked-by-checkboxes)
12678 (setq org-blocked-by-checkboxes t))
12679 (throw 'dont-block nil))))
12680 t))) ; do not block
12682 (defun org-entry-blocked-p ()
12683 "Non-nil if entry at point is blocked."
12684 (and (not (org-entry-get nil "NOBLOCKING"))
12685 (member (org-entry-get nil "TODO") org-not-done-keywords)
12686 (not (run-hook-with-args-until-failure
12687 'org-blocker-hook
12688 (list :type 'todo-state-change
12689 :position (point)
12690 :from 'todo
12691 :to 'done)))))
12693 (defun org-update-statistics-cookies (all)
12694 "Update the statistics cookie, either from TODO or from checkboxes.
12695 This should be called with the cursor in a line with a statistics
12696 cookie. When called with a \\[universal-argument] prefix, update
12697 all statistics cookies in the buffer."
12698 (interactive "P")
12699 (if all
12700 (progn
12701 (org-update-checkbox-count 'all)
12702 (org-map-entries 'org-update-parent-todo-statistics))
12703 (if (not (org-at-heading-p))
12704 (org-update-checkbox-count)
12705 (let ((pos (point-marker))
12706 end l1 l2)
12707 (ignore-errors (org-back-to-heading t))
12708 (if (not (org-at-heading-p))
12709 (org-update-checkbox-count)
12710 (setq l1 (org-outline-level))
12711 (setq end (save-excursion
12712 (outline-next-heading)
12713 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12714 (point)))
12715 (if (and (save-excursion
12716 (re-search-forward
12717 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12718 (not (save-excursion (re-search-forward
12719 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12720 (org-update-checkbox-count)
12721 (if (and l2 (> l2 l1))
12722 (progn
12723 (goto-char end)
12724 (org-update-parent-todo-statistics))
12725 (goto-char pos)
12726 (beginning-of-line 1)
12727 (while (re-search-forward
12728 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12729 (point-at-eol) t)
12730 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12731 (goto-char pos)
12732 (move-marker pos nil)))))
12734 (defvar org-entry-property-inherited-from) ;; defined below
12735 (defun org-update-parent-todo-statistics ()
12736 "Update any statistics cookie in the parent of the current headline.
12737 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12738 the entire subtree and this will travel up the hierarchy and update
12739 statistics everywhere."
12740 (let* ((prop (save-excursion (org-up-heading-safe)
12741 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12742 (recursive (or (not org-hierarchical-todo-statistics)
12743 (and prop (string-match "\\<recursive\\>" prop))))
12744 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12746 (first t)
12747 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12748 level ltoggle l1 new ndel
12749 (cnt-all 0) (cnt-done 0) is-percent kwd
12750 checkbox-beg cookie-present)
12751 (catch 'exit
12752 (save-excursion
12753 (beginning-of-line 1)
12754 (setq ltoggle (funcall outline-level))
12755 ;; Three situations are to consider:
12757 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12758 ;; to the top-level ancestor on the headline;
12760 ;; 2. If parent has "recursive" property, repeat up to the
12761 ;; headline setting that property, taking inheritance into
12762 ;; account;
12764 ;; 3. Else, move up to direct parent and proceed only once.
12765 (while (and (setq level (org-up-heading-safe))
12766 (or recursive first)
12767 (>= (point) lim))
12768 (setq first nil cookie-present nil)
12769 (unless (and level
12770 (not (string-match
12771 "\\<checkbox\\>"
12772 (downcase (or (org-entry-get nil "COOKIE_DATA")
12773 "")))))
12774 (throw 'exit nil))
12775 (while (re-search-forward box-re (point-at-eol) t)
12776 (setq cnt-all 0 cnt-done 0 cookie-present t)
12777 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12778 (save-match-data
12779 (unless (outline-next-heading) (throw 'exit nil))
12780 (while (and (looking-at org-complex-heading-regexp)
12781 (> (setq l1 (length (match-string 1))) level))
12782 (setq kwd (and (or recursive (= l1 ltoggle))
12783 (match-string 2)))
12784 (if (or (eq org-provide-todo-statistics 'all-headlines)
12785 (and (eq org-provide-todo-statistics t)
12786 (or (member kwd org-done-keywords)))
12787 (and (listp org-provide-todo-statistics)
12788 (stringp (car org-provide-todo-statistics))
12789 (or (member kwd org-provide-todo-statistics)
12790 (member kwd org-done-keywords)))
12791 (and (listp org-provide-todo-statistics)
12792 (listp (car org-provide-todo-statistics))
12793 (or (member kwd (car org-provide-todo-statistics))
12794 (and (member kwd org-done-keywords)
12795 (member kwd (cadr org-provide-todo-statistics))))))
12796 (setq cnt-all (1+ cnt-all))
12797 (and (eq org-provide-todo-statistics t)
12799 (setq cnt-all (1+ cnt-all))))
12800 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12801 (member kwd org-done-keywords))
12802 (and (listp org-provide-todo-statistics)
12803 (listp (car org-provide-todo-statistics))
12804 (member kwd org-done-keywords)
12805 (member kwd (cadr org-provide-todo-statistics)))
12806 (and (listp org-provide-todo-statistics)
12807 (stringp (car org-provide-todo-statistics))
12808 (member kwd org-done-keywords)))
12809 (setq cnt-done (1+ cnt-done)))
12810 (outline-next-heading)))
12811 (setq new
12812 (if is-percent
12813 (format "[%d%%]" (floor (* 100.0 cnt-done)
12814 (max 1 cnt-all)))
12815 (format "[%d/%d]" cnt-done cnt-all))
12816 ndel (- (match-end 0) checkbox-beg))
12817 (goto-char checkbox-beg)
12818 (insert new)
12819 (delete-region (point) (+ (point) ndel))
12820 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12821 (when cookie-present
12822 (run-hook-with-args 'org-after-todo-statistics-hook
12823 cnt-done (- cnt-all cnt-done))))))
12824 (run-hooks 'org-todo-statistics-hook)))
12826 (defvar org-after-todo-statistics-hook nil
12827 "Hook that is called after a TODO statistics cookie has been updated.
12828 Each function is called with two arguments: the number of not-done entries
12829 and the number of done entries.
12831 For example, the following function, when added to this hook, will switch
12832 an entry to DONE when all children are done, and back to TODO when new
12833 entries are set to a TODO status. Note that this hook is only called
12834 when there is a statistics cookie in the headline!
12836 (defun org-summary-todo (n-done n-not-done)
12837 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12838 (let (org-log-done org-log-states) ; turn off logging
12839 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12842 (defvar org-todo-statistics-hook nil
12843 "Hook that is run whenever Org thinks TODO statistics should be updated.
12844 This hook runs even if there is no statistics cookie present, in which case
12845 `org-after-todo-statistics-hook' would not run.")
12847 (defun org-todo-trigger-tag-changes (state)
12848 "Apply the changes defined in `org-todo-state-tags-triggers'."
12849 (let ((l org-todo-state-tags-triggers)
12850 changes)
12851 (when (or (not state) (equal state ""))
12852 (setq changes (append changes (cdr (assoc "" l)))))
12853 (when (and (stringp state) (> (length state) 0))
12854 (setq changes (append changes (cdr (assoc state l)))))
12855 (when (member state org-not-done-keywords)
12856 (setq changes (append changes (cdr (assq 'todo l)))))
12857 (when (member state org-done-keywords)
12858 (setq changes (append changes (cdr (assq 'done l)))))
12859 (dolist (c changes)
12860 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12862 (defun org-local-logging (value)
12863 "Get logging settings from a property VALUE."
12864 ;; Directly set the variables, they are already local.
12865 (setq org-log-done nil
12866 org-log-repeat nil
12867 org-todo-log-states nil)
12868 (dolist (w (split-string value))
12869 (let (a)
12870 (cond
12871 ((setq a (assoc w org-startup-options))
12872 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12873 (set (nth 1 a) (nth 2 a))))
12874 ((setq a (org-extract-log-state-settings w))
12875 (and (member (car a) org-todo-keywords-1)
12876 (push a org-todo-log-states)))))))
12878 (defun org-get-todo-sequence-head (kwd)
12879 "Return the head of the TODO sequence to which KWD belongs.
12880 If KWD is not set, check if there is a text property remembering the
12881 right sequence."
12882 (let (p)
12883 (cond
12884 ((not kwd)
12885 (or (get-text-property (point-at-bol) 'org-todo-head)
12886 (progn
12887 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12888 nil (point-at-eol)))
12889 (get-text-property p 'org-todo-head))))
12890 ((not (member kwd org-todo-keywords-1))
12891 (car org-todo-keywords-1))
12892 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12894 (defun org-fast-todo-selection ()
12895 "Fast TODO keyword selection with single keys.
12896 Returns the new TODO keyword, or nil if no state change should occur."
12897 (let* ((fulltable org-todo-key-alist)
12898 (done-keywords org-done-keywords) ;; needed for the faces.
12899 (maxlen (apply 'max (mapcar
12900 (lambda (x)
12901 (if (stringp (car x)) (string-width (car x)) 0))
12902 fulltable)))
12903 (expert nil)
12904 (fwidth (+ maxlen 3 1 3))
12905 (ncol (/ (- (window-width) 4) fwidth))
12906 tg cnt e c tbl
12907 groups ingroup)
12908 (save-excursion
12909 (save-window-excursion
12910 (if expert
12911 (set-buffer (get-buffer-create " *Org todo*"))
12912 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12913 (erase-buffer)
12914 (setq-local org-done-keywords done-keywords)
12915 (setq tbl fulltable cnt 0)
12916 (while (setq e (pop tbl))
12917 (cond
12918 ((equal e '(:startgroup))
12919 (push '() groups) (setq ingroup t)
12920 (unless (= cnt 0)
12921 (setq cnt 0)
12922 (insert "\n"))
12923 (insert "{ "))
12924 ((equal e '(:endgroup))
12925 (setq ingroup nil cnt 0)
12926 (insert "}\n"))
12927 ((equal e '(:newline))
12928 (unless (= cnt 0)
12929 (setq cnt 0)
12930 (insert "\n")
12931 (setq e (car tbl))
12932 (while (equal (car tbl) '(:newline))
12933 (insert "\n")
12934 (setq tbl (cdr tbl)))))
12936 (setq tg (car e) c (cdr e))
12937 (when ingroup (push tg (car groups)))
12938 (setq tg (org-add-props tg nil 'face
12939 (org-get-todo-face tg)))
12940 (when (and (= cnt 0) (not ingroup)) (insert " "))
12941 (insert "[" c "] " tg (make-string
12942 (- fwidth 4 (length tg)) ?\ ))
12943 (when (= (setq cnt (1+ cnt)) ncol)
12944 (insert "\n")
12945 (when ingroup (insert " "))
12946 (setq cnt 0)))))
12947 (insert "\n")
12948 (goto-char (point-min))
12949 (unless expert (org-fit-window-to-buffer))
12950 (message "[a-z..]:Set [SPC]:clear")
12951 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12952 (cond
12953 ((or (= c ?\C-g)
12954 (and (= c ?q) (not (rassoc c fulltable))))
12955 (setq quit-flag t))
12956 ((= c ?\ ) nil)
12957 ((setq e (rassoc c fulltable) tg (car e))
12959 (t (setq quit-flag t)))))))
12961 (defun org-entry-is-todo-p ()
12962 (member (org-get-todo-state) org-not-done-keywords))
12964 (defun org-entry-is-done-p ()
12965 (member (org-get-todo-state) org-done-keywords))
12967 (defun org-get-todo-state ()
12968 "Return the TODO keyword of the current subtree."
12969 (save-excursion
12970 (org-back-to-heading t)
12971 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12972 (match-end 2)
12973 (match-string 2))))
12975 (defun org-at-date-range-p (&optional inactive-ok)
12976 "Non-nil if point is inside a date range.
12978 When optional argument INACTIVE-OK is non-nil, also consider
12979 inactive time ranges.
12981 When this function returns a non-nil value, match data is set
12982 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12983 on INACTIVE-OK."
12984 (interactive)
12985 (save-excursion
12986 (catch 'exit
12987 (let ((pos (point)))
12988 (skip-chars-backward "^[<\r\n")
12989 (skip-chars-backward "<[")
12990 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12991 (>= (match-end 0) pos)
12992 (throw 'exit t))
12993 (skip-chars-backward "^<[\r\n")
12994 (skip-chars-backward "<[")
12995 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12996 (>= (match-end 0) pos)
12997 (throw 'exit t)))
12998 nil)))
13000 (defun org-get-repeat (&optional timestamp)
13001 "Check if there is a time-stamp with repeater in this entry.
13003 Return the repeater, as a string, or nil. Also return nil when
13004 this function is called before first heading.
13006 When optional argument TIMESTAMP is a string, extract the
13007 repeater from there instead."
13008 (save-match-data
13009 (cond (timestamp
13010 (and (string-match org-repeat-re timestamp)
13011 (match-string-no-properties 1 timestamp)))
13012 ((org-before-first-heading-p) nil)
13014 (save-excursion
13015 (org-back-to-heading t)
13016 (let ((end (org-entry-end-position)))
13017 (catch :repeat
13018 (while (re-search-forward org-repeat-re end t)
13019 (when (save-match-data (org-at-timestamp-p 'agenda))
13020 (throw :repeat (match-string-no-properties 1)))))))))))
13022 (defvar org-last-changed-timestamp)
13023 (defvar org-last-inserted-timestamp)
13024 (defvar org-log-post-message)
13025 (defvar org-log-note-purpose)
13026 (defvar org-log-note-how nil)
13027 (defvar org-log-note-extra)
13028 (defun org-auto-repeat-maybe (done-word)
13029 "Check if the current headline contains a repeated time-stamp.
13031 If yes, set TODO state back to what it was and change the base date
13032 of repeating deadline/scheduled time stamps to new date.
13034 This function is run automatically after each state change to a DONE state."
13035 (let* ((repeat (org-get-repeat))
13036 (aa (assoc org-last-state org-todo-kwd-alist))
13037 (interpret (nth 1 aa))
13038 (head (nth 2 aa))
13039 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13040 (msg "Entry repeats: ")
13041 (org-log-done nil)
13042 (org-todo-log-states nil)
13043 (end (copy-marker (org-entry-end-position))))
13044 (unwind-protect
13045 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13046 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13047 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13048 org-todo-repeat-to-state)))
13049 (org-todo (cond
13050 ((and to-state (member to-state org-todo-keywords-1))
13051 to-state)
13052 ((eq interpret 'type) org-last-state)
13053 (head)
13054 (t 'none))))
13055 (org-back-to-heading t)
13056 (org-add-planning-info nil nil 'closed)
13057 ;; When `org-log-repeat' is non-nil or entry contains
13058 ;; a clock, set LAST_REPEAT property.
13059 (when (or org-log-repeat
13060 (catch :clock
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]*\\(\\S-+\\)" value start)
16079 (setq start (match-end 0))
16080 (let ((p (match-string-no-properties 1 value)))
16081 (unless (member-ignore-case p org-special-properties)
16082 (push p props))))))))))
16083 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16085 (defun org-property-values (key)
16086 "List all non-nil values of property KEY in current buffer."
16087 (org-with-wide-buffer
16088 (goto-char (point-min))
16089 (let ((case-fold-search t)
16090 (re (org-re-property key))
16091 values)
16092 (while (re-search-forward re nil t)
16093 (push (org-entry-get (point) key) values))
16094 (delete-dups values))))
16096 (defun org-insert-property-drawer ()
16097 "Insert a property drawer into the current entry."
16098 (org-with-wide-buffer
16099 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16100 (org-back-to-heading t)
16101 (org-with-limited-levels (org-back-to-heading t)))
16102 (forward-line)
16103 (when (looking-at-p org-planning-line-re) (forward-line))
16104 (unless (looking-at-p org-property-drawer-re)
16105 ;; Make sure we start editing a line from current entry, not from
16106 ;; next one. It prevents extending text properties or overlays
16107 ;; belonging to the latter.
16108 (when (bolp) (backward-char))
16109 (let ((begin (1+ (point)))
16110 (inhibit-read-only t))
16111 (insert "\n:PROPERTIES:\n:END:")
16112 (when (eobp) (insert "\n"))
16113 (org-indent-region begin (point))))))
16115 (defun org-insert-drawer (&optional arg drawer)
16116 "Insert a drawer at point.
16118 When optional argument ARG is non-nil, insert a property drawer.
16120 Optional argument DRAWER, when non-nil, is a string representing
16121 drawer's name. Otherwise, the user is prompted for a name.
16123 If a region is active, insert the drawer around that region
16124 instead.
16126 Point is left between drawer's boundaries."
16127 (interactive "P")
16128 (let* ((drawer (if arg "PROPERTIES"
16129 (or drawer (read-from-minibuffer "Drawer: ")))))
16130 (cond
16131 ;; With C-u, fall back on `org-insert-property-drawer'
16132 (arg (org-insert-property-drawer))
16133 ;; Check validity of suggested drawer's name.
16134 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16135 (user-error "Invalid drawer name"))
16136 ;; With an active region, insert a drawer at point.
16137 ((not (org-region-active-p))
16138 (progn
16139 (unless (bolp) (insert "\n"))
16140 (insert (format ":%s:\n\n:END:\n" drawer))
16141 (forward-line -2)))
16142 ;; Otherwise, insert the drawer at point
16144 (let ((rbeg (region-beginning))
16145 (rend (copy-marker (region-end))))
16146 (unwind-protect
16147 (progn
16148 (goto-char rbeg)
16149 (beginning-of-line)
16150 (when (save-excursion
16151 (re-search-forward org-outline-regexp-bol rend t))
16152 (user-error "Drawers cannot contain headlines"))
16153 ;; Position point at the beginning of the first
16154 ;; non-blank line in region. Insert drawer's opening
16155 ;; there, then indent it.
16156 (org-skip-whitespace)
16157 (beginning-of-line)
16158 (insert ":" drawer ":\n")
16159 (forward-line -1)
16160 (indent-for-tab-command)
16161 ;; Move point to the beginning of the first blank line
16162 ;; after the last non-blank line in region. Insert
16163 ;; drawer's closing, then indent it.
16164 (goto-char rend)
16165 (skip-chars-backward " \r\t\n")
16166 (insert "\n:END:")
16167 (deactivate-mark t)
16168 (indent-for-tab-command)
16169 (unless (eolp) (insert "\n")))
16170 ;; Clear marker, whatever the outcome of insertion is.
16171 (set-marker rend nil)))))))
16173 (defvar org-property-set-functions-alist nil
16174 "Property set function alist.
16175 Each entry should have the following format:
16177 (PROPERTY . READ-FUNCTION)
16179 The read function will be called with the same argument as
16180 `org-completing-read'.")
16182 (defun org-set-property-function (property)
16183 "Get the function that should be used to set PROPERTY.
16184 This is computed according to `org-property-set-functions-alist'."
16185 (or (cdr (assoc property org-property-set-functions-alist))
16186 'org-completing-read))
16188 (defun org-read-property-value (property)
16189 "Read PROPERTY value from user."
16190 (let* ((completion-ignore-case t)
16191 (allowed (org-property-get-allowed-values nil property 'table))
16192 (cur (org-entry-get nil property))
16193 (prompt (concat property " value"
16194 (if (and cur (string-match "\\S-" cur))
16195 (concat " [" cur "]") "") ": "))
16196 (set-function (org-set-property-function property))
16197 (val (if allowed
16198 (funcall set-function prompt allowed nil
16199 (not (get-text-property 0 'org-unrestricted
16200 (caar allowed))))
16201 (funcall set-function prompt
16202 (mapcar 'list (org-property-values property))
16203 nil nil "" nil cur))))
16204 (org-trim val)))
16206 (defvar org-last-set-property nil)
16207 (defvar org-last-set-property-value nil)
16208 (defun org-read-property-name ()
16209 "Read a property name."
16210 (let ((completion-ignore-case t)
16211 (default-prop (or (and (org-at-property-p)
16212 (match-string-no-properties 2))
16213 org-last-set-property)))
16214 (org-completing-read
16215 (concat "Property"
16216 (if default-prop (concat " [" default-prop "]") "")
16217 ": ")
16218 (mapcar #'list (org-buffer-property-keys nil t t))
16219 nil nil nil nil default-prop)))
16221 (defun org-set-property-and-value (use-last)
16222 "Allow to set [PROPERTY]: [value] direction from prompt.
16223 When use-default, don't even ask, just use the last
16224 \"[PROPERTY]: [value]\" string from the history."
16225 (interactive "P")
16226 (let* ((completion-ignore-case t)
16227 (pv (or (and use-last org-last-set-property-value)
16228 (org-completing-read
16229 "Enter a \"[Property]: [value]\" pair: "
16230 nil nil nil nil nil
16231 org-last-set-property-value)))
16232 prop val)
16233 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16234 (setq prop (match-string 1 pv)
16235 val (match-string 2 pv))
16236 (org-set-property prop val))))
16238 (defun org-set-property (property value)
16239 "In the current entry, set PROPERTY to VALUE.
16241 When called interactively, this will prompt for a property name, offering
16242 completion on existing and default properties. And then it will prompt
16243 for a value, offering completion either on allowed values (via an inherited
16244 xxx_ALL property) or on existing values in other instances of this property
16245 in the current file.
16247 Throw an error when trying to set a property with an invalid name."
16248 (interactive (list nil nil))
16249 (let ((property (or property (org-read-property-name))))
16250 ;; `org-entry-put' also makes the following check, but this one
16251 ;; avoids polluting `org-last-set-property' and
16252 ;; `org-last-set-property-value' needlessly.
16253 (unless (org--valid-property-p property)
16254 (user-error "Invalid property name: \"%s\"" property))
16255 (let ((value (or value (org-read-property-value property)))
16256 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16257 (setq org-last-set-property property)
16258 (setq org-last-set-property-value (concat property ": " value))
16259 ;; Possibly postprocess the inserted value:
16260 (when fn (setq value (funcall fn value)))
16261 (unless (equal (org-entry-get nil property) value)
16262 (org-entry-put nil property value)))))
16264 (defun org-find-property (property &optional value)
16265 "Find first entry in buffer that sets PROPERTY.
16267 When optional argument VALUE is non-nil, only consider an entry
16268 if it contains PROPERTY set to this value. If PROPERTY should be
16269 explicitly set to nil, use string \"nil\" for VALUE.
16271 Return position where the entry begins, or nil if there is no
16272 such entry. If narrowing is in effect, only search the visible
16273 part of the buffer."
16274 (save-excursion
16275 (goto-char (point-min))
16276 (let ((case-fold-search t)
16277 (re (org-re-property property nil (not value) value)))
16278 (catch 'exit
16279 (while (re-search-forward re nil t)
16280 (when (if value (org-at-property-p)
16281 (org-entry-get (point) property nil t))
16282 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16284 (defun org-delete-property (property)
16285 "In the current entry, delete PROPERTY."
16286 (interactive
16287 (let* ((completion-ignore-case t)
16288 (cat (org-entry-get (point) "CATEGORY"))
16289 (props0 (org-entry-properties nil 'standard))
16290 (props (if cat props0
16291 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16292 (prop (if (< 1 (length props))
16293 (completing-read "Property: " props nil t)
16294 (caar props))))
16295 (list prop)))
16296 (if (not property)
16297 (message "No property to delete in this entry")
16298 (org-entry-delete nil property)
16299 (message "Property \"%s\" deleted" property)))
16301 (defun org-delete-property-globally (property)
16302 "Remove PROPERTY globally, from all entries.
16303 This function ignores narrowing, if any."
16304 (interactive
16305 (let* ((completion-ignore-case t)
16306 (prop (completing-read
16307 "Globally remove property: "
16308 (mapcar #'list (org-buffer-property-keys)))))
16309 (list prop)))
16310 (org-with-wide-buffer
16311 (goto-char (point-min))
16312 (let ((count 0)
16313 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16314 (while (re-search-forward re nil t)
16315 (when (org-entry-delete (point) property) (cl-incf count)))
16316 (message "Property \"%s\" removed from %d entries" property count))))
16318 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16320 (defun org-compute-property-at-point ()
16321 "Compute the property at point.
16322 This looks for an enclosing column format, extracts the operator and
16323 then applies it to the property in the column format's scope."
16324 (interactive)
16325 (unless (org-at-property-p)
16326 (user-error "Not at a property"))
16327 (let ((prop (match-string-no-properties 2)))
16328 (org-columns-get-format-and-top-level)
16329 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16330 (user-error "No operator defined for property %s" prop))
16331 (org-columns-compute prop)))
16333 (defvar org-property-allowed-value-functions nil
16334 "Hook for functions supplying allowed values for a specific property.
16335 The functions must take a single argument, the name of the property, and
16336 return a flat list of allowed values. If \":ETC\" is one of
16337 the values, this means that these values are intended as defaults for
16338 completion, but that other values should be allowed too.
16339 The functions must return nil if they are not responsible for this
16340 property.")
16342 (defun org-property-get-allowed-values (pom property &optional table)
16343 "Get allowed values for the property PROPERTY.
16344 When TABLE is non-nil, return an alist that can directly be used for
16345 completion."
16346 (let (vals)
16347 (cond
16348 ((equal property "TODO")
16349 (setq vals (org-with-point-at pom
16350 (append org-todo-keywords-1 '("")))))
16351 ((equal property "PRIORITY")
16352 (let ((n org-lowest-priority))
16353 (while (>= n org-highest-priority)
16354 (push (char-to-string n) vals)
16355 (setq n (1- n)))))
16356 ((equal property "CATEGORY"))
16357 ((member property org-special-properties))
16358 ((setq vals (run-hook-with-args-until-success
16359 'org-property-allowed-value-functions property)))
16361 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16362 (when (and vals (string-match "\\S-" vals))
16363 (setq vals (car (read-from-string (concat "(" vals ")"))))
16364 (setq vals (mapcar (lambda (x)
16365 (cond ((stringp x) x)
16366 ((numberp x) (number-to-string x))
16367 ((symbolp x) (symbol-name x))
16368 (t "???")))
16369 vals)))))
16370 (when (member ":ETC" vals)
16371 (setq vals (remove ":ETC" vals))
16372 (org-add-props (car vals) '(org-unrestricted t)))
16373 (if table (mapcar 'list vals) vals)))
16375 (defun org-property-previous-allowed-value (&optional _previous)
16376 "Switch to the next allowed value for this property."
16377 (interactive)
16378 (org-property-next-allowed-value t))
16380 (defun org-property-next-allowed-value (&optional previous)
16381 "Switch to the next allowed value for this property."
16382 (interactive)
16383 (unless (org-at-property-p)
16384 (user-error "Not at a property"))
16385 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16386 (key (match-string 2))
16387 (value (match-string 3))
16388 (allowed (or (org-property-get-allowed-values (point) key)
16389 (and (member value '("[ ]" "[-]" "[X]"))
16390 '("[ ]" "[X]"))))
16391 (heading (save-match-data (nth 4 (org-heading-components))))
16392 nval)
16393 (unless allowed
16394 (user-error "Allowed values for this property have not been defined"))
16395 (when previous (setq allowed (reverse allowed)))
16396 (when (member value allowed)
16397 (setq nval (car (cdr (member value allowed)))))
16398 (setq nval (or nval (car allowed)))
16399 (when (equal nval value)
16400 (user-error "Only one allowed value for this property"))
16401 (org-at-property-p)
16402 (replace-match (concat " :" key ": " nval) t t)
16403 (org-indent-line)
16404 (beginning-of-line 1)
16405 (skip-chars-forward " \t")
16406 (when (equal prop org-effort-property)
16407 (org-refresh-property
16408 '((effort . identity)
16409 (effort-minutes . org-duration-to-minutes))
16410 nval)
16411 (when (string= org-clock-current-task heading)
16412 (setq org-clock-effort nval)
16413 (org-clock-update-mode-line)))
16414 (run-hook-with-args 'org-property-changed-functions key nval)))
16416 (defun org-find-olp (path &optional this-buffer)
16417 "Return a marker pointing to the entry at outline path OLP.
16418 If anything goes wrong, throw an error.
16419 You can wrap this call to catch the error like this:
16421 (condition-case msg
16422 (org-mobile-locate-entry (match-string 4))
16423 (error (nth 1 msg)))
16425 The return value will then be either a string with the error message,
16426 or a marker if everything is OK.
16428 If THIS-BUFFER is set, the outline path does not contain a file,
16429 only headings."
16430 (let* ((file (if this-buffer buffer-file-name (pop path)))
16431 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16432 (level 1)
16433 (lmin 1)
16434 (lmax 1)
16435 end found flevel)
16436 (unless buffer (error "File not found :%s" file))
16437 (with-current-buffer buffer
16438 (unless (derived-mode-p 'org-mode)
16439 (error "Buffer %s needs to be in Org mode" buffer))
16440 (org-with-wide-buffer
16441 (goto-char (point-min))
16442 (dolist (heading path)
16443 (let ((re (format org-complex-heading-regexp-format
16444 (regexp-quote heading)))
16445 (cnt 0))
16446 (while (re-search-forward re end t)
16447 (setq level (- (match-end 1) (match-beginning 1)))
16448 (when (and (>= level lmin) (<= level lmax))
16449 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16450 (when (= cnt 0)
16451 (error "Heading not found on level %d: %s" lmax heading))
16452 (when (> cnt 1)
16453 (error "Heading not unique on level %d: %s" lmax heading))
16454 (goto-char found)
16455 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16456 (setq end (save-excursion (org-end-of-subtree t t)))))
16457 (when (org-at-heading-p)
16458 (point-marker))))))
16460 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16461 "Find node HEADING in BUFFER.
16462 Return a marker to the heading if it was found, or nil if not.
16463 If POS-ONLY is set, return just the position instead of a marker.
16465 The heading text must match exact, but it may have a TODO keyword,
16466 a priority cookie and tags in the standard locations."
16467 (with-current-buffer (or buffer (current-buffer))
16468 (org-with-wide-buffer
16469 (goto-char (point-min))
16470 (let (case-fold-search)
16471 (when (re-search-forward
16472 (format org-complex-heading-regexp-format
16473 (regexp-quote heading)) nil t)
16474 (if pos-only
16475 (match-beginning 0)
16476 (move-marker (make-marker) (match-beginning 0))))))))
16478 (defun org-find-exact-heading-in-directory (heading &optional dir)
16479 "Find Org node headline HEADING in all .org files in directory DIR.
16480 When the target headline is found, return a marker to this location."
16481 (let ((files (directory-files (or dir default-directory)
16482 t "\\`[^.#].*\\.org\\'"))
16483 visiting m buffer)
16484 (catch 'found
16485 (dolist (file files)
16486 (message "trying %s" file)
16487 (setq visiting (org-find-base-buffer-visiting file))
16488 (setq buffer (or visiting (find-file-noselect file)))
16489 (setq m (org-find-exact-headline-in-buffer
16490 heading buffer))
16491 (when (and (not m) (not visiting)) (kill-buffer buffer))
16492 (and m (throw 'found m))))))
16494 (defun org-find-entry-with-id (ident)
16495 "Locate the entry that contains the ID property with exact value IDENT.
16496 IDENT can be a string, a symbol or a number, this function will search for
16497 the string representation of it.
16498 Return the position where this entry starts, or nil if there is no such entry."
16499 (interactive "sID: ")
16500 (let ((id (cond
16501 ((stringp ident) ident)
16502 ((symbolp ident) (symbol-name ident))
16503 ((numberp ident) (number-to-string ident))
16504 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16505 (org-with-wide-buffer (org-find-property "ID" id))))
16507 ;;;; Timestamps
16509 (defvar org-last-changed-timestamp nil)
16510 (defvar org-last-inserted-timestamp nil
16511 "The last time stamp inserted with `org-insert-time-stamp'.")
16513 (defun org-time-stamp (arg &optional inactive)
16514 "Prompt for a date/time and insert a time stamp.
16516 If the user specifies a time like HH:MM or if this command is
16517 called with at least one prefix argument, the time stamp contains
16518 the date and the time. Otherwise, only the date is included.
16520 All parts of a date not specified by the user are filled in from
16521 the timestamp at point, if any, or the current date/time
16522 otherwise.
16524 If there is already a timestamp at the cursor, it is replaced.
16526 With two universal prefix arguments, insert an active timestamp
16527 with the current time without prompting the user.
16529 When called from lisp, the timestamp is inactive if INACTIVE is
16530 non-nil."
16531 (interactive "P")
16532 (let* ((ts (cond
16533 ((org-at-date-range-p t)
16534 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16535 ((org-at-timestamp-p 'lax) (match-string 0))))
16536 ;; Default time is either the timestamp at point or today.
16537 ;; When entering a range, only the range start is considered.
16538 (default-time (if (not ts) (current-time)
16539 (apply #'encode-time (org-parse-time-string ts))))
16540 (default-input (and ts (org-get-compact-tod ts)))
16541 (repeater (and ts
16542 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16543 (match-string 0 ts)))
16544 org-time-was-given
16545 org-end-time-was-given
16546 (time
16547 (and (if (equal arg '(16)) (current-time)
16548 ;; Preserve `this-command' and `last-command'.
16549 (let ((this-command this-command)
16550 (last-command last-command))
16551 (org-read-date
16552 arg 'totime nil nil default-time default-input
16553 inactive))))))
16554 (cond
16555 ((and ts
16556 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16557 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16558 (insert "--")
16559 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16561 ;; Make sure we're on a timestamp. When in the middle of a date
16562 ;; range, move arbitrarily to range end.
16563 (unless (org-at-timestamp-p 'lax)
16564 (skip-chars-forward "-")
16565 (org-at-timestamp-p 'lax))
16566 (replace-match "")
16567 (setq org-last-changed-timestamp
16568 (org-insert-time-stamp
16569 time (or org-time-was-given arg)
16570 inactive nil nil (list org-end-time-was-given)))
16571 (when repeater
16572 (backward-char)
16573 (insert " " repeater)
16574 (setq org-last-changed-timestamp
16575 (concat (substring org-last-inserted-timestamp 0 -1)
16576 " " repeater ">")))
16577 (message "Timestamp updated"))
16578 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16579 (t (org-insert-time-stamp
16580 time (or org-time-was-given arg) inactive nil nil
16581 (list org-end-time-was-given))))))
16583 ;; FIXME: can we use this for something else, like computing time differences?
16584 (defun org-get-compact-tod (s)
16585 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16586 (let* ((t1 (match-string 1 s))
16587 (h1 (string-to-number (match-string 2 s)))
16588 (m1 (string-to-number (match-string 3 s)))
16589 (t2 (and (match-end 4) (match-string 5 s)))
16590 (h2 (and t2 (string-to-number (match-string 6 s))))
16591 (m2 (and t2 (string-to-number (match-string 7 s))))
16592 dh dm)
16593 (if (not t2)
16595 (setq dh (- h2 h1) dm (- m2 m1))
16596 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16597 (concat t1 "+" (number-to-string dh)
16598 (and (/= 0 dm) (format ":%02d" dm)))))))
16600 (defun org-time-stamp-inactive (&optional arg)
16601 "Insert an inactive time stamp.
16602 An inactive time stamp is enclosed in square brackets instead of angle
16603 brackets. It is inactive in the sense that it does not trigger agenda entries,
16604 does not link to the calendar and cannot be changed with the S-cursor keys.
16605 So these are more for recording a certain time/date."
16606 (interactive "P")
16607 (org-time-stamp arg 'inactive))
16609 (defvar org-date-ovl (make-overlay 1 1))
16610 (overlay-put org-date-ovl 'face 'org-date-selected)
16611 (delete-overlay org-date-ovl)
16613 (defvar org-ans1) ; dynamically scoped parameter
16614 (defvar org-ans2) ; dynamically scoped parameter
16616 (defvar org-plain-time-of-day-regexp) ; defined below
16618 (defvar org-overriding-default-time nil) ; dynamically scoped
16619 (defvar org-read-date-overlay nil)
16620 (defvar org-dcst nil) ; dynamically scoped
16621 (defvar org-read-date-history nil)
16622 (defvar org-read-date-final-answer nil)
16623 (defvar org-read-date-analyze-futurep nil)
16624 (defvar org-read-date-analyze-forced-year nil)
16625 (defvar org-read-date-inactive)
16627 (defvar org-read-date-minibuffer-local-map
16628 (let* ((map (make-sparse-keymap)))
16629 (set-keymap-parent map minibuffer-local-map)
16630 (org-defkey map (kbd ".")
16631 (lambda () (interactive)
16632 ;; Are we at the beginning of the prompt?
16633 (if (looking-back "^[^:]+: "
16634 (let ((inhibit-field-text-motion t))
16635 (line-beginning-position)))
16636 (org-eval-in-calendar '(calendar-goto-today))
16637 (insert "."))))
16638 (org-defkey map (kbd "C-.")
16639 (lambda () (interactive)
16640 (org-eval-in-calendar '(calendar-goto-today))))
16641 (org-defkey map [(meta shift left)]
16642 (lambda () (interactive)
16643 (org-eval-in-calendar '(calendar-backward-month 1))))
16644 (org-defkey map [(meta shift right)]
16645 (lambda () (interactive)
16646 (org-eval-in-calendar '(calendar-forward-month 1))))
16647 (org-defkey map [(meta shift up)]
16648 (lambda () (interactive)
16649 (org-eval-in-calendar '(calendar-backward-year 1))))
16650 (org-defkey map [(meta shift down)]
16651 (lambda () (interactive)
16652 (org-eval-in-calendar '(calendar-forward-year 1))))
16653 (org-defkey map [?\e (shift left)]
16654 (lambda () (interactive)
16655 (org-eval-in-calendar '(calendar-backward-month 1))))
16656 (org-defkey map [?\e (shift right)]
16657 (lambda () (interactive)
16658 (org-eval-in-calendar '(calendar-forward-month 1))))
16659 (org-defkey map [?\e (shift up)]
16660 (lambda () (interactive)
16661 (org-eval-in-calendar '(calendar-backward-year 1))))
16662 (org-defkey map [?\e (shift down)]
16663 (lambda () (interactive)
16664 (org-eval-in-calendar '(calendar-forward-year 1))))
16665 (org-defkey map [(shift up)]
16666 (lambda () (interactive)
16667 (org-eval-in-calendar '(calendar-backward-week 1))))
16668 (org-defkey map [(shift down)]
16669 (lambda () (interactive)
16670 (org-eval-in-calendar '(calendar-forward-week 1))))
16671 (org-defkey map [(shift left)]
16672 (lambda () (interactive)
16673 (org-eval-in-calendar '(calendar-backward-day 1))))
16674 (org-defkey map [(shift right)]
16675 (lambda () (interactive)
16676 (org-eval-in-calendar '(calendar-forward-day 1))))
16677 (org-defkey map "!"
16678 (lambda () (interactive)
16679 (org-eval-in-calendar '(diary-view-entries))
16680 (message "")))
16681 (org-defkey map ">"
16682 (lambda () (interactive)
16683 (org-eval-in-calendar '(calendar-scroll-left 1))))
16684 (org-defkey map "<"
16685 (lambda () (interactive)
16686 (org-eval-in-calendar '(calendar-scroll-right 1))))
16687 (org-defkey map "\C-v"
16688 (lambda () (interactive)
16689 (org-eval-in-calendar
16690 '(calendar-scroll-left-three-months 1))))
16691 (org-defkey map "\M-v"
16692 (lambda () (interactive)
16693 (org-eval-in-calendar
16694 '(calendar-scroll-right-three-months 1))))
16695 map)
16696 "Keymap for minibuffer commands when using `org-read-date'.")
16698 (defvar org-def)
16699 (defvar org-defdecode)
16700 (defvar org-with-time)
16702 (defvar calendar-setup) ; Dynamically scoped.
16703 (defun org-read-date (&optional with-time to-time from-string prompt
16704 default-time default-input inactive)
16705 "Read a date, possibly a time, and make things smooth for the user.
16706 The prompt will suggest to enter an ISO date, but you can also enter anything
16707 which will at least partially be understood by `parse-time-string'.
16708 Unrecognized parts of the date will default to the current day, month, year,
16709 hour and minute. If this command is called to replace a timestamp at point,
16710 or to enter the second timestamp of a range, the default time is taken
16711 from the existing stamp. Furthermore, the command prefers the future,
16712 so if you are giving a date where the year is not given, and the day-month
16713 combination is already past in the current year, it will assume you
16714 mean next year. For details, see the manual. A few examples:
16716 3-2-5 --> 2003-02-05
16717 feb 15 --> currentyear-02-15
16718 2/15 --> currentyear-02-15
16719 sep 12 9 --> 2009-09-12
16720 12:45 --> today 12:45
16721 22 sept 0:34 --> currentyear-09-22 0:34
16722 12 --> currentyear-currentmonth-12
16723 Fri --> nearest Friday after today
16724 -Tue --> last Tuesday
16725 etc.
16727 Furthermore you can specify a relative date by giving, as the *first* thing
16728 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16729 change in days weeks, months, years.
16730 With a single plus or minus, the date is relative to today. With a double
16731 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16732 +4d --> four days from today
16733 +4 --> same as above
16734 +2w --> two weeks from today
16735 ++5 --> five days from default date
16737 The function understands only English month and weekday abbreviations.
16739 While prompting, a calendar is popped up - you can also select the
16740 date with the mouse (button 1). The calendar shows a period of three
16741 months. To scroll it to other months, use the keys `>' and `<'.
16742 If you don't like the calendar, turn it off with
16743 (setq org-read-date-popup-calendar nil)
16745 With optional argument TO-TIME, the date will immediately be converted
16746 to an internal time.
16747 With an optional argument WITH-TIME, the prompt will suggest to
16748 also insert a time. Note that when WITH-TIME is not set, you can
16749 still enter a time, and this function will inform the calling routine
16750 about this change. The calling routine may then choose to change the
16751 format used to insert the time stamp into the buffer to include the time.
16752 With optional argument FROM-STRING, read from this string instead from
16753 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16754 the time/date that is used for everything that is not specified by the
16755 user."
16756 (require 'parse-time)
16757 (let* ((org-with-time with-time)
16758 (org-time-stamp-rounding-minutes
16759 (if (equal org-with-time '(16))
16760 '(0 0)
16761 org-time-stamp-rounding-minutes))
16762 (org-dcst org-display-custom-times)
16763 (ct (org-current-time))
16764 (org-def (or org-overriding-default-time default-time ct))
16765 (org-defdecode (decode-time org-def))
16766 (cur-frame (selected-frame))
16767 (mouse-autoselect-window nil) ; Don't let the mouse jump
16768 (calendar-setup
16769 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16770 (calendar-move-hook nil)
16771 (calendar-view-diary-initially-flag nil)
16772 (calendar-view-holidays-initially-flag nil)
16773 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16774 ;; Rationalize `org-def' and `org-defdecode', if required.
16775 (when (< (nth 2 org-defdecode) org-extend-today-until)
16776 (setf (nth 2 org-defdecode) -1)
16777 (setf (nth 1 org-defdecode) 59)
16778 (setq org-def (apply #'encode-time org-defdecode))
16779 (setq org-defdecode (decode-time org-def)))
16780 (let* ((timestr (format-time-string
16781 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16782 org-def))
16783 (prompt (concat (if prompt (concat prompt " ") "")
16784 (format "Date+time [%s]: " timestr))))
16785 (cond
16786 (from-string (setq ans from-string))
16787 (org-read-date-popup-calendar
16788 (save-excursion
16789 (save-window-excursion
16790 (calendar)
16791 (when (eq calendar-setup 'calendar-only)
16792 (setq cal-frame
16793 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16794 (select-frame cal-frame))
16795 (org-eval-in-calendar '(setq cursor-type nil) t)
16796 (unwind-protect
16797 (progn
16798 (calendar-forward-day (- (time-to-days org-def)
16799 (calendar-absolute-from-gregorian
16800 (calendar-current-date))))
16801 (org-eval-in-calendar nil t)
16802 (let* ((old-map (current-local-map))
16803 (map (copy-keymap calendar-mode-map))
16804 (minibuffer-local-map
16805 (copy-keymap org-read-date-minibuffer-local-map)))
16806 (org-defkey map (kbd "RET") 'org-calendar-select)
16807 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16808 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16809 (unwind-protect
16810 (progn
16811 (use-local-map map)
16812 (setq org-read-date-inactive inactive)
16813 (add-hook 'post-command-hook 'org-read-date-display)
16814 (setq org-ans0
16815 (read-string prompt
16816 default-input
16817 'org-read-date-history
16818 nil))
16819 ;; org-ans0: from prompt
16820 ;; org-ans1: from mouse click
16821 ;; org-ans2: from calendar motion
16822 (setq ans
16823 (concat org-ans0 " " (or org-ans1 org-ans2))))
16824 (remove-hook 'post-command-hook 'org-read-date-display)
16825 (use-local-map old-map)
16826 (when org-read-date-overlay
16827 (delete-overlay org-read-date-overlay)
16828 (setq org-read-date-overlay nil)))))
16829 (bury-buffer "*Calendar*")
16830 (when cal-frame
16831 (delete-frame cal-frame)
16832 (select-frame-set-input-focus cur-frame))))))
16834 (t ; Naked prompt only
16835 (unwind-protect
16836 (setq ans (read-string prompt default-input
16837 'org-read-date-history timestr))
16838 (when org-read-date-overlay
16839 (delete-overlay org-read-date-overlay)
16840 (setq org-read-date-overlay nil))))))
16842 (setq final (org-read-date-analyze ans org-def org-defdecode))
16844 (when org-read-date-analyze-forced-year
16845 (message "Year was forced into %s"
16846 (if org-read-date-force-compatible-dates
16847 "compatible range (1970-2037)"
16848 "range representable on this machine"))
16849 (ding))
16851 ;; One round trip to get rid of 34th of August and stuff like that....
16852 (setq final (decode-time (apply 'encode-time final)))
16854 (setq org-read-date-final-answer ans)
16856 (if to-time
16857 (apply 'encode-time final)
16858 (if (and (boundp 'org-time-was-given) org-time-was-given)
16859 (format "%04d-%02d-%02d %02d:%02d"
16860 (nth 5 final) (nth 4 final) (nth 3 final)
16861 (nth 2 final) (nth 1 final))
16862 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16864 (defun org-read-date-display ()
16865 "Display the current date prompt interpretation in the minibuffer."
16866 (when org-read-date-display-live
16867 (when org-read-date-overlay
16868 (delete-overlay org-read-date-overlay))
16869 (when (minibufferp (current-buffer))
16870 (save-excursion
16871 (end-of-line 1)
16872 (while (not (equal (buffer-substring
16873 (max (point-min) (- (point) 4)) (point))
16874 " "))
16875 (insert " ")))
16876 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16877 " " (or org-ans1 org-ans2)))
16878 (org-end-time-was-given nil)
16879 (f (org-read-date-analyze ans org-def org-defdecode))
16880 (fmts (if org-dcst
16881 org-time-stamp-custom-formats
16882 org-time-stamp-formats))
16883 (fmt (if (or org-with-time
16884 (and (boundp 'org-time-was-given) org-time-was-given))
16885 (cdr fmts)
16886 (car fmts)))
16887 (txt (format-time-string fmt (apply 'encode-time f)))
16888 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16889 (txt (concat "=> " txt)))
16890 (when (and org-end-time-was-given
16891 (string-match org-plain-time-of-day-regexp txt))
16892 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16893 org-end-time-was-given
16894 (substring txt (match-end 0)))))
16895 (when org-read-date-analyze-futurep
16896 (setq txt (concat txt " (=>F)")))
16897 (setq org-read-date-overlay
16898 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16899 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16901 (defun org-read-date-analyze (ans def defdecode)
16902 "Analyze the combined answer of the date prompt."
16903 ;; FIXME: cleanup and comment
16904 ;; Pass `current-time' result to `decode-time' (instead of calling
16905 ;; without arguments) so that only `current-time' has to be
16906 ;; overridden in tests.
16907 (let ((org-def def)
16908 (org-defdecode defdecode)
16909 (nowdecode (decode-time (current-time)))
16910 delta deltan deltaw deltadef year month day
16911 hour minute second wday pm h2 m2 tl wday1
16912 iso-year iso-weekday iso-week iso-date futurep kill-year)
16913 (setq org-read-date-analyze-futurep nil
16914 org-read-date-analyze-forced-year nil)
16915 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16916 (setq ans "+0"))
16918 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16919 (setq ans (replace-match "" t t ans)
16920 deltan (car delta)
16921 deltaw (nth 1 delta)
16922 deltadef (nth 2 delta)))
16924 ;; Check if there is an iso week date in there. If yes, store the
16925 ;; info and postpone interpreting it until the rest of the parsing
16926 ;; is done.
16927 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16928 (setq iso-year (when (match-end 1)
16929 (org-small-year-to-year
16930 (string-to-number (match-string 1 ans))))
16931 iso-weekday (when (match-end 3)
16932 (string-to-number (match-string 3 ans)))
16933 iso-week (string-to-number (match-string 2 ans)))
16934 (setq ans (replace-match "" t t ans)))
16936 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16937 (when (string-match
16938 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16939 (setq year (if (match-end 2)
16940 (string-to-number (match-string 2 ans))
16941 (progn (setq kill-year t)
16942 (string-to-number (format-time-string "%Y"))))
16943 month (string-to-number (match-string 3 ans))
16944 day (string-to-number (match-string 4 ans)))
16945 (setq year (org-small-year-to-year year))
16946 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16947 t nil ans)))
16949 ;; Help matching dotted european dates
16950 (when (string-match
16951 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16952 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16953 (setq kill-year t)
16954 (string-to-number (format-time-string "%Y")))
16955 day (string-to-number (match-string 1 ans))
16956 month (string-to-number (match-string 2 ans))
16957 ans (replace-match (format "%04d-%02d-%02d" year month day)
16958 t nil ans)))
16960 ;; Help matching american dates, like 5/30 or 5/30/7
16961 (when (string-match
16962 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16963 (setq year (if (match-end 4)
16964 (string-to-number (match-string 4 ans))
16965 (progn (setq kill-year t)
16966 (string-to-number (format-time-string "%Y"))))
16967 month (string-to-number (match-string 1 ans))
16968 day (string-to-number (match-string 2 ans)))
16969 (setq year (org-small-year-to-year year))
16970 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16971 t nil ans)))
16972 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16973 ;; If there is a time with am/pm, and *no* time without it, we convert
16974 ;; so that matching will be successful.
16975 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16976 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16977 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16978 (setq hour (string-to-number (match-string 1 ans))
16979 minute (if (match-end 3)
16980 (string-to-number (match-string 3 ans))
16982 pm (equal ?p
16983 (string-to-char (downcase (match-string 4 ans)))))
16984 (if (and (= hour 12) (not pm))
16985 (setq hour 0)
16986 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16987 (setq ans (replace-match (format "%02d:%02d" hour minute)
16988 t t ans))))
16990 ;; Check if a time range is given as a duration
16991 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16992 (setq hour (string-to-number (match-string 1 ans))
16993 h2 (+ hour (string-to-number (match-string 3 ans)))
16994 minute (string-to-number (match-string 2 ans))
16995 m2 (+ minute (if (match-end 5) (string-to-number
16996 (match-string 5 ans))0)))
16997 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16998 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16999 t t ans)))
17001 ;; Check if there is a time range
17002 (when (boundp 'org-end-time-was-given)
17003 (setq org-time-was-given nil)
17004 (when (and (string-match org-plain-time-of-day-regexp ans)
17005 (match-end 8))
17006 (setq org-end-time-was-given (match-string 8 ans))
17007 (setq ans (concat (substring ans 0 (match-beginning 7))
17008 (substring ans (match-end 7))))))
17010 (setq tl (parse-time-string ans)
17011 day (or (nth 3 tl) (nth 3 org-defdecode))
17012 month
17013 (cond ((nth 4 tl))
17014 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17015 ;; Day was specified. Make sure DAY+MONTH
17016 ;; combination happens in the future.
17017 ((nth 3 tl)
17018 (setq futurep t)
17019 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17020 (nth 4 nowdecode)))
17021 (t (nth 4 org-defdecode)))
17022 year
17023 (cond ((and (not kill-year) (nth 5 tl)))
17024 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17025 ;; Month was guessed in the future and is at least
17026 ;; equal to NOWDECODE's. Fix year accordingly.
17027 (futurep
17028 (if (or (> month (nth 4 nowdecode))
17029 (>= day (nth 3 nowdecode)))
17030 (nth 5 nowdecode)
17031 (1+ (nth 5 nowdecode))))
17032 ;; Month was specified. Make sure MONTH+YEAR
17033 ;; combination happens in the future.
17034 ((nth 4 tl)
17035 (setq futurep t)
17036 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17037 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17038 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17039 (t (nth 5 nowdecode))))
17040 (t (nth 5 org-defdecode)))
17041 hour (or (nth 2 tl) (nth 2 org-defdecode))
17042 minute (or (nth 1 tl) (nth 1 org-defdecode))
17043 second (or (nth 0 tl) 0)
17044 wday (nth 6 tl))
17046 (when (and (eq org-read-date-prefer-future 'time)
17047 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17048 (equal day (nth 3 nowdecode))
17049 (equal month (nth 4 nowdecode))
17050 (equal year (nth 5 nowdecode))
17051 (nth 2 tl)
17052 (or (< (nth 2 tl) (nth 2 nowdecode))
17053 (and (= (nth 2 tl) (nth 2 nowdecode))
17054 (nth 1 tl)
17055 (< (nth 1 tl) (nth 1 nowdecode)))))
17056 (setq day (1+ day)
17057 futurep t))
17059 ;; Special date definitions below
17060 (cond
17061 (iso-week
17062 ;; There was an iso week
17063 (require 'cal-iso)
17064 (setq futurep nil)
17065 (setq year (or iso-year year)
17066 day (or iso-weekday wday 1)
17067 wday nil ; to make sure that the trigger below does not match
17068 iso-date (calendar-gregorian-from-absolute
17069 (calendar-iso-to-absolute
17070 (list iso-week day year))))
17071 ; FIXME: Should we also push ISO weeks into the future?
17072 ; (when (and org-read-date-prefer-future
17073 ; (not iso-year)
17074 ; (< (calendar-absolute-from-gregorian iso-date)
17075 ; (time-to-days (current-time))))
17076 ; (setq year (1+ year)
17077 ; iso-date (calendar-gregorian-from-absolute
17078 ; (calendar-iso-to-absolute
17079 ; (list iso-week day year)))))
17080 (setq month (car iso-date)
17081 year (nth 2 iso-date)
17082 day (nth 1 iso-date)))
17083 (deltan
17084 (setq futurep nil)
17085 (unless deltadef
17086 ;; Pass `current-time' result to `decode-time' (instead of
17087 ;; calling without arguments) so that only `current-time' has
17088 ;; to be overridden in tests.
17089 (let ((now (decode-time (current-time))))
17090 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17091 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17092 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17093 ((equal deltaw "m") (setq month (+ month deltan)))
17094 ((equal deltaw "y") (setq year (+ year deltan)))))
17095 ((and wday (not (nth 3 tl)))
17096 ;; Weekday was given, but no day, so pick that day in the week
17097 ;; on or after the derived date.
17098 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17099 (unless (equal wday wday1)
17100 (setq day (+ day (% (- wday wday1 -7) 7))))))
17101 (when (and (boundp 'org-time-was-given)
17102 (nth 2 tl))
17103 (setq org-time-was-given t))
17104 (when (< year 100) (setq year (+ 2000 year)))
17105 ;; Check of the date is representable
17106 (if org-read-date-force-compatible-dates
17107 (progn
17108 (when (< year 1970)
17109 (setq year 1970 org-read-date-analyze-forced-year t))
17110 (when (> year 2037)
17111 (setq year 2037 org-read-date-analyze-forced-year t)))
17112 (condition-case nil
17113 (ignore (encode-time second minute hour day month year))
17114 (error
17115 (setq year (nth 5 org-defdecode))
17116 (setq org-read-date-analyze-forced-year t))))
17117 (setq org-read-date-analyze-futurep futurep)
17118 (list second minute hour day month year)))
17120 (defvar parse-time-weekdays)
17121 (defun org-read-date-get-relative (s today default)
17122 "Check string S for special relative date string.
17123 TODAY and DEFAULT are internal times, for today and for a default.
17124 Return shift list (N what def-flag)
17125 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17126 N is the number of WHATs to shift.
17127 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17128 the DEFAULT date rather than TODAY."
17129 (require 'parse-time)
17130 (when (and
17131 (string-match
17132 (concat
17133 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17134 "\\([0-9]+\\)?"
17135 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17136 "\\([ \t]\\|$\\)") s)
17137 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17138 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17139 (string-to-char (substring (match-string 1 s) -1))
17140 ?+))
17141 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17142 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17143 (what (if (match-end 3) (match-string 3 s) "d"))
17144 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17145 (date (if rel default today))
17146 (wday (nth 6 (decode-time date)))
17147 delta)
17148 (if wday1
17149 (progn
17150 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17151 (when (= delta 0) (setq delta 7))
17152 (when (= dir ?-)
17153 (setq delta (- delta 7))
17154 (when (= delta 0) (setq delta -7)))
17155 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17156 (list delta "d" rel))
17157 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17159 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17160 "Turn a user-specified date into the internal representation.
17161 The internal representation needed by the calendar is (month day year).
17162 This is a wrapper to handle the brain-dead convention in calendar that
17163 user function argument order change dependent on argument order."
17164 (pcase calendar-date-style
17165 (`american (list arg1 arg2 arg3))
17166 (`european (list arg2 arg1 arg3))
17167 (`iso (list arg2 arg3 arg1))))
17169 (defun org-eval-in-calendar (form &optional keepdate)
17170 "Eval FORM in the calendar window and return to current window.
17171 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17172 (let ((sf (selected-frame))
17173 (sw (selected-window)))
17174 (select-window (get-buffer-window "*Calendar*" t))
17175 (eval form)
17176 (when (and (not keepdate) (calendar-cursor-to-date))
17177 (let* ((date (calendar-cursor-to-date))
17178 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17179 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17180 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17181 (select-window sw)
17182 (select-frame-set-input-focus sf)))
17184 (defun org-calendar-select ()
17185 "Return to `org-read-date' with the date currently selected.
17186 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17187 (interactive)
17188 (when (calendar-cursor-to-date)
17189 (let* ((date (calendar-cursor-to-date))
17190 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17191 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17192 (when (active-minibuffer-window) (exit-minibuffer))))
17194 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17195 "Insert a date stamp for the date given by the internal TIME.
17196 See `format-time-string' for the format of TIME.
17197 WITH-HM means use the stamp format that includes the time of the day.
17198 INACTIVE means use square brackets instead of angular ones, so that the
17199 stamp will not contribute to the agenda.
17200 PRE and POST are optional strings to be inserted before and after the
17201 stamp.
17202 The command returns the inserted time stamp."
17203 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17204 stamp)
17205 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17206 (insert-before-markers (or pre ""))
17207 (when (listp extra)
17208 (setq extra (car extra))
17209 (if (and (stringp extra)
17210 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17211 (setq extra (format "-%02d:%02d"
17212 (string-to-number (match-string 1 extra))
17213 (string-to-number (match-string 2 extra))))
17214 (setq extra nil)))
17215 (when extra
17216 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17217 (insert-before-markers (setq stamp (format-time-string fmt time)))
17218 (insert-before-markers (or post ""))
17219 (setq org-last-inserted-timestamp stamp)))
17221 (defun org-toggle-time-stamp-overlays ()
17222 "Toggle the use of custom time stamp formats."
17223 (interactive)
17224 (setq org-display-custom-times (not org-display-custom-times))
17225 (unless org-display-custom-times
17226 (let ((p (point-min)) (bmp (buffer-modified-p)))
17227 (while (setq p (next-single-property-change p 'display))
17228 (when (and (get-text-property p 'display)
17229 (eq (get-text-property p 'face) 'org-date))
17230 (remove-text-properties
17231 p (setq p (next-single-property-change p 'display))
17232 '(display t))))
17233 (set-buffer-modified-p bmp)))
17234 (org-restart-font-lock)
17235 (setq org-table-may-need-update t)
17236 (if org-display-custom-times
17237 (message "Time stamps are overlaid with custom format")
17238 (message "Time stamp overlays removed")))
17240 (defun org-display-custom-time (beg end)
17241 "Overlay modified time stamp format over timestamp between BEG and END."
17242 (let* ((ts (buffer-substring beg end))
17243 t1 with-hm tf time str (off 0))
17244 (save-match-data
17245 (setq t1 (org-parse-time-string ts t))
17246 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17247 (setq off (- (match-end 0) (match-beginning 0)))))
17248 (setq end (- end off))
17249 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17250 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17251 time (org-fix-decoded-time t1)
17252 str (org-add-props
17253 (format-time-string
17254 (substring tf 1 -1) (apply 'encode-time time))
17255 nil 'mouse-face 'highlight))
17256 (put-text-property beg end 'display str)))
17258 (defun org-fix-decoded-time (time)
17259 "Set 0 instead of nil for the first 6 elements of time.
17260 Don't touch the rest."
17261 (let ((n 0))
17262 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17264 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17265 "Difference between TIMESTAMP-STRING and now in days.
17266 If SECONDS is non-nil, return the difference in seconds."
17267 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17268 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17269 (funcall fdiff (current-time)))))
17271 (defun org-deadline-close-p (timestamp-string &optional ndays)
17272 "Is the time in TIMESTAMP-STRING close to the current date?"
17273 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17274 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17275 (not (org-entry-is-done-p))))
17277 (defun org-get-wdays (ts &optional delay zero-delay)
17278 "Get the deadline lead time appropriate for timestring TS.
17279 When DELAY is non-nil, get the delay time for scheduled items
17280 instead of the deadline lead time. When ZERO-DELAY is non-nil
17281 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17282 don't try to find the delay cookie in the scheduled timestamp."
17283 (let ((tv (if delay org-scheduled-delay-days
17284 org-deadline-warning-days)))
17285 (cond
17286 ((or (and delay (< tv 0))
17287 (and delay zero-delay (<= tv 0))
17288 (and (not delay) (<= tv 0)))
17289 ;; Enforce this value no matter what
17290 (- tv))
17291 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17292 ;; lead time is specified.
17293 (floor (* (string-to-number (match-string 1 ts))
17294 (cdr (assoc (match-string 2 ts)
17295 '(("d" . 1) ("w" . 7)
17296 ("m" . 30.4) ("y" . 365.25)
17297 ("h" . 0.041667)))))))
17298 ;; go for the default.
17299 (t tv))))
17301 (defun org-calendar-select-mouse (ev)
17302 "Return to `org-read-date' with the date currently selected.
17303 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17304 (interactive "e")
17305 (mouse-set-point ev)
17306 (when (calendar-cursor-to-date)
17307 (let* ((date (calendar-cursor-to-date))
17308 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17309 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17310 (when (active-minibuffer-window) (exit-minibuffer))))
17312 (defun org-check-deadlines (ndays)
17313 "Check if there are any deadlines due or past due.
17314 A deadline is considered due if it happens within `org-deadline-warning-days'
17315 days from today's date. If the deadline appears in an entry marked DONE,
17316 it is not shown. A numeric prefix argument NDAYS can be used to test that
17317 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17318 are shown."
17319 (interactive "P")
17320 (let* ((org-warn-days
17321 (cond
17322 ((equal ndays '(4)) 100000)
17323 (ndays (prefix-numeric-value ndays))
17324 (t (abs org-deadline-warning-days))))
17325 (case-fold-search nil)
17326 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17327 (callback
17328 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17329 (message "%d deadlines past-due or due within %d days"
17330 (org-occur regexp nil callback)
17331 org-warn-days)))
17333 (defsubst org-re-timestamp (type)
17334 "Return a regexp for timestamp TYPE.
17335 Allowed values for TYPE are:
17337 all: all timestamps
17338 active: only active timestamps (<...>)
17339 inactive: only inactive timestamps ([...])
17340 scheduled: only scheduled timestamps
17341 deadline: only deadline timestamps
17342 closed: only closed time-stamps
17344 When TYPE is nil, fall back on returning a regexp that matches
17345 both scheduled and deadline timestamps."
17346 (cl-case type
17347 (all org-ts-regexp-both)
17348 (active org-ts-regexp)
17349 (inactive org-ts-regexp-inactive)
17350 (scheduled org-scheduled-time-regexp)
17351 (deadline org-deadline-time-regexp)
17352 (closed org-closed-time-regexp)
17353 (otherwise
17354 (concat "\\<"
17355 (regexp-opt (list org-deadline-string org-scheduled-string))
17356 " *<\\([^>]+\\)>"))))
17358 (defun org-check-before-date (d)
17359 "Check if there are deadlines or scheduled entries before date D."
17360 (interactive (list (org-read-date)))
17361 (let* ((case-fold-search nil)
17362 (regexp (org-re-timestamp org-ts-type))
17363 (ts-type org-ts-type)
17364 (callback
17365 (lambda ()
17366 (let ((match (match-string 1)))
17367 (and (if (memq ts-type '(active inactive all))
17368 (eq (org-element-type (save-excursion
17369 (backward-char)
17370 (org-element-context)))
17371 'timestamp)
17372 (org-at-planning-p))
17373 (time-less-p
17374 (org-time-string-to-time match t)
17375 (org-time-string-to-time d t)))))))
17376 (message "%d entries before %s"
17377 (org-occur regexp nil callback)
17378 d)))
17380 (defun org-check-after-date (d)
17381 "Check if there are deadlines or scheduled entries after date D."
17382 (interactive (list (org-read-date)))
17383 (let* ((case-fold-search nil)
17384 (regexp (org-re-timestamp org-ts-type))
17385 (ts-type org-ts-type)
17386 (callback
17387 (lambda ()
17388 (let ((match (match-string 1)))
17389 (and (if (memq ts-type '(active inactive all))
17390 (eq (org-element-type (save-excursion
17391 (backward-char)
17392 (org-element-context)))
17393 'timestamp)
17394 (org-at-planning-p))
17395 (not (time-less-p
17396 (org-time-string-to-time match t)
17397 (org-time-string-to-time d t))))))))
17398 (message "%d entries after %s"
17399 (org-occur regexp nil callback)
17400 d)))
17402 (defun org-check-dates-range (start-date end-date)
17403 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17404 (interactive (list (org-read-date nil nil nil "Range starts")
17405 (org-read-date nil nil nil "Range end")))
17406 (let ((case-fold-search nil)
17407 (regexp (org-re-timestamp org-ts-type))
17408 (callback
17409 (let ((type org-ts-type))
17410 (lambda ()
17411 (let ((match (match-string 1)))
17412 (and
17413 (if (memq type '(active inactive all))
17414 (eq (org-element-type (save-excursion
17415 (backward-char)
17416 (org-element-context)))
17417 'timestamp)
17418 (org-at-planning-p))
17419 (not (time-less-p
17420 (org-time-string-to-time match t)
17421 (org-time-string-to-time start-date t)))
17422 (time-less-p
17423 (org-time-string-to-time match t)
17424 (org-time-string-to-time end-date t))))))))
17425 (message "%d entries between %s and %s"
17426 (org-occur regexp nil callback) start-date end-date)))
17428 (defun org-evaluate-time-range (&optional to-buffer)
17429 "Evaluate a time range by computing the difference between start and end.
17430 Normally the result is just printed in the echo area, but with prefix arg
17431 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17432 If the time range is actually in a table, the result is inserted into the
17433 next column.
17434 For time difference computation, a year is assumed to be exactly 365
17435 days in order to avoid rounding problems."
17436 (interactive "P")
17438 (org-clock-update-time-maybe)
17439 (save-excursion
17440 (unless (org-at-date-range-p t)
17441 (goto-char (point-at-bol))
17442 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17443 (unless (org-at-date-range-p t)
17444 (user-error "Not at a time-stamp range, and none found in current line")))
17445 (let* ((ts1 (match-string 1))
17446 (ts2 (match-string 2))
17447 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17448 (match-end (match-end 0))
17449 (time1 (org-time-string-to-time ts1))
17450 (time2 (org-time-string-to-time ts2))
17451 (t1 (float-time time1))
17452 (t2 (float-time time2))
17453 (diff (abs (- t2 t1)))
17454 (negative (< (- t2 t1) 0))
17455 ;; (ys (floor (* 365 24 60 60)))
17456 (ds (* 24 60 60))
17457 (hs (* 60 60))
17458 (fy "%dy %dd %02d:%02d")
17459 (fy1 "%dy %dd")
17460 (fd "%dd %02d:%02d")
17461 (fd1 "%dd")
17462 (fh "%02d:%02d")
17463 y d h m align)
17464 (if havetime
17465 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17467 d (floor (/ diff ds)) diff (mod diff ds)
17468 h (floor (/ diff hs)) diff (mod diff hs)
17469 m (floor (/ diff 60)))
17470 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17472 d (floor (+ (/ diff ds) 0.5))
17473 h 0 m 0))
17474 (if (not to-buffer)
17475 (message "%s" (org-make-tdiff-string y d h m))
17476 (if (org-at-table-p)
17477 (progn
17478 (goto-char match-end)
17479 (setq align t)
17480 (and (looking-at " *|") (goto-char (match-end 0))))
17481 (goto-char match-end))
17482 (when (looking-at
17483 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17484 (replace-match ""))
17485 (when negative (insert " -"))
17486 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17487 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17488 (insert " " (format fh h m))))
17489 (when align (org-table-align))
17490 (message "Time difference inserted")))))
17492 (defun org-make-tdiff-string (y d h m)
17493 (let ((fmt "")
17494 (l nil))
17495 (when (> y 0)
17496 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17497 (push y l))
17498 (when (> d 0)
17499 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17500 (push d l))
17501 (when (> h 0)
17502 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17503 (push h l))
17504 (when (> m 0)
17505 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17506 (push m l))
17507 (apply 'format fmt (nreverse l))))
17509 (defun org-time-string-to-time (s &optional zone)
17510 "Convert timestamp string S into internal time.
17511 The optional ZONE is omitted or nil for Emacs local time, t for
17512 Universal Time, ‘wall’ for system wall clock time, or a string as
17513 in the TZ environment variable."
17514 (apply #'encode-time (org-parse-time-string s nil zone)))
17516 (defun org-time-string-to-seconds (s &optional zone)
17517 "Convert a timestamp string S into a number of seconds.
17518 The optional ZONE is omitted or nil for Emacs local time, t for
17519 Universal Time, ‘wall’ for system wall clock time, or a string as
17520 in the TZ environment variable."
17521 (float-time (org-time-string-to-time s zone)))
17523 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17525 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17526 "Convert time stamp S to an absolute day number.
17528 If DAYNR in non-nil, and there is a specifier for a cyclic time
17529 stamp, get the closest date to DAYNR. If PREFER is
17530 `past' (respectively `future') return a date past (respectively
17531 after) or equal to DAYNR.
17533 POS is the location of time stamp S, as a buffer position in
17534 BUFFER.
17536 Diary sexp timestamps are matched against DAYNR, when non-nil.
17537 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17538 signaled."
17539 (cond
17540 ((string-match "\\`%%\\((.*)\\)" s)
17541 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17542 ;; only able to match individual dates. If it fails, raise an
17543 ;; error.
17544 (if (and daynr
17545 (org-diary-sexp-entry
17546 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17547 daynr
17548 (signal 'org-diary-sexp-no-match (list s))))
17549 (daynr (org-closest-date s daynr prefer))
17550 (t (time-to-days
17551 (condition-case errdata
17552 (apply #'encode-time (org-parse-time-string s))
17553 (error (error "Bad timestamp `%s'%s\nError was: %s"
17555 (if (not (and buffer pos)) ""
17556 (format-message " at %d in buffer `%s'" pos buffer))
17557 (cdr errdata))))))))
17559 (defun org-days-to-iso-week (days)
17560 "Return the iso week number."
17561 (require 'cal-iso)
17562 (car (calendar-iso-from-absolute days)))
17564 (defun org-small-year-to-year (year)
17565 "Convert 2-digit years into 4-digit years.
17566 YEAR is expanded into one of the 30 next years, if possible, or
17567 into a past one. Any year larger than 99 is returned unchanged."
17568 (if (>= year 100) year
17569 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17570 (century (/ current 100))
17571 (offset (- year (% current 100))))
17572 (cond ((> offset 30) (+ (* (1- century) 100) year))
17573 ((> offset -70) (+ (* century 100) year))
17574 (t (+ (* (1+ century) 100) year))))))
17576 (defun org-time-from-absolute (d)
17577 "Return the time corresponding to date D.
17578 D may be an absolute day number, or a calendar-type list (month day year)."
17579 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17580 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17582 (defvar org-agenda-current-date)
17583 (defun org-calendar-holiday ()
17584 "List of holidays, for Diary display in Org mode."
17585 (require 'holidays)
17586 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17587 (and hl (mapconcat #'identity hl "; "))))
17589 (defun org-diary-sexp-entry (sexp entry d)
17590 "Process a SEXP diary ENTRY for date D."
17591 (require 'diary-lib)
17592 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17593 ;; dynamically.
17594 (let* ((sexp `(let ((entry ,entry)
17595 (date ',d))
17596 ,(car (read-from-string sexp))))
17597 (result (if calendar-debug-sexp (eval sexp)
17598 (condition-case nil
17599 (eval sexp)
17600 (error
17601 (beep)
17602 (message "Bad sexp at line %d in %s: %s"
17603 (org-current-line)
17604 (buffer-file-name) sexp)
17605 (sleep-for 2))))))
17606 (cond ((stringp result) (split-string result "; "))
17607 ((and (consp result)
17608 (not (consp (cdr result)))
17609 (stringp (cdr result))) (cdr result))
17610 ((and (consp result)
17611 (stringp (car result))) result)
17612 (result entry))))
17614 (defun org-diary-to-ical-string (frombuf)
17615 "Get iCalendar entries from diary entries in buffer FROMBUF.
17616 This uses the icalendar.el library."
17617 (let* ((tmpdir temporary-file-directory)
17618 (tmpfile (make-temp-name
17619 (expand-file-name "orgics" tmpdir)))
17620 buf rtn b e)
17621 (with-current-buffer frombuf
17622 (icalendar-export-region (point-min) (point-max) tmpfile)
17623 (setq buf (find-buffer-visiting tmpfile))
17624 (set-buffer buf)
17625 (goto-char (point-min))
17626 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17627 (setq b (match-beginning 0)))
17628 (goto-char (point-max))
17629 (when (re-search-backward "^END:VEVENT" nil t)
17630 (setq e (match-end 0)))
17631 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17632 (kill-buffer buf)
17633 (delete-file tmpfile)
17634 rtn))
17636 (defun org-closest-date (start current prefer)
17637 "Return closest date to CURRENT starting from START.
17639 CURRENT and START are both time stamps.
17641 When PREFER is `past', return a date that is either CURRENT or
17642 past. When PREFER is `future', return a date that is either
17643 CURRENT or future.
17645 Only time stamps with a repeater are modified. Any other time
17646 stamp stay unchanged. In any case, return value is an absolute
17647 day number."
17648 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17649 ;; No repeater. Do not shift time stamp.
17650 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17651 (let ((value (string-to-number (match-string 1 start)))
17652 (type (match-string 2 start)))
17653 (if (= 0 value)
17654 ;; Repeater with a 0-value is considered as void.
17655 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17656 (let* ((base (org-date-to-gregorian start))
17657 (target (org-date-to-gregorian current))
17658 (sday (calendar-absolute-from-gregorian base))
17659 (cday (calendar-absolute-from-gregorian target))
17660 n1 n2)
17661 ;; If START is already past CURRENT, just return START.
17662 (if (<= cday sday) sday
17663 ;; Compute closest date before (N1) and closest date past
17664 ;; (N2) CURRENT.
17665 (pcase type
17666 ("h"
17667 (let ((missing-hours
17668 (mod (+ (- (* 24 (- cday sday))
17669 (nth 2 (org-parse-time-string start)))
17670 org-extend-today-until)
17671 value)))
17672 (setf n1 (if (= missing-hours 0) cday
17673 (- cday (1+ (/ missing-hours 24)))))
17674 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17675 ((or "d" "w")
17676 (let ((value (if (equal type "w") (* 7 value) value)))
17677 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17678 (setf n2 (+ n1 value))))
17679 ("m"
17680 (let* ((add-months
17681 (lambda (d n)
17682 ;; Add N months to gregorian date D, i.e.,
17683 ;; a list (MONTH DAY YEAR). Return a valid
17684 ;; gregorian date.
17685 (let ((m (+ (nth 0 d) n)))
17686 (list (mod m 12)
17687 (nth 1 d)
17688 (+ (/ m 12) (nth 2 d))))))
17689 (months ; Complete months to TARGET.
17690 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17691 (- (nth 0 target) (nth 0 base))
17692 ;; If START's day is greater than
17693 ;; TARGET's, remove incomplete month.
17694 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17695 value)
17696 value))
17697 (before (funcall add-months base months)))
17698 (setf n1 (calendar-absolute-from-gregorian before))
17699 (setf n2
17700 (calendar-absolute-from-gregorian
17701 (funcall add-months before value)))))
17703 (let* ((d (nth 1 base))
17704 (m (nth 0 base))
17705 (y (nth 2 base))
17706 (years ; Complete years to TARGET.
17707 (* (/ (- (nth 2 target)
17709 ;; If START's month and day are
17710 ;; greater than TARGET's, remove
17711 ;; incomplete year.
17712 (if (or (> (nth 0 target) m)
17713 (and (= (nth 0 target) m)
17714 (> (nth 1 target) d)))
17717 value)
17718 value))
17719 (before (list m d (+ y years))))
17720 (setf n1 (calendar-absolute-from-gregorian before))
17721 (setf n2 (calendar-absolute-from-gregorian
17722 (list m d (+ (nth 2 before) value)))))))
17723 ;; Handle PREFER parameter, if any.
17724 (cond
17725 ((eq prefer 'past) (if (= cday n2) n2 n1))
17726 ((eq prefer 'future) (if (= cday n1) n1 n2))
17727 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17729 (defun org-date-to-gregorian (d)
17730 "Turn any specification of date D into a Gregorian date for the calendar."
17731 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17732 ((and (listp d) (= (length d) 3)) d)
17733 ((stringp d)
17734 (let ((d (org-parse-time-string d)))
17735 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17736 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17738 (defun org-parse-time-string (s &optional nodefault zone)
17739 "Parse the standard Org time string.
17741 This should be a lot faster than the normal `parse-time-string'.
17743 If time is not given, defaults to 0:00. However, with optional
17744 NODEFAULT, hour and minute fields will be nil if not given.
17746 The optional ZONE is omitted or nil for Emacs local time, t for
17747 Universal Time, ‘wall’ for system wall clock time, or a string as
17748 in the TZ environment variable."
17749 (cond ((string-match org-ts-regexp0 s)
17750 (list 0
17751 (when (or (match-beginning 8) (not nodefault))
17752 (string-to-number (or (match-string 8 s) "0")))
17753 (when (or (match-beginning 7) (not nodefault))
17754 (string-to-number (or (match-string 7 s) "0")))
17755 (string-to-number (match-string 4 s))
17756 (string-to-number (match-string 3 s))
17757 (string-to-number (match-string 2 s))
17758 nil nil zone))
17759 ((string-match "^<[^>]+>$" s)
17760 ;; FIXME: `decode-time' needs to be called with ZONE as its
17761 ;; second argument. However, this requires at least Emacs
17762 ;; 25.1. We can do it when we switch to this version as our
17763 ;; minimal requirement.
17764 (decode-time (seconds-to-time (org-matcher-time s))))
17765 (t (error "Not a standard Org time string: %s" s))))
17767 (defun org-timestamp-up (&optional arg)
17768 "Increase the date item at the cursor by one.
17769 If the cursor is on the year, change the year. If it is on the month,
17770 the day or the time, change that.
17771 With prefix ARG, change by that many units."
17772 (interactive "p")
17773 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17775 (defun org-timestamp-down (&optional arg)
17776 "Decrease the date item at the cursor by one.
17777 If the cursor is on the year, change the year. If it is on the month,
17778 the day or the time, change that.
17779 With prefix ARG, change by that many units."
17780 (interactive "p")
17781 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17783 (defun org-timestamp-up-day (&optional arg)
17784 "Increase the date in the time stamp by one day.
17785 With prefix ARG, change that many days."
17786 (interactive "p")
17787 (if (and (not (org-at-timestamp-p 'lax))
17788 (org-at-heading-p))
17789 (org-todo 'up)
17790 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17792 (defun org-timestamp-down-day (&optional arg)
17793 "Decrease the date in the time stamp by one day.
17794 With prefix ARG, change that many days."
17795 (interactive "p")
17796 (if (and (not (org-at-timestamp-p 'lax))
17797 (org-at-heading-p))
17798 (org-todo 'down)
17799 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17801 (defun org-at-timestamp-p (&optional extended)
17802 "Non-nil if point is inside a timestamp.
17804 By default, the function only consider syntactically valid active
17805 timestamps. However, the caller may have a broader definition
17806 for timestamps. As a consequence, optional argument EXTENDED can
17807 be set to the following values
17809 `inactive'
17811 Include also syntactically valid inactive timestamps.
17813 `agenda'
17815 Include timestamps allowed in Agenda, i.e., those in
17816 properties drawers, planning lines and clock lines.
17818 `lax'
17820 Ignore context. The function matches any part of the
17821 document looking like a timestamp. This includes comments,
17822 example blocks...
17824 For backward-compatibility with Org 9.0, every other non-nil
17825 value is equivalent to `inactive'.
17827 When at a timestamp, return the position of the point as a symbol
17828 among `bracket', `after', `year', `month', `hour', `minute',
17829 `day' or a number of character from the last know part of the
17830 time stamp.
17832 When matching, the match groups are the following:
17833 group 1: year
17834 group 2: month
17835 group 3: day number
17836 group 4: day name
17837 group 5: hours, if any
17838 group 6: minutes, if any"
17839 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17840 (pos (point))
17841 (match?
17842 (let ((boundaries (org-in-regexp regexp)))
17843 (save-match-data
17844 (cond ((null boundaries) nil)
17845 ((eq extended 'lax) t)
17847 (or (and (eq extended 'agenda)
17848 (or (org-at-planning-p)
17849 (org-at-property-p)
17850 (and (bound-and-true-p
17851 org-agenda-include-inactive-timestamps)
17852 (org-at-clock-log-p))))
17853 (eq 'timestamp
17854 (save-excursion
17855 (when (= pos (cdr boundaries)) (forward-char -1))
17856 (org-element-type (org-element-context)))))))))))
17857 (cond
17858 ((not match?) nil)
17859 ((= pos (match-beginning 0)) 'bracket)
17860 ;; Distinguish location right before the closing bracket from
17861 ;; right after it.
17862 ((= pos (1- (match-end 0))) 'bracket)
17863 ((= pos (match-end 0)) 'after)
17864 ((org-pos-in-match-range pos 2) 'year)
17865 ((org-pos-in-match-range pos 3) 'month)
17866 ((org-pos-in-match-range pos 7) 'hour)
17867 ((org-pos-in-match-range pos 8) 'minute)
17868 ((or (org-pos-in-match-range pos 4)
17869 (org-pos-in-match-range pos 5)) 'day)
17870 ((and (> pos (or (match-end 8) (match-end 5)))
17871 (< pos (match-end 0)))
17872 (- pos (or (match-end 8) (match-end 5))))
17873 (t 'day))))
17875 (defun org-toggle-timestamp-type ()
17876 "Toggle the type (<active> or [inactive]) of a time stamp."
17877 (interactive)
17878 (when (org-at-timestamp-p 'lax)
17879 (let ((beg (match-beginning 0)) (end (match-end 0))
17880 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17881 (save-excursion
17882 (goto-char beg)
17883 (while (re-search-forward "[][<>]" end t)
17884 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17885 t t)))
17886 (message "Timestamp is now %sactive"
17887 (if (equal (char-after beg) ?<) "" "in")))))
17889 (defun org-at-clock-log-p ()
17890 "Non-nil if point is on a clock log line."
17891 (and (org-match-line org-clock-line-re)
17892 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17894 (defvar org-clock-history) ; defined in org-clock.el
17895 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17896 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17897 "Change the date in the time stamp at point.
17898 The date will be changed by N times WHAT. WHAT can be `day', `month',
17899 `year', `minute', `second'. If WHAT is not given, the cursor position
17900 in the timestamp determines what will be changed.
17901 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17902 (let ((origin (point))
17903 (timestamp? (org-at-timestamp-p 'lax))
17904 origin-cat
17905 with-hm inactive
17906 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17907 extra rem
17908 ts time time0 fixnext clrgx)
17909 (unless timestamp? (user-error "Not at a timestamp"))
17910 (if (and (not what) (eq timestamp? 'bracket))
17911 (org-toggle-timestamp-type)
17912 ;; Point isn't on brackets. Remember the part of the time-stamp
17913 ;; the point was in. Indeed, size of time-stamps may change,
17914 ;; but point must be kept in the same category nonetheless.
17915 (setq origin-cat timestamp?)
17916 (when (and (not what) (not (eq timestamp? 'day))
17917 org-display-custom-times
17918 (get-text-property (point) 'display)
17919 (not (get-text-property (1- (point)) 'display)))
17920 (setq timestamp? 'day))
17921 (setq timestamp? (or what timestamp?)
17922 inactive (= (char-after (match-beginning 0)) ?\[)
17923 ts (match-string 0))
17924 (replace-match "")
17925 (when (string-match
17926 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17928 (setq extra (match-string 1 ts))
17929 (when suppress-tmp-delay
17930 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17931 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17932 (setq with-hm t))
17933 (setq time0 (org-parse-time-string ts))
17934 (when (and updown
17935 (eq timestamp? 'minute)
17936 (not current-prefix-arg))
17937 ;; This looks like s-up and s-down. Change by one rounding step.
17938 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17939 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17940 (setcar (cdr time0) (+ (nth 1 time0)
17941 (if (> n 0) (- rem) (- dm rem))))))
17942 (setq time
17943 (apply #'encode-time
17944 (or (car time0) 0)
17945 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17946 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17947 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17948 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17949 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17950 (nthcdr 6 time0)))
17951 (when (and (memq timestamp? '(hour minute))
17952 extra
17953 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17954 (setq extra (org-modify-ts-extra
17955 extra
17956 (if (eq timestamp? 'hour) 2 5)
17957 n dm)))
17958 (when (integerp timestamp?)
17959 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17960 (when (eq what 'calendar)
17961 (let ((cal-date (org-get-date-from-calendar)))
17962 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17963 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17964 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17965 (setcar time0 (or (car time0) 0))
17966 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17967 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17968 (setq time (apply 'encode-time time0))))
17969 ;; Insert the new time-stamp, and ensure point stays in the same
17970 ;; category as before (i.e. not after the last position in that
17971 ;; category).
17972 (let ((pos (point)))
17973 ;; Stay before inserted string. `save-excursion' is of no use.
17974 (setq org-last-changed-timestamp
17975 (org-insert-time-stamp time with-hm inactive nil nil extra))
17976 (goto-char pos))
17977 (save-match-data
17978 (looking-at org-ts-regexp3)
17979 (goto-char
17980 (pcase origin-cat
17981 ;; `day' category ends before `hour' if any, or at the end
17982 ;; of the day name.
17983 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17984 (`hour (min (match-end 7) origin))
17985 (`minute (min (1- (match-end 8)) origin))
17986 ((pred integerp) (min (1- (match-end 0)) origin))
17987 ;; Point was right after the time-stamp. However, the
17988 ;; time-stamp length might have changed, so refer to
17989 ;; (match-end 0) instead.
17990 (`after (match-end 0))
17991 ;; `year' and `month' have both fixed size: point couldn't
17992 ;; have moved into another part.
17993 (_ origin))))
17994 ;; Update clock if on a CLOCK line.
17995 (org-clock-update-time-maybe)
17996 ;; Maybe adjust the closest clock in `org-clock-history'
17997 (when org-clock-adjust-closest
17998 (if (not (and (org-at-clock-log-p)
17999 (< 1 (length (delq nil (mapcar 'marker-position
18000 org-clock-history))))))
18001 (message "No clock to adjust")
18002 (cond ((save-excursion ; fix previous clock?
18003 (re-search-backward org-ts-regexp0 nil t)
18004 (looking-back (concat org-clock-string " \\[")
18005 (line-beginning-position)))
18006 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18007 ((save-excursion ; fix next clock?
18008 (re-search-backward org-ts-regexp0 nil t)
18009 (looking-at (concat org-ts-regexp0 "\\] =>")))
18010 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18011 (save-window-excursion
18012 ;; Find closest clock to point, adjust the previous/next one in history
18013 (let* ((p (save-excursion (org-back-to-heading t)))
18014 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18015 (clfixnth
18016 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18017 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18018 (if (not clfixpos)
18019 (message "No clock to adjust")
18020 (save-excursion
18021 (org-goto-marker-or-bmk clfixpos)
18022 (org-show-subtree)
18023 (when (re-search-forward clrgx nil t)
18024 (goto-char (match-beginning 1))
18025 (let (org-clock-adjust-closest)
18026 (org-timestamp-change n timestamp? updown))
18027 (message "Clock adjusted in %s for heading: %s"
18028 (file-name-nondirectory (buffer-file-name))
18029 (org-get-heading t t)))))))))
18030 ;; Try to recenter the calendar window, if any.
18031 (when (and org-calendar-follow-timestamp-change
18032 (get-buffer-window "*Calendar*" t)
18033 (memq timestamp? '(day month year)))
18034 (org-recenter-calendar (time-to-days time))))))
18036 (defun org-modify-ts-extra (s pos n dm)
18037 "Change the different parts of the lead-time and repeat fields in timestamp."
18038 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18039 ng h m new rem)
18040 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18041 (cond
18042 ((or (org-pos-in-match-range pos 2)
18043 (org-pos-in-match-range pos 3))
18044 (setq m (string-to-number (match-string 3 s))
18045 h (string-to-number (match-string 2 s)))
18046 (if (org-pos-in-match-range pos 2)
18047 (setq h (+ h n))
18048 (setq n (* dm (with-no-warnings (signum n))))
18049 (unless (= 0 (setq rem (% m dm)))
18050 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18051 (setq m (+ m n)))
18052 (when (< m 0) (setq m (+ m 60) h (1- h)))
18053 (when (> m 59) (setq m (- m 60) h (1+ h)))
18054 (setq h (mod h 24))
18055 (setq ng 1 new (format "-%02d:%02d" h m)))
18056 ((org-pos-in-match-range pos 6)
18057 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18058 ((org-pos-in-match-range pos 5)
18059 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18061 ((org-pos-in-match-range pos 9)
18062 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18063 ((org-pos-in-match-range pos 8)
18064 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18066 (when ng
18067 (setq s (concat
18068 (substring s 0 (match-beginning ng))
18070 (substring s (match-end ng))))))
18073 (defun org-recenter-calendar (d)
18074 "If the calendar is visible, recenter it to date D."
18075 (let ((cwin (get-buffer-window "*Calendar*" t)))
18076 (when cwin
18077 (let ((calendar-move-hook nil))
18078 (with-selected-window cwin
18079 (calendar-goto-date
18080 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18082 (defun org-goto-calendar (&optional arg)
18083 "Go to the Emacs calendar at the current date.
18084 If there is a time stamp in the current line, go to that date.
18085 A prefix ARG can be used to force the current date."
18086 (interactive "P")
18087 (let ((calendar-move-hook nil)
18088 (calendar-view-holidays-initially-flag nil)
18089 (calendar-view-diary-initially-flag nil)
18090 diff)
18091 (when (or (org-at-timestamp-p 'lax)
18092 (org-match-line (concat ".*" org-ts-regexp)))
18093 (let ((d1 (time-to-days (current-time)))
18094 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18095 (setq diff (- d2 d1))))
18096 (calendar)
18097 (calendar-goto-today)
18098 (when (and diff (not arg)) (calendar-forward-day diff))))
18100 (defun org-get-date-from-calendar ()
18101 "Return a list (month day year) of date at point in calendar."
18102 (with-current-buffer "*Calendar*"
18103 (save-match-data
18104 (calendar-cursor-to-date))))
18106 (defun org-date-from-calendar ()
18107 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18108 If there is already a time stamp at the cursor position, update it."
18109 (interactive)
18110 (if (org-at-timestamp-p 'lax)
18111 (org-timestamp-change 0 'calendar)
18112 (let ((cal-date (org-get-date-from-calendar)))
18113 (org-insert-time-stamp
18114 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18116 (defcustom org-effort-durations
18117 `(("min" . 1)
18118 ("h" . 60)
18119 ("d" . ,(* 60 8))
18120 ("w" . ,(* 60 8 5))
18121 ("m" . ,(* 60 8 5 4))
18122 ("y" . ,(* 60 8 5 40)))
18123 "Conversion factor to minutes for an effort modifier.
18125 Each entry has the form (MODIFIER . MINUTES).
18127 In an effort string, a number followed by MODIFIER is multiplied
18128 by the specified number of MINUTES to obtain an effort in
18129 minutes.
18131 For example, if the value of this variable is ((\"hours\" . 60)), then an
18132 effort string \"2hours\" is equivalent to 120 minutes."
18133 :group 'org-agenda
18134 :version "26.1"
18135 :package-version '(Org . "8.3")
18136 :type '(alist :key-type (string :tag "Modifier")
18137 :value-type (number :tag "Minutes")))
18139 (defcustom org-image-actual-width t
18140 "Should we use the actual width of images when inlining them?
18142 When set to t, always use the image width.
18144 When set to a number, use imagemagick (when available) to set
18145 the image's width to this value.
18147 When set to a number in a list, try to get the width from any
18148 #+ATTR.* keyword if it matches a width specification like
18150 #+ATTR_HTML: :width 300px
18152 and fall back on that number if none is found.
18154 When set to nil, try to get the width from an #+ATTR.* keyword
18155 and fall back on the original width if none is found.
18157 This requires Emacs >= 24.1, build with imagemagick support."
18158 :group 'org-appearance
18159 :version "24.4"
18160 :package-version '(Org . "8.0")
18161 :type '(choice
18162 (const :tag "Use the image width" t)
18163 (integer :tag "Use a number of pixels")
18164 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18165 (const :tag "Use #+ATTR* or don't resize" nil)))
18167 (defcustom org-agenda-inhibit-startup nil
18168 "Inhibit startup when preparing agenda buffers.
18169 When this variable is t, the initialization of the Org agenda
18170 buffers is inhibited: e.g. the visibility state is not set, the
18171 tables are not re-aligned, etc."
18172 :type 'boolean
18173 :version "24.3"
18174 :group 'org-agenda)
18176 (defcustom org-agenda-ignore-properties nil
18177 "Avoid updating text properties when building the agenda.
18178 Properties are used to prepare buffers for effort estimates,
18179 appointments, statistics and subtree-local categories.
18180 If you don't use these in the agenda, you can add them to this
18181 list and agenda building will be a bit faster.
18182 The value is a list, with zero or more of the symbols `effort', `appt',
18183 `stats' or `category'."
18184 :type '(set :greedy t
18185 (const effort)
18186 (const appt)
18187 (const stats)
18188 (const category))
18189 :version "26.1"
18190 :package-version '(Org . "8.3")
18191 :group 'org-agenda)
18193 ;;;; Files
18195 (defun org-save-all-org-buffers ()
18196 "Save all Org buffers without user confirmation."
18197 (interactive)
18198 (message "Saving all Org buffers...")
18199 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18200 (when (featurep 'org-id) (org-id-locations-save))
18201 (message "Saving all Org buffers... done"))
18203 (defun org-revert-all-org-buffers ()
18204 "Revert all Org buffers.
18205 Prompt for confirmation when there are unsaved changes.
18206 Be sure you know what you are doing before letting this function
18207 overwrite your changes.
18209 This function is useful in a setup where one tracks org files
18210 with a version control system, to revert on one machine after pulling
18211 changes from another. I believe the procedure must be like this:
18213 1. M-x org-save-all-org-buffers
18214 2. Pull changes from the other machine, resolve conflicts
18215 3. M-x org-revert-all-org-buffers"
18216 (interactive)
18217 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18218 (user-error "Abort"))
18219 (save-excursion
18220 (save-window-excursion
18221 (dolist (b (buffer-list))
18222 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18223 (with-current-buffer b buffer-file-name))
18224 (pop-to-buffer-same-window b)
18225 (revert-buffer t 'no-confirm)))
18226 (when (and (featurep 'org-id) org-id-track-globally)
18227 (org-id-locations-load)))))
18229 ;;;; Agenda files
18231 ;;;###autoload
18232 (defun org-switchb (&optional arg)
18233 "Switch between Org buffers.
18235 With `\\[universal-argument]' prefix, restrict available buffers to files.
18237 With `\\[universal-argument] \\[universal-argument]' \
18238 prefix, restrict available buffers to agenda files."
18239 (interactive "P")
18240 (let ((blist (org-buffer-list
18241 (cond ((equal arg '(4)) 'files)
18242 ((equal arg '(16)) 'agenda)))))
18243 (pop-to-buffer-same-window
18244 (completing-read "Org buffer: "
18245 (mapcar #'list (mapcar #'buffer-name blist))
18246 nil t))))
18248 (defun org-buffer-list (&optional predicate exclude-tmp)
18249 "Return a list of Org buffers.
18250 PREDICATE can be `export', `files' or `agenda'.
18252 export restrict the list to Export buffers.
18253 files restrict the list to buffers visiting Org files.
18254 agenda restrict the list to buffers visiting agenda files.
18256 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18257 (let* ((bfn nil)
18258 (agenda-files (and (eq predicate 'agenda)
18259 (mapcar 'file-truename (org-agenda-files t))))
18260 (filter
18261 (cond
18262 ((eq predicate 'files)
18263 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18264 ((eq predicate 'export)
18265 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18266 ((eq predicate 'agenda)
18267 (lambda (b)
18268 (with-current-buffer b
18269 (and (derived-mode-p 'org-mode)
18270 (setq bfn (buffer-file-name b))
18271 (member (file-truename bfn) agenda-files)))))
18272 (t (lambda (b) (with-current-buffer b
18273 (or (derived-mode-p 'org-mode)
18274 (string-match "\\*Org .*Export"
18275 (buffer-name b)))))))))
18276 (delq nil
18277 (mapcar
18278 (lambda(b)
18279 (if (and (funcall filter b)
18280 (or (not exclude-tmp)
18281 (not (string-match "tmp" (buffer-name b)))))
18283 nil))
18284 (buffer-list)))))
18286 (defun org-agenda-files (&optional unrestricted archives)
18287 "Get the list of agenda files.
18288 Optional UNRESTRICTED means return the full list even if a restriction
18289 is currently in place.
18290 When ARCHIVES is t, include all archive files that are really being
18291 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18292 `org-agenda-archives-mode' is t."
18293 (let ((files
18294 (cond
18295 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18296 ((stringp org-agenda-files) (org-read-agenda-file-list))
18297 ((listp org-agenda-files) org-agenda-files)
18298 (t (error "Invalid value of `org-agenda-files'")))))
18299 (setq files (apply 'append
18300 (mapcar (lambda (f)
18301 (if (file-directory-p f)
18302 (directory-files
18303 f t org-agenda-file-regexp)
18304 (list f)))
18305 files)))
18306 (when org-agenda-skip-unavailable-files
18307 (setq files (delq nil
18308 (mapcar (function
18309 (lambda (file)
18310 (and (file-readable-p file) file)))
18311 files))))
18312 (when (or (eq archives t)
18313 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18314 (setq files (org-add-archive-files files)))
18315 files))
18317 (defun org-agenda-file-p (&optional file)
18318 "Return non-nil, if FILE is an agenda file.
18319 If FILE is omitted, use the file associated with the current
18320 buffer."
18321 (let ((fname (or file (buffer-file-name))))
18322 (and fname
18323 (member (file-truename fname)
18324 (mapcar #'file-truename (org-agenda-files t))))))
18326 (defun org-edit-agenda-file-list ()
18327 "Edit the list of agenda files.
18328 Depending on setup, this either uses customize to edit the variable
18329 `org-agenda-files', or it visits the file that is holding the list. In the
18330 latter case, the buffer is set up in a way that saving it automatically kills
18331 the buffer and restores the previous window configuration."
18332 (interactive)
18333 (if (stringp org-agenda-files)
18334 (let ((cw (current-window-configuration)))
18335 (find-file org-agenda-files)
18336 (setq-local org-window-configuration cw)
18337 (add-hook 'after-save-hook
18338 (lambda ()
18339 (set-window-configuration
18340 (prog1 org-window-configuration
18341 (kill-buffer (current-buffer))))
18342 (org-install-agenda-files-menu)
18343 (message "New agenda file list installed"))
18344 nil 'local)
18345 (message "%s" (substitute-command-keys
18346 "Edit list and finish with \\[save-buffer]")))
18347 (customize-variable 'org-agenda-files)))
18349 (defun org-store-new-agenda-file-list (list)
18350 "Set new value for the agenda file list and save it correctly."
18351 (if (stringp org-agenda-files)
18352 (let ((fe (org-read-agenda-file-list t)) b u)
18353 (while (setq b (find-buffer-visiting org-agenda-files))
18354 (kill-buffer b))
18355 (with-temp-file org-agenda-files
18356 (insert
18357 (mapconcat
18358 (lambda (f) ;; Keep un-expanded entries.
18359 (if (setq u (assoc f fe))
18360 (cdr u)
18362 list "\n")
18363 "\n")))
18364 (let ((org-mode-hook nil) (org-inhibit-startup t)
18365 (org-insert-mode-line-in-empty-file nil))
18366 (setq org-agenda-files list)
18367 (customize-save-variable 'org-agenda-files org-agenda-files))))
18369 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18370 "Read the list of agenda files from a file.
18371 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18372 filenames, used by `org-store-new-agenda-file-list' to write back
18373 un-expanded file names."
18374 (when (file-directory-p org-agenda-files)
18375 (error "`org-agenda-files' cannot be a single directory"))
18376 (when (stringp org-agenda-files)
18377 (with-temp-buffer
18378 (insert-file-contents org-agenda-files)
18379 (mapcar
18380 (lambda (f)
18381 (let ((e (expand-file-name (substitute-in-file-name f)
18382 org-directory)))
18383 (if pair-with-expansion
18384 (cons e f)
18385 e)))
18386 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18388 ;;;###autoload
18389 (defun org-cycle-agenda-files ()
18390 "Cycle through the files in `org-agenda-files'.
18391 If the current buffer visits an agenda file, find the next one in the list.
18392 If the current buffer does not, find the first agenda file."
18393 (interactive)
18394 (let* ((fs (or (org-agenda-files t)
18395 (user-error "No agenda files")))
18396 (files (copy-sequence fs))
18397 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18398 file)
18399 (when tcf
18400 (while (and (setq file (pop files))
18401 (not (equal (file-truename file) tcf)))))
18402 (find-file (car (or files fs)))
18403 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18405 (defun org-agenda-file-to-front (&optional to-end)
18406 "Move/add the current file to the top of the agenda file list.
18407 If the file is not present in the list, it is added to the front. If it is
18408 present, it is moved there. With optional argument TO-END, add/move to the
18409 end of the list."
18410 (interactive "P")
18411 (let ((org-agenda-skip-unavailable-files nil)
18412 (file-alist (mapcar (lambda (x)
18413 (cons (file-truename x) x))
18414 (org-agenda-files t)))
18415 (ctf (file-truename
18416 (or buffer-file-name
18417 (user-error "Please save the current buffer to a file"))))
18418 x had)
18419 (setq x (assoc ctf file-alist) had x)
18421 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18422 (if to-end
18423 (setq file-alist (append (delq x file-alist) (list x)))
18424 (setq file-alist (cons x (delq x file-alist))))
18425 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18426 (org-install-agenda-files-menu)
18427 (message "File %s to %s of agenda file list"
18428 (if had "moved" "added") (if to-end "end" "front"))))
18430 (defun org-remove-file (&optional file)
18431 "Remove current file from the list of files in variable `org-agenda-files'.
18432 These are the files which are being checked for agenda entries.
18433 Optional argument FILE means use this file instead of the current."
18434 (interactive)
18435 (let* ((org-agenda-skip-unavailable-files nil)
18436 (file (or file buffer-file-name
18437 (user-error "Current buffer does not visit a file")))
18438 (true-file (file-truename file))
18439 (afile (abbreviate-file-name file))
18440 (files (delq nil (mapcar
18441 (lambda (x)
18442 (unless (equal true-file
18443 (file-truename x))
18445 (org-agenda-files t)))))
18446 (if (not (= (length files) (length (org-agenda-files t))))
18447 (progn
18448 (org-store-new-agenda-file-list files)
18449 (org-install-agenda-files-menu)
18450 (message "Removed from Org Agenda list: %s" afile))
18451 (message "File was not in list: %s (not removed)" afile))))
18453 (defun org-file-menu-entry (file)
18454 (vector file (list 'find-file file) t))
18456 (defun org-check-agenda-file (file)
18457 "Make sure FILE exists. If not, ask user what to do."
18458 (unless (file-exists-p file)
18459 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18460 (abbreviate-file-name file))
18461 (let ((r (downcase (read-char-exclusive))))
18462 (cond
18463 ((equal r ?r)
18464 (org-remove-file file)
18465 (throw 'nextfile t))
18466 (t (user-error "Abort"))))))
18468 (defun org-get-agenda-file-buffer (file)
18469 "Get an agenda buffer visiting FILE.
18470 If the buffer needs to be created, add it to the list of buffers
18471 which might be released later."
18472 (let ((buf (org-find-base-buffer-visiting file)))
18473 (if buf
18474 buf ; just return it
18475 ;; Make a new buffer and remember it
18476 (setq buf (find-file-noselect file))
18477 (when buf (push buf org-agenda-new-buffers))
18478 buf)))
18480 (defun org-release-buffers (blist)
18481 "Release all buffers in list, asking the user for confirmation when needed.
18482 When a buffer is unmodified, it is just killed. When modified, it is saved
18483 \(if the user agrees) and then killed."
18484 (let (file)
18485 (dolist (buf blist)
18486 (setq file (buffer-file-name buf))
18487 (when (and (buffer-modified-p buf)
18488 file
18489 (y-or-n-p (format "Save file %s? " file)))
18490 (with-current-buffer buf (save-buffer)))
18491 (kill-buffer buf))))
18493 (defun org-agenda-prepare-buffers (files)
18494 "Create buffers for all agenda files, protect archived trees and comments."
18495 (interactive)
18496 (let ((pa '(:org-archived t))
18497 (pc '(:org-comment t))
18498 (pall '(:org-archived t :org-comment t))
18499 (inhibit-read-only t)
18500 (org-inhibit-startup org-agenda-inhibit-startup)
18501 (rea (concat ":" org-archive-tag ":"))
18502 re pos)
18503 (setq org-tag-alist-for-agenda nil
18504 org-tag-groups-alist-for-agenda nil)
18505 (save-excursion
18506 (save-restriction
18507 (dolist (file files)
18508 (catch 'nextfile
18509 (if (bufferp file)
18510 (set-buffer file)
18511 (org-check-agenda-file file)
18512 (set-buffer (org-get-agenda-file-buffer file)))
18513 (widen)
18514 (org-set-regexps-and-options 'tags-only)
18515 (setq pos (point))
18516 (or (memq 'category org-agenda-ignore-properties)
18517 (org-refresh-category-properties))
18518 (or (memq 'stats org-agenda-ignore-properties)
18519 (org-refresh-stats-properties))
18520 (or (memq 'effort org-agenda-ignore-properties)
18521 (org-refresh-effort-properties))
18522 (or (memq 'appt org-agenda-ignore-properties)
18523 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18524 (setq org-todo-keywords-for-agenda
18525 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18526 (setq org-done-keywords-for-agenda
18527 (append org-done-keywords-for-agenda org-done-keywords))
18528 (setq org-todo-keyword-alist-for-agenda
18529 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18530 (setq org-tag-alist-for-agenda
18531 (org-uniquify
18532 (append org-tag-alist-for-agenda
18533 org-current-tag-alist)))
18534 ;; Merge current file's tag groups into global
18535 ;; `org-tag-groups-alist-for-agenda'.
18536 (when org-group-tags
18537 (dolist (alist org-tag-groups-alist)
18538 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18539 (if old
18540 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18541 (push alist org-tag-groups-alist-for-agenda)))))
18542 (org-with-silent-modifications
18543 (save-excursion
18544 (remove-text-properties (point-min) (point-max) pall)
18545 (when org-agenda-skip-archived-trees
18546 (goto-char (point-min))
18547 (while (re-search-forward rea nil t)
18548 (when (org-at-heading-p t)
18549 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18550 (goto-char (point-min))
18551 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18552 (while (re-search-forward re nil t)
18553 (when (save-match-data (org-in-commented-heading-p t))
18554 (add-text-properties
18555 (match-beginning 0) (org-end-of-subtree t) pc)))))
18556 (goto-char pos)))))
18557 (setq org-todo-keywords-for-agenda
18558 (org-uniquify org-todo-keywords-for-agenda))
18559 (setq org-todo-keyword-alist-for-agenda
18560 (org-uniquify org-todo-keyword-alist-for-agenda))))
18563 ;;;; CDLaTeX minor mode
18565 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18566 "Keymap for the minor `org-cdlatex-mode'.")
18568 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18569 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18570 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18571 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18572 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18574 (defvar org-cdlatex-texmathp-advice-is-done nil
18575 "Flag remembering if we have applied the advice to texmathp already.")
18577 (define-minor-mode org-cdlatex-mode
18578 "Toggle the minor `org-cdlatex-mode'.
18579 This mode supports entering LaTeX environment and math in LaTeX fragments
18580 in Org mode.
18581 \\{org-cdlatex-mode-map}"
18582 nil " OCDL" nil
18583 (when org-cdlatex-mode
18584 (require 'cdlatex)
18585 (run-hooks 'cdlatex-mode-hook)
18586 (cdlatex-compute-tables))
18587 (unless org-cdlatex-texmathp-advice-is-done
18588 (setq org-cdlatex-texmathp-advice-is-done t)
18589 (defadvice texmathp (around org-math-always-on activate)
18590 "Always return t in Org buffers.
18591 This is because we want to insert math symbols without dollars even outside
18592 the LaTeX math segments. If Org mode thinks that point is actually inside
18593 an embedded LaTeX fragment, let `texmathp' do its job.
18594 `\\[org-cdlatex-mode-map]'"
18595 (interactive)
18596 (let (p)
18597 (cond
18598 ((not (derived-mode-p 'org-mode)) ad-do-it)
18599 ((eq this-command 'cdlatex-math-symbol)
18600 (setq ad-return-value t
18601 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18603 (let ((p (org-inside-LaTeX-fragment-p)))
18604 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18605 (setq ad-return-value t
18606 texmathp-why '("Org mode embedded math" . 0))
18607 (when p ad-do-it)))))))))
18609 (defun turn-on-org-cdlatex ()
18610 "Unconditionally turn on `org-cdlatex-mode'."
18611 (org-cdlatex-mode 1))
18613 (defun org-try-cdlatex-tab ()
18614 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18615 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18616 - inside a LaTeX fragment, or
18617 - after the first word in a line, where an abbreviation expansion could
18618 insert a LaTeX environment."
18619 (when org-cdlatex-mode
18620 (cond
18621 ;; Before any word on the line: No expansion possible.
18622 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18623 ;; Just after first word on the line: Expand it. Make sure it
18624 ;; cannot happen on headlines, though.
18625 ((save-excursion
18626 (skip-chars-backward "a-zA-Z0-9*")
18627 (skip-chars-backward " \t")
18628 (and (bolp) (not (org-at-heading-p))))
18629 (cdlatex-tab) t)
18630 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18632 (defun org-cdlatex-underscore-caret (&optional _arg)
18633 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18634 Revert to the normal definition outside of these fragments."
18635 (interactive "P")
18636 (if (org-inside-LaTeX-fragment-p)
18637 (call-interactively 'cdlatex-sub-superscript)
18638 (let (org-cdlatex-mode)
18639 (call-interactively (key-binding (vector last-input-event))))))
18641 (defun org-cdlatex-math-modify (&optional _arg)
18642 "Execute `cdlatex-math-modify' in LaTeX fragments.
18643 Revert to the normal definition outside of these fragments."
18644 (interactive "P")
18645 (if (org-inside-LaTeX-fragment-p)
18646 (call-interactively 'cdlatex-math-modify)
18647 (let (org-cdlatex-mode)
18648 (call-interactively (key-binding (vector last-input-event))))))
18650 (defun org-cdlatex-environment-indent (&optional environment item)
18651 "Execute `cdlatex-environment' and indent the inserted environment.
18653 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18655 The inserted environment is indented to current indentation
18656 unless point is at the beginning of the line, in which the
18657 environment remains unintended."
18658 (interactive)
18659 ;; cdlatex-environment always return nil. Therefore, capture output
18660 ;; first and determine if an environment was selected.
18661 (let* ((beg (point-marker))
18662 (end (copy-marker (point) t))
18663 (inserted (progn
18664 (ignore-errors (cdlatex-environment environment item))
18665 (< beg end)))
18666 ;; Figure out how many lines to move forward after the
18667 ;; environment has been inserted.
18668 (lines (when inserted
18669 (save-excursion
18670 (- (cl-loop while (< beg (point))
18671 with x = 0
18672 do (forward-line -1)
18673 (cl-incf x)
18674 finally return x)
18675 (if (progn (goto-char beg)
18676 (and (progn (skip-chars-forward " \t") (eolp))
18677 (progn (skip-chars-backward " \t") (bolp))))
18678 1 0)))))
18679 (env (org-trim (delete-and-extract-region beg end))))
18680 (when inserted
18681 ;; Get indentation of next line unless at column 0.
18682 (let ((ind (if (bolp) 0
18683 (save-excursion
18684 (org-return-indent)
18685 (prog1 (org-get-indentation)
18686 (when (progn (skip-chars-forward " \t") (eolp))
18687 (delete-region beg (point)))))))
18688 (bol (progn (skip-chars-backward " \t") (bolp))))
18689 ;; Insert a newline before environment unless at column zero
18690 ;; to "escape" the current line. Insert a newline if
18691 ;; something is one the same line as \end{ENVIRONMENT}.
18692 (insert
18693 (concat (unless bol "\n") env
18694 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18695 (unless (zerop ind)
18696 (save-excursion
18697 (goto-char beg)
18698 (while (< (point) end)
18699 (unless (eolp) (indent-line-to ind))
18700 (forward-line))))
18701 (goto-char beg)
18702 (forward-line lines)
18703 (indent-line-to ind)))
18704 (set-marker beg nil)
18705 (set-marker end nil)))
18708 ;;;; LaTeX fragments
18710 (defun org-inside-LaTeX-fragment-p ()
18711 "Test if point is inside a LaTeX fragment.
18712 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18713 sequence appearing also before point.
18714 Even though the matchers for math are configurable, this function assumes
18715 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18716 delimiters are skipped when they have been removed by customization.
18717 The return value is nil, or a cons cell with the delimiter and the
18718 position of this delimiter.
18720 This function does a reasonably good job, but can locally be fooled by
18721 for example currency specifications. For example it will assume being in
18722 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18723 fragments that are properly closed, but during editing, we have to live
18724 with the uncertainty caused by missing closing delimiters. This function
18725 looks only before point, not after."
18726 (catch 'exit
18727 (let ((pos (point))
18728 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18729 (lim (save-excursion (org-backward-paragraph) (point)))
18730 dd-on str (start 0) m re)
18731 (goto-char pos)
18732 (when dodollar
18733 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18734 re (nth 1 (assoc "$" org-latex-regexps)))
18735 (while (string-match re str start)
18736 (cond
18737 ((= (match-end 0) (length str))
18738 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18739 ((= (match-end 0) (- (length str) 5))
18740 (throw 'exit nil))
18741 (t (setq start (match-end 0))))))
18742 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18743 (goto-char pos)
18744 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18745 (and (match-beginning 2) (throw 'exit nil))
18746 ;; count $$
18747 (while (re-search-backward "\\$\\$" lim t)
18748 (setq dd-on (not dd-on)))
18749 (goto-char pos)
18750 (when dd-on (cons "$$" m))))))
18752 (defun org-inside-latex-macro-p ()
18753 "Is point inside a LaTeX macro or its arguments?"
18754 (save-match-data
18755 (org-in-regexp
18756 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18758 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18759 "Build an overlay between BEG and END using IMAGE file.
18760 Argument IMAGETYPE is the extension of the displayed image,
18761 as a string. It defaults to \"png\"."
18762 (let ((ov (make-overlay beg end))
18763 (imagetype (or (intern imagetype) 'png)))
18764 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18765 (overlay-put ov 'evaporate t)
18766 (overlay-put ov
18767 'modification-hooks
18768 (list (lambda (o _flag _beg _end &optional _l)
18769 (delete-overlay o))))
18770 (overlay-put ov
18771 'display
18772 (list 'image :type imagetype :file image :ascent 'center))))
18774 (defun org--list-latex-overlays (&optional beg end)
18775 "List all Org LaTeX overlays in current buffer.
18776 Limit to overlays between BEG and END when those are provided."
18777 (cl-remove-if-not
18778 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18779 (overlays-in (or beg (point-min)) (or end (point-max)))))
18781 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18782 "Remove all overlays with LaTeX fragment images in current buffer.
18783 When optional arguments BEG and END are non-nil, remove all
18784 overlays between them instead. Return a non-nil value when some
18785 overlays were removed, nil otherwise."
18786 (let ((overlays (org--list-latex-overlays beg end)))
18787 (mapc #'delete-overlay overlays)
18788 overlays))
18790 (defun org-toggle-latex-fragment (&optional arg)
18791 "Preview the LaTeX fragment at point, or all locally or globally.
18793 If the cursor is on a LaTeX fragment, create the image and overlay
18794 it over the source code, if there is none. Remove it otherwise.
18795 If there is no fragment at point, display all fragments in the
18796 current section.
18798 With prefix ARG, preview or clear image for all fragments in the
18799 current subtree or in the whole buffer when used before the first
18800 headline. With a prefix ARG `\\[universal-argument] \
18801 \\[universal-argument]' preview or clear images
18802 for all fragments in the buffer."
18803 (interactive "P")
18804 (when (display-graphic-p)
18805 (catch 'exit
18806 (save-excursion
18807 (let (beg end msg)
18808 (cond
18809 ((or (equal arg '(16))
18810 (and (equal arg '(4))
18811 (org-with-limited-levels (org-before-first-heading-p))))
18812 (if (org-remove-latex-fragment-image-overlays)
18813 (progn (message "LaTeX fragments images removed from buffer")
18814 (throw 'exit nil))
18815 (setq msg "Creating images for buffer...")))
18816 ((equal arg '(4))
18817 (org-with-limited-levels (org-back-to-heading t))
18818 (setq beg (point))
18819 (setq end (progn (org-end-of-subtree t) (point)))
18820 (if (org-remove-latex-fragment-image-overlays beg end)
18821 (progn
18822 (message "LaTeX fragment images removed from subtree")
18823 (throw 'exit nil))
18824 (setq msg "Creating images for subtree...")))
18825 ((let ((datum (org-element-context)))
18826 (when (memq (org-element-type datum)
18827 '(latex-environment latex-fragment))
18828 (setq beg (org-element-property :begin datum))
18829 (setq end (org-element-property :end datum))
18830 (if (org-remove-latex-fragment-image-overlays beg end)
18831 (progn (message "LaTeX fragment image removed")
18832 (throw 'exit nil))
18833 (setq msg "Creating image...")))))
18835 (org-with-limited-levels
18836 (setq beg (if (org-at-heading-p) (line-beginning-position)
18837 (outline-previous-heading)
18838 (point)))
18839 (setq end (progn (outline-next-heading) (point)))
18840 (if (org-remove-latex-fragment-image-overlays beg end)
18841 (progn
18842 (message "LaTeX fragment images removed from section")
18843 (throw 'exit nil))
18844 (setq msg "Creating images for section...")))))
18845 (let ((file (buffer-file-name (buffer-base-buffer))))
18846 (org-format-latex
18847 (concat org-preview-latex-image-directory "org-ltximg")
18848 beg end
18849 ;; Emacs cannot overlay images from remote hosts. Create
18850 ;; it in `temporary-file-directory' instead.
18851 (if (or (not file) (file-remote-p file))
18852 temporary-file-directory
18853 default-directory)
18854 'overlays msg 'forbuffer org-preview-latex-default-process))
18855 (message (concat msg "done")))))))
18857 (defun org-format-latex
18858 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18859 "Replace LaTeX fragments with links to an image.
18861 The function takes care of creating the replacement image.
18863 Only consider fragments between BEG and END when those are
18864 provided.
18866 When optional argument OVERLAYS is non-nil, display the image on
18867 top of the fragment instead of replacing it.
18869 PROCESSING-TYPE is the conversion method to use, as a symbol.
18871 Some of the options can be changed using the variable
18872 `org-format-latex-options', which see."
18873 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18874 (unless (eq processing-type 'verbatim)
18875 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18876 (cnt 0)
18877 checkdir-flag)
18878 (goto-char (or beg (point-min)))
18879 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18880 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18881 (overlay-recenter (or end (point-max))))
18882 (while (re-search-forward math-regexp end t)
18883 (unless (and overlays
18884 (eq (get-char-property (point) 'org-overlay-type)
18885 'org-latex-overlay))
18886 (let* ((context (org-element-context))
18887 (type (org-element-type context)))
18888 (when (memq type '(latex-environment latex-fragment))
18889 (let ((block-type (eq type 'latex-environment))
18890 (value (org-element-property :value context))
18891 (beg (org-element-property :begin context))
18892 (end (save-excursion
18893 (goto-char (org-element-property :end context))
18894 (skip-chars-backward " \r\t\n")
18895 (point))))
18896 (cond
18897 ((eq processing-type 'mathjax)
18898 ;; Prepare for MathJax processing.
18899 (if (not (string-match "\\`\\$\\$?" value))
18900 (goto-char end)
18901 (delete-region beg end)
18902 (if (string= (match-string 0 value) "$$")
18903 (insert "\\[" (substring value 2 -2) "\\]")
18904 (insert "\\(" (substring value 1 -1) "\\)"))))
18905 ((assq processing-type org-preview-latex-process-alist)
18906 ;; Process to an image.
18907 (cl-incf cnt)
18908 (goto-char beg)
18909 (let* ((processing-info
18910 (cdr (assq processing-type org-preview-latex-process-alist)))
18911 (face (face-at-point))
18912 ;; Get the colors from the face at point.
18914 (let ((color (plist-get org-format-latex-options
18915 :foreground)))
18916 (if (and forbuffer (eq color 'auto))
18917 (face-attribute face :foreground nil 'default)
18918 color)))
18920 (let ((color (plist-get org-format-latex-options
18921 :background)))
18922 (if (and forbuffer (eq color 'auto))
18923 (face-attribute face :background nil 'default)
18924 color)))
18925 (hash (sha1 (prin1-to-string
18926 (list org-format-latex-header
18927 org-latex-default-packages-alist
18928 org-latex-packages-alist
18929 org-format-latex-options
18930 forbuffer value fg bg))))
18931 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18932 (absprefix (expand-file-name prefix dir))
18933 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18934 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18935 (sep (and block-type "\n\n"))
18936 (link (concat sep "[[file:" linkfile "]]" sep))
18937 (options
18938 (org-combine-plists
18939 org-format-latex-options
18940 `(:foreground ,fg :background ,bg))))
18941 (when msg (message msg cnt))
18942 (unless checkdir-flag ; Ensure the directory exists.
18943 (setq checkdir-flag t)
18944 (let ((todir (file-name-directory absprefix)))
18945 (unless (file-directory-p todir)
18946 (make-directory todir t))))
18947 (unless (file-exists-p movefile)
18948 (org-create-formula-image
18949 value movefile options forbuffer processing-type))
18950 (if overlays
18951 (progn
18952 (dolist (o (overlays-in beg end))
18953 (when (eq (overlay-get o 'org-overlay-type)
18954 'org-latex-overlay)
18955 (delete-overlay o)))
18956 (org--format-latex-make-overlay beg end movefile imagetype)
18957 (goto-char end))
18958 (delete-region beg end)
18959 (insert
18960 (org-add-props link
18961 (list 'org-latex-src
18962 (replace-regexp-in-string "\"" "" value)
18963 'org-latex-src-embed-type
18964 (if block-type 'paragraph 'character)))))))
18965 ((eq processing-type 'mathml)
18966 ;; Process to MathML.
18967 (unless (org-format-latex-mathml-available-p)
18968 (user-error "LaTeX to MathML converter not configured"))
18969 (cl-incf cnt)
18970 (when msg (message msg cnt))
18971 (goto-char beg)
18972 (delete-region beg end)
18973 (insert (org-format-latex-as-mathml
18974 value block-type prefix dir)))
18976 (error "Unknown conversion process %s for LaTeX fragments"
18977 processing-type)))))))))))
18979 (defun org-create-math-formula (latex-frag &optional mathml-file)
18980 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18981 Use `org-latex-to-mathml-convert-command'. If the conversion is
18982 sucessful, return the portion between \"<math...> </math>\"
18983 elements otherwise return nil. When MATHML-FILE is specified,
18984 write the results in to that file. When invoked as an
18985 interactive command, prompt for LATEX-FRAG, with initial value
18986 set to the current active region and echo the results for user
18987 inspection."
18988 (interactive (list (let ((frag (when (org-region-active-p)
18989 (buffer-substring-no-properties
18990 (region-beginning) (region-end)))))
18991 (read-string "LaTeX Fragment: " frag nil frag))))
18992 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18993 (let* ((tmp-in-file
18994 (let ((file (file-relative-name
18995 (make-temp-name (expand-file-name "ltxmathml-in")))))
18996 (write-region latex-frag nil file)
18997 file))
18998 (tmp-out-file (file-relative-name
18999 (make-temp-name (expand-file-name "ltxmathml-out"))))
19000 (cmd (format-spec
19001 org-latex-to-mathml-convert-command
19002 `((?j . ,(and org-latex-to-mathml-jar-file
19003 (shell-quote-argument
19004 (expand-file-name
19005 org-latex-to-mathml-jar-file))))
19006 (?I . ,(shell-quote-argument tmp-in-file))
19007 (?i . ,latex-frag)
19008 (?o . ,(shell-quote-argument tmp-out-file)))))
19009 mathml shell-command-output)
19010 (when (called-interactively-p 'any)
19011 (unless (org-format-latex-mathml-available-p)
19012 (user-error "LaTeX to MathML converter not configured")))
19013 (message "Running %s" cmd)
19014 (setq shell-command-output (shell-command-to-string cmd))
19015 (setq mathml
19016 (when (file-readable-p tmp-out-file)
19017 (with-current-buffer (find-file-noselect tmp-out-file t)
19018 (goto-char (point-min))
19019 (when (re-search-forward
19020 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19021 (regexp-quote
19022 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19023 nil t)
19024 (prog1 (match-string 0) (kill-buffer))))))
19025 (cond
19026 (mathml
19027 (setq mathml
19028 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19029 (when mathml-file
19030 (write-region mathml nil mathml-file))
19031 (when (called-interactively-p 'any)
19032 (message mathml)))
19033 ((message "LaTeX to MathML conversion failed")
19034 (message shell-command-output)))
19035 (delete-file tmp-in-file)
19036 (when (file-exists-p tmp-out-file)
19037 (delete-file tmp-out-file))
19038 mathml))
19040 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19041 prefix &optional dir)
19042 "Use `org-create-math-formula' but check local cache first."
19043 (let* ((absprefix (expand-file-name prefix dir))
19044 (print-length nil) (print-level nil)
19045 (formula-id (concat
19046 "formula-"
19047 (sha1
19048 (prin1-to-string
19049 (list latex-frag
19050 org-latex-to-mathml-convert-command)))))
19051 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19052 (formula-cache-dir (file-name-directory formula-cache)))
19054 (unless (file-directory-p formula-cache-dir)
19055 (make-directory formula-cache-dir t))
19057 (unless (file-exists-p formula-cache)
19058 (org-create-math-formula latex-frag formula-cache))
19060 (if (file-exists-p formula-cache)
19061 ;; Successful conversion. Return the link to MathML file.
19062 (org-add-props
19063 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19064 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19065 'org-latex-src-embed-type (if latex-frag-type
19066 'paragraph 'character)))
19067 ;; Failed conversion. Return the LaTeX fragment verbatim
19068 latex-frag)))
19070 (defun org--get-display-dpi ()
19071 "Get the DPI of the display.
19072 The function assumes that the display has the same pixel width in
19073 the horizontal and vertical directions."
19074 (if (display-graphic-p)
19075 (round (/ (display-pixel-height)
19076 (/ (display-mm-height) 25.4)))
19077 (error "Attempt to calculate the dpi of a non-graphic display")))
19079 (defun org-create-formula-image
19080 (string tofile options buffer &optional processing-type)
19081 "Create an image from LaTeX source using external processes.
19083 The LaTeX STRING is saved to a temporary LaTeX file, then
19084 converted to an image file by process PROCESSING-TYPE defined in
19085 `org-preview-latex-process-alist'. A nil value defaults to
19086 `org-preview-latex-default-process'.
19088 The generated image file is eventually moved to TOFILE.
19090 The OPTIONS argument controls the size, foreground color and
19091 background color of the generated image.
19093 When BUFFER non-nil, this function is used for LaTeX previewing.
19094 Otherwise, it is used to deal with LaTeX snippets showed in
19095 a HTML file."
19096 (let* ((processing-type (or processing-type
19097 org-preview-latex-default-process))
19098 (processing-info
19099 (cdr (assq processing-type org-preview-latex-process-alist)))
19100 (programs (plist-get processing-info :programs))
19101 (error-message (or (plist-get processing-info :message) ""))
19102 (use-xcolor (plist-get processing-info :use-xcolor))
19103 (image-input-type (plist-get processing-info :image-input-type))
19104 (image-output-type (plist-get processing-info :image-output-type))
19105 (post-clean (or (plist-get processing-info :post-clean)
19106 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19107 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19108 (latex-header
19109 (or (plist-get processing-info :latex-header)
19110 (org-latex-make-preamble
19111 (org-export-get-environment (org-export-get-backend 'latex))
19112 org-format-latex-header
19113 'snippet)))
19114 (latex-compiler (plist-get processing-info :latex-compiler))
19115 (image-converter (plist-get processing-info :image-converter))
19116 (tmpdir temporary-file-directory)
19117 (texfilebase (make-temp-name
19118 (expand-file-name "orgtex" tmpdir)))
19119 (texfile (concat texfilebase ".tex"))
19120 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19121 '(1.0 . 1.0)))
19122 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19123 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19124 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19125 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19126 "Black"))
19127 (bg (or (plist-get options (if buffer :background :html-background))
19128 "Transparent"))
19129 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19130 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19131 (dolist (program programs)
19132 (org-check-external-command program error-message))
19133 (if use-xcolor
19134 (progn (if (eq fg 'default)
19135 (setq fg (org-latex-color :foreground))
19136 (setq fg (org-latex-color-format fg)))
19137 (if (eq bg 'default)
19138 (setq bg (org-latex-color :background))
19139 (setq bg (org-latex-color-format
19140 (if (string= bg "Transparent") "white" bg))))
19141 (with-temp-file texfile
19142 (insert latex-header)
19143 (insert "\n\\begin{document}\n"
19144 "\\definecolor{fg}{rgb}{" fg "}\n"
19145 "\\definecolor{bg}{rgb}{" bg "}\n"
19146 "\n\\pagecolor{bg}\n"
19147 "\n{\\color{fg}\n"
19148 string
19149 "\n}\n"
19150 "\n\\end{document}\n")))
19151 (if (eq fg 'default)
19152 (setq fg (org-dvipng-color :foreground))
19153 (unless (string= fg "Transparent")
19154 (setq fg (org-dvipng-color-format fg))))
19155 (if (eq bg 'default)
19156 (setq bg (org-dvipng-color :background))
19157 (unless (string= bg "Transparent")
19158 (setq bg (org-dvipng-color-format bg))))
19159 (with-temp-file texfile
19160 (insert latex-header)
19161 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19163 (let* ((err-msg (format "Please adjust `%s' part of \
19164 `org-preview-latex-process-alist'."
19165 processing-type))
19166 (image-input-file
19167 (org-compile-file
19168 texfile latex-compiler image-input-type err-msg log-buf))
19169 (image-output-file
19170 (org-compile-file
19171 image-input-file image-converter image-output-type err-msg log-buf
19172 `((?F . ,(shell-quote-argument fg))
19173 (?B . ,(shell-quote-argument bg))
19174 (?D . ,(shell-quote-argument (format "%s" dpi)))
19175 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19176 (copy-file image-output-file tofile 'replace)
19177 (dolist (e post-clean)
19178 (when (file-exists-p (concat texfilebase e))
19179 (delete-file (concat texfilebase e))))
19180 image-output-file)))
19182 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19183 "Fill a LaTeX header template TPL.
19184 In the template, the following place holders will be recognized:
19186 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19187 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19188 [PACKAGES] \\usepackage statements for PKG
19189 [NO-PACKAGES] do not include PKG
19190 [EXTRA] the string EXTRA
19191 [NO-EXTRA] do not include EXTRA
19193 For backward compatibility, if both the positive and the negative place
19194 holder is missing, the positive one (without the \"NO-\") will be
19195 assumed to be present at the end of the template.
19196 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19197 EXTRA is a string.
19198 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19199 (let (rpl (end ""))
19200 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19201 (setq rpl (if (or (match-end 1) (not def-pkg))
19202 "" (org-latex-packages-to-string def-pkg snippets-p t))
19203 tpl (replace-match rpl t t tpl))
19204 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19206 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19207 (setq rpl (if (or (match-end 1) (not pkg))
19208 "" (org-latex-packages-to-string pkg snippets-p t))
19209 tpl (replace-match rpl t t tpl))
19210 (when pkg (setq end
19211 (concat end "\n"
19212 (org-latex-packages-to-string pkg snippets-p)))))
19214 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19215 (setq rpl (if (or (match-end 1) (not extra))
19216 "" (concat extra "\n"))
19217 tpl (replace-match rpl t t tpl))
19218 (when (and extra (string-match "\\S-" extra))
19219 (setq end (concat end "\n" extra))))
19221 (if (string-match "\\S-" end)
19222 (concat tpl "\n" end)
19223 tpl)))
19225 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19226 "Turn an alist of packages into a string with the \\usepackage macros."
19227 (setq pkg (mapconcat (lambda(p)
19228 (cond
19229 ((stringp p) p)
19230 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19231 (format "%% Package %s omitted" (cadr p)))
19232 ((equal "" (car p))
19233 (format "\\usepackage{%s}" (cadr p)))
19235 (format "\\usepackage[%s]{%s}"
19236 (car p) (cadr p)))))
19238 "\n"))
19239 (if newline (concat pkg "\n") pkg))
19241 (defun org-dvipng-color (attr)
19242 "Return a RGB color specification for dvipng."
19243 (org-dvipng-color-format (face-attribute 'default attr nil)))
19245 (defun org-dvipng-color-format (color-name)
19246 "Convert COLOR-NAME to a RGB color value for dvipng."
19247 (apply #'format "rgb %s %s %s"
19248 (mapcar 'org-normalize-color
19249 (color-values color-name))))
19251 (defun org-latex-color (attr)
19252 "Return a RGB color for the LaTeX color package."
19253 (org-latex-color-format (face-attribute 'default attr nil)))
19255 (defun org-latex-color-format (color-name)
19256 "Convert COLOR-NAME to a RGB color value."
19257 (apply #'format "%s,%s,%s"
19258 (mapcar 'org-normalize-color
19259 (color-values color-name))))
19261 (defun org-normalize-color (value)
19262 "Return string to be used as color value for an RGB component."
19263 (format "%g" (/ value 65535.0)))
19267 ;; Image display
19269 (defvar-local org-inline-image-overlays nil)
19271 (defun org-toggle-inline-images (&optional include-linked)
19272 "Toggle the display of inline images.
19273 INCLUDE-LINKED is passed to `org-display-inline-images'."
19274 (interactive "P")
19275 (if org-inline-image-overlays
19276 (progn
19277 (org-remove-inline-images)
19278 (when (called-interactively-p 'interactive)
19279 (message "Inline image display turned off")))
19280 (org-display-inline-images include-linked)
19281 (when (called-interactively-p 'interactive)
19282 (message (if org-inline-image-overlays
19283 (format "%d images displayed inline"
19284 (length org-inline-image-overlays))
19285 "No images to display inline")))))
19287 (defun org-redisplay-inline-images ()
19288 "Refresh the display of inline images."
19289 (interactive)
19290 (if (not org-inline-image-overlays)
19291 (org-toggle-inline-images)
19292 (org-toggle-inline-images)
19293 (org-toggle-inline-images)))
19295 (defun org-display-inline-images (&optional include-linked refresh beg end)
19296 "Display inline images.
19298 An inline image is a link which follows either of these
19299 conventions:
19301 1. Its path is a file with an extension matching return value
19302 from `image-file-name-regexp' and it has no contents.
19304 2. Its description consists in a single link of the previous
19305 type.
19307 When optional argument INCLUDE-LINKED is non-nil, also links with
19308 a text description part will be inlined. This can be nice for
19309 a quick look at those images, but it does not reflect what
19310 exported files will look like.
19312 When optional argument REFRESH is non-nil, refresh existing
19313 images between BEG and END. This will create new image displays
19314 only if necessary. BEG and END default to the buffer
19315 boundaries."
19316 (interactive "P")
19317 (when (display-graphic-p)
19318 (unless refresh
19319 (org-remove-inline-images)
19320 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19321 (org-with-wide-buffer
19322 (goto-char (or beg (point-min)))
19323 (let* ((case-fold-search t)
19324 (file-extension-re (image-file-name-regexp))
19325 (link-abbrevs (mapcar #'car
19326 (append org-link-abbrev-alist-local
19327 org-link-abbrev-alist)))
19328 ;; Check absolute, relative file names and explicit
19329 ;; "file:" links. Also check link abbreviations since
19330 ;; some might expand to "file" links.
19331 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19332 (and link-abbrevs
19333 (format "\\|\\(?:%s:\\)"
19334 (regexp-opt link-abbrevs))))))
19335 (while (re-search-forward file-types-re end t)
19336 (let ((link (save-match-data (org-element-context))))
19337 ;; Check if we're at an inline image, i.e., an image file
19338 ;; link without a description (unless INCLUDE-LINKED is
19339 ;; non-nil).
19340 (when (and (equal "file" (org-element-property :type link))
19341 (or include-linked
19342 (null (org-element-contents link)))
19343 (string-match-p file-extension-re
19344 (org-element-property :path link)))
19345 (let ((file (expand-file-name
19346 (org-link-unescape
19347 (org-element-property :path link)))))
19348 (when (file-exists-p file)
19349 (let ((width
19350 ;; Apply `org-image-actual-width' specifications.
19351 (cond
19352 ((not (image-type-available-p 'imagemagick)) nil)
19353 ((eq org-image-actual-width t) nil)
19354 ((listp org-image-actual-width)
19356 ;; First try to find a width among
19357 ;; attributes associated to the paragraph
19358 ;; containing link.
19359 (let ((paragraph
19360 (let ((e link))
19361 (while (and (setq e (org-element-property
19362 :parent e))
19363 (not (eq (org-element-type e)
19364 'paragraph))))
19365 e)))
19366 (when paragraph
19367 (save-excursion
19368 (goto-char (org-element-property :begin paragraph))
19369 (when
19370 (re-search-forward
19371 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19372 (org-element-property
19373 :post-affiliated paragraph)
19375 (string-to-number (match-string 1))))))
19376 ;; Otherwise, fall-back to provided number.
19377 (car org-image-actual-width)))
19378 ((numberp org-image-actual-width)
19379 org-image-actual-width)))
19380 (old (get-char-property-and-overlay
19381 (org-element-property :begin link)
19382 'org-image-overlay)))
19383 (if (and (car-safe old) refresh)
19384 (image-refresh (overlay-get (cdr old) 'display))
19385 (let ((image (create-image file
19386 (and width 'imagemagick)
19388 :width width)))
19389 (when image
19390 (let ((ov (make-overlay
19391 (org-element-property :begin link)
19392 (progn
19393 (goto-char
19394 (org-element-property :end link))
19395 (skip-chars-backward " \t")
19396 (point)))))
19397 (overlay-put ov 'display image)
19398 (overlay-put ov 'face 'default)
19399 (overlay-put ov 'org-image-overlay t)
19400 (overlay-put
19401 ov 'modification-hooks
19402 (list 'org-display-inline-remove-overlay))
19403 (push ov org-inline-image-overlays)))))))))))))))
19405 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19406 "Remove inline-display overlay if a corresponding region is modified."
19407 (let ((inhibit-modification-hooks t))
19408 (when (and ov after)
19409 (delete ov org-inline-image-overlays)
19410 (delete-overlay ov))))
19412 (defun org-remove-inline-images ()
19413 "Remove inline display of images."
19414 (interactive)
19415 (mapc #'delete-overlay org-inline-image-overlays)
19416 (setq org-inline-image-overlays nil))
19418 ;;;; Key bindings
19420 (defun org-remap (map &rest commands)
19421 "In MAP, remap the functions given in COMMANDS.
19422 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19423 (let (new old)
19424 (while commands
19425 (setq old (pop commands) new (pop commands))
19426 (org-defkey map (vector 'remap old) new))))
19428 ;; Outline functions from `outline-mode-prefix-map'
19429 ;; that can be remapped in Org:
19430 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19431 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19432 (define-key org-mode-map [remap outline-forward-same-level]
19433 'org-forward-heading-same-level)
19434 (define-key org-mode-map [remap outline-backward-same-level]
19435 'org-backward-heading-same-level)
19436 (define-key org-mode-map [remap outline-show-branches]
19437 'org-kill-note-or-show-branches)
19438 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19439 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19440 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19441 (define-key org-mode-map [remap outline-next-visible-heading]
19442 'org-next-visible-heading)
19443 (define-key org-mode-map [remap outline-previous-visible-heading]
19444 'org-previous-visible-heading)
19445 (define-key org-mode-map [remap show-children] 'org-show-children)
19447 ;; Outline functions from `outline-mode-prefix-map' that can not
19448 ;; be remapped in Org:
19450 ;; - the column "key binding" shows whether the Outline function is still
19451 ;; available in Org mode on the same key that it has been bound to in
19452 ;; Outline mode:
19453 ;; - "overridden": key used for a different functionality in Org mode
19454 ;; - else: key still bound to the same Outline function in Org mode
19456 ;; | Outline function | key binding | Org replacement |
19457 ;; |------------------------------------+-------------+--------------------------|
19458 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19459 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19460 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19461 ;; | `show-entry' | overridden | no replacement |
19462 ;; | `show-branches' | `C-c C-k' | still same function |
19463 ;; | `show-subtree' | overridden | visibility cycling |
19464 ;; | `show-all' | overridden | no replacement |
19465 ;; | `hide-subtree' | overridden | visibility cycling |
19466 ;; | `hide-body' | overridden | no replacement |
19467 ;; | `hide-entry' | overridden | visibility cycling |
19468 ;; | `hide-leaves' | overridden | no replacement |
19469 ;; | `hide-sublevels' | overridden | no replacement |
19470 ;; | `hide-other' | overridden | no replacement |
19472 ;; Make `C-c C-x' a prefix key
19473 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19475 ;; TAB key with modifiers
19476 (org-defkey org-mode-map "\C-i" 'org-cycle)
19477 (org-defkey org-mode-map [(tab)] 'org-cycle)
19478 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19479 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19481 ;; The following line is necessary under Suse GNU/Linux
19482 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19483 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19484 (define-key org-mode-map [backtab] 'org-shifttab)
19486 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19487 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19488 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19490 ;; Cursor keys with modifiers
19491 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19492 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19493 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19494 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19496 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19497 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19498 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19499 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19500 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19501 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19503 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19504 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19505 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19506 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19508 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19509 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19510 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19511 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19513 ;; Babel keys
19514 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19515 (dolist (pair org-babel-key-bindings)
19516 (define-key org-babel-map (car pair) (cdr pair)))
19518 ;;; Extra keys for tty access.
19519 ;; We only set them when really needed because otherwise the
19520 ;; menus don't show the simple keys
19522 (when (or org-use-extra-keys (not window-system))
19523 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19524 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19525 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19526 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19527 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19528 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19529 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19530 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19531 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19532 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19533 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19534 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19535 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19536 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19537 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19538 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19539 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19540 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19541 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19542 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19543 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19544 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19545 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19546 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19547 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19548 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19549 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19550 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19552 ;; All the other keys
19553 (org-remap org-mode-map
19554 'self-insert-command 'org-self-insert-command
19555 'delete-char 'org-delete-char
19556 'delete-backward-char 'org-delete-backward-char)
19557 (org-defkey org-mode-map "|" 'org-force-self-insert)
19559 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19560 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19561 (if (boundp 'narrow-map)
19562 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19563 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19564 (if (boundp 'narrow-map)
19565 (org-defkey narrow-map "b" 'org-narrow-to-block)
19566 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19567 (if (boundp 'narrow-map)
19568 (org-defkey narrow-map "e" 'org-narrow-to-element)
19569 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19570 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19571 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19572 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19573 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19574 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19575 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19576 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19577 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19578 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19579 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19580 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19581 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19582 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19583 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19584 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19585 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19586 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19587 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19588 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19589 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19590 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19591 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19592 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19593 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19594 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19595 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19596 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19597 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19598 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19599 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19600 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19601 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19602 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19603 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19604 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19605 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19606 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19607 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19608 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19609 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19610 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19611 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19612 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19613 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19614 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19615 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19616 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19617 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19618 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19619 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19620 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19621 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19622 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19623 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19624 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19625 (org-defkey org-mode-map "\C-c^" 'org-sort)
19626 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19627 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19628 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19629 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19630 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19631 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19632 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19633 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19634 (org-defkey org-mode-map "\C-m" 'org-return)
19635 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19636 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19637 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19638 (org-defkey org-mode-map (kbd "C-c TAB") #'org-table-toggle-column-width)
19639 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19640 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19641 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19642 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19643 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19644 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19645 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19646 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19647 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19648 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19649 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19650 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19651 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19652 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19653 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19654 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19655 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19656 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19657 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19658 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19659 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19660 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19662 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19663 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19664 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19666 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19667 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19668 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19669 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19670 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19671 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19672 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19673 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19674 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19675 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19676 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19677 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19678 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19679 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19680 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19681 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19682 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19683 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19684 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19685 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19686 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19687 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19689 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19690 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19691 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19692 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19693 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19695 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19697 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19699 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19700 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19702 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19705 (defconst org-speed-commands-default
19707 ("Outline Navigation")
19708 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19709 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19710 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19711 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19712 ("F" . org-next-block)
19713 ("B" . org-previous-block)
19714 ("u" . (org-speed-move-safe 'outline-up-heading))
19715 ("j" . org-goto)
19716 ("g" . (org-refile t))
19717 ("Outline Visibility")
19718 ("c" . org-cycle)
19719 ("C" . org-shifttab)
19720 (" " . org-display-outline-path)
19721 ("s" . org-narrow-to-subtree)
19722 ("=" . org-columns)
19723 ("Outline Structure Editing")
19724 ("U" . org-metaup)
19725 ("D" . org-metadown)
19726 ("r" . org-metaright)
19727 ("l" . org-metaleft)
19728 ("R" . org-shiftmetaright)
19729 ("L" . org-shiftmetaleft)
19730 ("i" . (progn (forward-char 1) (call-interactively
19731 'org-insert-heading-respect-content)))
19732 ("^" . org-sort)
19733 ("w" . org-refile)
19734 ("a" . org-archive-subtree-default-with-confirmation)
19735 ("@" . org-mark-subtree)
19736 ("#" . org-toggle-comment)
19737 ("Clock Commands")
19738 ("I" . org-clock-in)
19739 ("O" . org-clock-out)
19740 ("Meta Data Editing")
19741 ("t" . org-todo)
19742 ("," . (org-priority))
19743 ("0" . (org-priority ?\ ))
19744 ("1" . (org-priority ?A))
19745 ("2" . (org-priority ?B))
19746 ("3" . (org-priority ?C))
19747 (":" . org-set-tags-command)
19748 ("e" . org-set-effort)
19749 ("E" . org-inc-effort)
19750 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19751 (org-entry-put (point) "APPT_WARNTIME" m)))
19752 ("Agenda Views etc")
19753 ("v" . org-agenda)
19754 ("/" . org-sparse-tree)
19755 ("Misc")
19756 ("o" . org-open-at-point)
19757 ("?" . org-speed-command-help)
19758 ("<" . (org-agenda-set-restriction-lock 'subtree))
19759 (">" . (org-agenda-remove-restriction-lock))
19761 "The default speed commands.")
19763 (defun org-print-speed-command (e)
19764 (if (> (length (car e)) 1)
19765 (progn
19766 (princ "\n")
19767 (princ (car e))
19768 (princ "\n")
19769 (princ (make-string (length (car e)) ?-))
19770 (princ "\n"))
19771 (princ (car e))
19772 (princ " ")
19773 (if (symbolp (cdr e))
19774 (princ (symbol-name (cdr e)))
19775 (prin1 (cdr e)))
19776 (princ "\n")))
19778 (defun org-speed-command-help ()
19779 "Show the available speed commands."
19780 (interactive)
19781 (if (not org-use-speed-commands)
19782 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19783 (with-output-to-temp-buffer "*Help*"
19784 (princ "User-defined Speed commands\n===========================\n")
19785 (mapc #'org-print-speed-command org-speed-commands-user)
19786 (princ "\n")
19787 (princ "Built-in Speed commands\n=======================\n")
19788 (mapc #'org-print-speed-command org-speed-commands-default))
19789 (with-current-buffer "*Help*"
19790 (setq truncate-lines t))))
19792 (defun org-speed-move-safe (cmd)
19793 "Execute CMD, but make sure that the cursor always ends up in a headline.
19794 If not, return to the original position and throw an error."
19795 (interactive)
19796 (let ((pos (point)))
19797 (call-interactively cmd)
19798 (unless (and (bolp) (org-at-heading-p))
19799 (goto-char pos)
19800 (error "Boundary reached while executing %s" cmd))))
19802 (defvar org-self-insert-command-undo-counter 0)
19804 (defvar org-table-auto-blank-field) ; defined in org-table.el
19805 (defvar org-speed-command nil)
19807 (defun org-speed-command-activate (keys)
19808 "Hook for activating single-letter speed commands.
19809 `org-speed-commands-default' specifies a minimal command set.
19810 Use `org-speed-commands-user' for further customization."
19811 (when (or (and (bolp) (looking-at org-outline-regexp))
19812 (and (functionp org-use-speed-commands)
19813 (funcall org-use-speed-commands)))
19814 (cdr (assoc keys (append org-speed-commands-user
19815 org-speed-commands-default)))))
19817 (defun org-babel-speed-command-activate (keys)
19818 "Hook for activating single-letter code block commands."
19819 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19820 (cdr (assoc keys org-babel-key-bindings))))
19822 (defcustom org-speed-command-hook
19823 '(org-speed-command-activate org-babel-speed-command-activate)
19824 "Hook for activating speed commands at strategic locations.
19825 Hook functions are called in sequence until a valid handler is
19826 found.
19828 Each hook takes a single argument, a user-pressed command key
19829 which is also a `self-insert-command' from the global map.
19831 Within the hook, examine the cursor position and the command key
19832 and return nil or a valid handler as appropriate. Handler could
19833 be one of an interactive command, a function, or a form.
19835 Set `org-use-speed-commands' to non-nil value to enable this
19836 hook. The default setting is `org-speed-command-activate'."
19837 :group 'org-structure
19838 :version "24.1"
19839 :type 'hook)
19841 (defun org-self-insert-command (N)
19842 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19843 If the cursor is in a table looking at whitespace, the whitespace is
19844 overwritten, and the table is not marked as requiring realignment."
19845 (interactive "p")
19846 (org-check-before-invisible-edit 'insert)
19847 (cond
19848 ((and org-use-speed-commands
19849 (let ((kv (this-command-keys-vector)))
19850 (setq org-speed-command
19851 (run-hook-with-args-until-success
19852 'org-speed-command-hook
19853 (make-string 1 (aref kv (1- (length kv))))))))
19854 (cond
19855 ((commandp org-speed-command)
19856 (setq this-command org-speed-command)
19857 (call-interactively org-speed-command))
19858 ((functionp org-speed-command)
19859 (funcall org-speed-command))
19860 ((and org-speed-command (listp org-speed-command))
19861 (eval org-speed-command))
19862 (t (let (org-use-speed-commands)
19863 (call-interactively 'org-self-insert-command)))))
19864 ((and
19865 (org-at-table-p)
19866 (eq N 1)
19867 (not (org-region-active-p))
19868 (progn
19869 ;; Check if we blank the field, and if that triggers align.
19870 (and (featurep 'org-table) org-table-auto-blank-field
19871 (memq last-command
19872 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19873 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19874 ;; Got extra space, this field does not determine
19875 ;; column width.
19876 (let (org-table-may-need-update) (org-table-blank-field))
19877 ;; No extra space, this field may determine column
19878 ;; width.
19879 (org-table-blank-field)))
19881 (looking-at "[^|\n]* \\( \\)|"))
19882 ;; There is room for insertion without re-aligning the table.
19883 (delete-region (match-beginning 1) (match-end 1))
19884 (self-insert-command N))
19886 (setq org-table-may-need-update t)
19887 (self-insert-command N)
19888 (org-fix-tags-on-the-fly)
19889 (when org-self-insert-cluster-for-undo
19890 (if (not (eq last-command 'org-self-insert-command))
19891 (setq org-self-insert-command-undo-counter 1)
19892 (if (>= org-self-insert-command-undo-counter 20)
19893 (setq org-self-insert-command-undo-counter 1)
19894 (and (> org-self-insert-command-undo-counter 0)
19895 buffer-undo-list (listp buffer-undo-list)
19896 (not (cadr buffer-undo-list)) ; remove nil entry
19897 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19898 (setq org-self-insert-command-undo-counter
19899 (1+ org-self-insert-command-undo-counter))))))))
19901 (defun org-check-before-invisible-edit (kind)
19902 "Check is editing if kind KIND would be dangerous with invisible text around.
19903 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19904 ;; First, try to get out of here as quickly as possible, to reduce overhead
19905 (when (and org-catch-invisible-edits
19906 (or (not (boundp 'visible-mode)) (not visible-mode))
19907 (or (get-char-property (point) 'invisible)
19908 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19909 ;; OK, we need to take a closer look. Do not consider
19910 ;; invisibility obtained through text properties (e.g., link
19911 ;; fontification), as it cannot be toggled.
19912 (let* ((invisible-at-point
19913 (pcase (get-char-property-and-overlay (point) 'invisible)
19914 (`(,_ . ,(and (pred overlayp) o)) o)))
19915 ;; Assume that point cannot land in the middle of an
19916 ;; overlay, or between two overlays.
19917 (invisible-before-point
19918 (and (not invisible-at-point)
19919 (not (bobp))
19920 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19921 (`(,_ . ,(and (pred overlayp) o)) o))))
19922 (border-and-ok-direction
19924 ;; Check if we are acting predictably before invisible
19925 ;; text.
19926 (and invisible-at-point
19927 (memq kind '(insert delete-backward)))
19928 ;; Check if we are acting predictably after invisible text
19929 ;; This works not well, and I have turned it off. It seems
19930 ;; better to always show and stop after invisible text.
19931 ;; (and (not invisible-at-point) invisible-before-point
19932 ;; (memq kind '(insert delete)))
19934 (when (or invisible-at-point invisible-before-point)
19935 (when (eq org-catch-invisible-edits 'error)
19936 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19937 (if (and org-custom-properties-overlays
19938 (y-or-n-p "Display invisible properties in this buffer? "))
19939 (org-toggle-custom-properties-visibility)
19940 ;; Make the area visible
19941 (save-excursion
19942 (when invisible-before-point
19943 (goto-char
19944 (previous-single-char-property-change (point) 'invisible)))
19945 ;; Remove whatever overlay is currently making yet-to-be
19946 ;; edited text invisible. Also remove nested invisibility
19947 ;; related overlays.
19948 (delete-overlay (or invisible-at-point invisible-before-point))
19949 (let ((origin (if invisible-at-point (point) (1- (point)))))
19950 (while (pcase (get-char-property-and-overlay origin 'invisible)
19951 (`(,_ . ,(and (pred overlayp) o))
19952 (delete-overlay o)
19953 t)))))
19954 (cond
19955 ((eq org-catch-invisible-edits 'show)
19956 ;; That's it, we do the edit after showing
19957 (message
19958 "Unfolding invisible region around point before editing")
19959 (sit-for 1))
19960 ((and (eq org-catch-invisible-edits 'smart)
19961 border-and-ok-direction)
19962 (message "Unfolding invisible region around point before editing"))
19964 ;; Don't do the edit, make the user repeat it in full visibility
19965 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19967 (defun org-fix-tags-on-the-fly ()
19968 "Align tags in headline at point.
19969 Unlike to `org-set-tags', it ignores region and sorting."
19970 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19971 (org-at-heading-p))
19972 (let ((org-ignore-region t)
19973 (org-tags-sort-function nil))
19974 (org-set-tags nil t))))
19976 (defun org-delete-backward-char (N)
19977 "Like `delete-backward-char', insert whitespace at field end in tables.
19978 When deleting backwards, in tables this function will insert whitespace in
19979 front of the next \"|\" separator, to keep the table aligned. The table will
19980 still be marked for re-alignment if the field did fill the entire column,
19981 because, in this case the deletion might narrow the column."
19982 (interactive "p")
19983 (save-match-data
19984 (org-check-before-invisible-edit 'delete-backward)
19985 (if (and (org-at-table-p)
19986 (eq N 1)
19987 (not (org-region-active-p))
19988 (string-match "|" (buffer-substring (point-at-bol) (point)))
19989 (looking-at ".*?|"))
19990 (let ((pos (point))
19991 (noalign (looking-at "[^|\n\r]* |"))
19992 (c org-table-may-need-update))
19993 (backward-delete-char N)
19994 (unless overwrite-mode
19995 (skip-chars-forward "^|")
19996 (insert " ")
19997 (goto-char (1- pos)))
19998 ;; noalign: if there were two spaces at the end, this field
19999 ;; does not determine the width of the column.
20000 (when noalign (setq org-table-may-need-update c)))
20001 (backward-delete-char N)
20002 (org-fix-tags-on-the-fly))))
20004 (defun org-delete-char (N)
20005 "Like `delete-char', but insert whitespace at field end in tables.
20006 When deleting characters, in tables this function will insert whitespace in
20007 front of the next \"|\" separator, to keep the table aligned. The table will
20008 still be marked for re-alignment if the field did fill the entire column,
20009 because, in this case the deletion might narrow the column."
20010 (interactive "p")
20011 (save-match-data
20012 (org-check-before-invisible-edit 'delete)
20013 (if (and (org-at-table-p)
20014 (not (bolp))
20015 (not (= (char-after) ?|))
20016 (eq N 1))
20017 (if (looking-at ".*?|")
20018 (let ((pos (point))
20019 (noalign (looking-at "[^|\n\r]* |"))
20020 (c org-table-may-need-update))
20021 (replace-match
20022 (concat (substring (match-string 0) 1 -1) " |") nil t)
20023 (goto-char pos)
20024 ;; noalign: if there were two spaces at the end, this field
20025 ;; does not determine the width of the column.
20026 (when noalign (setq org-table-may-need-update c)))
20027 (delete-char N))
20028 (delete-char N)
20029 (org-fix-tags-on-the-fly))))
20031 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20032 (put 'org-self-insert-command 'delete-selection
20033 (lambda ()
20034 (not (run-hook-with-args-until-success
20035 'self-insert-uses-region-functions))))
20036 (put 'orgtbl-self-insert-command 'delete-selection
20037 (lambda ()
20038 (not (run-hook-with-args-until-success
20039 'self-insert-uses-region-functions))))
20040 (put 'org-delete-char 'delete-selection 'supersede)
20041 (put 'org-delete-backward-char 'delete-selection 'supersede)
20042 (put 'org-yank 'delete-selection 'yank)
20044 ;; Make `flyspell-mode' delay after some commands
20045 (put 'org-self-insert-command 'flyspell-delayed t)
20046 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20047 (put 'org-delete-char 'flyspell-delayed t)
20048 (put 'org-delete-backward-char 'flyspell-delayed t)
20050 ;; Make pabbrev-mode expand after Org mode commands
20051 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20052 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20054 (defun org-transpose-words ()
20055 "Transpose words for Org.
20056 This uses the `org-mode-transpose-word-syntax-table' syntax
20057 table, which interprets characters in `org-emphasis-alist' as
20058 word constituents."
20059 (interactive)
20060 (with-syntax-table org-mode-transpose-word-syntax-table
20061 (call-interactively 'transpose-words)))
20062 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20064 (defvar org-ctrl-c-ctrl-c-hook nil
20065 "Hook for functions attaching themselves to `C-c C-c'.
20067 This can be used to add additional functionality to the C-c C-c
20068 key which executes context-dependent commands. This hook is run
20069 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20070 run after the last test.
20072 Each function will be called with no arguments. The function
20073 must check if the context is appropriate for it to act. If yes,
20074 it should do its thing and then return a non-nil value. If the
20075 context is wrong, just do nothing and return nil.")
20077 (defvar org-ctrl-c-ctrl-c-final-hook nil
20078 "Hook for functions attaching themselves to `C-c C-c'.
20080 This can be used to add additional functionality to the C-c C-c
20081 key which executes context-dependent commands. This hook is run
20082 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20083 before the first test.
20085 Each function will be called with no arguments. The function
20086 must check if the context is appropriate for it to act. If yes,
20087 it should do its thing and then return a non-nil value. If the
20088 context is wrong, just do nothing and return nil.")
20090 (defvar org-tab-first-hook nil
20091 "Hook for functions to attach themselves to TAB.
20092 See `org-ctrl-c-ctrl-c-hook' for more information.
20093 This hook runs as the first action when TAB is pressed, even before
20094 `org-cycle' messes around with the `outline-regexp' to cater for
20095 inline tasks and plain list item folding.
20096 If any function in this hook returns t, any other actions that
20097 would have been caused by TAB (such as table field motion or visibility
20098 cycling) will not occur.")
20100 (defvar org-tab-after-check-for-table-hook nil
20101 "Hook for functions to attach themselves to TAB.
20102 See `org-ctrl-c-ctrl-c-hook' for more information.
20103 This hook runs after it has been established that the cursor is not in a
20104 table, but before checking if the cursor is in a headline or if global cycling
20105 should be done.
20106 If any function in this hook returns t, not other actions like visibility
20107 cycling will be done.")
20109 (defvar org-tab-after-check-for-cycling-hook nil
20110 "Hook for functions to attach themselves to TAB.
20111 See `org-ctrl-c-ctrl-c-hook' for more information.
20112 This hook runs after it has been established that not table field motion and
20113 not visibility should be done because of current context. This is probably
20114 the place where a package like yasnippets can hook in.")
20116 (defvar org-tab-before-tab-emulation-hook nil
20117 "Hook for functions to attach themselves to TAB.
20118 See `org-ctrl-c-ctrl-c-hook' for more information.
20119 This hook runs after every other options for TAB have been exhausted, but
20120 before indentation and \t insertion takes place.")
20122 (defvar org-metaleft-hook nil
20123 "Hook for functions attaching themselves to `M-left'.
20124 See `org-ctrl-c-ctrl-c-hook' for more information.")
20125 (defvar org-metaright-hook nil
20126 "Hook for functions attaching themselves to `M-right'.
20127 See `org-ctrl-c-ctrl-c-hook' for more information.")
20128 (defvar org-metaup-hook nil
20129 "Hook for functions attaching themselves to `M-up'.
20130 See `org-ctrl-c-ctrl-c-hook' for more information.")
20131 (defvar org-metadown-hook nil
20132 "Hook for functions attaching themselves to `M-down'.
20133 See `org-ctrl-c-ctrl-c-hook' for more information.")
20134 (defvar org-shiftmetaleft-hook nil
20135 "Hook for functions attaching themselves to `M-S-left'.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-shiftmetaright-hook nil
20138 "Hook for functions attaching themselves to `M-S-right'.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.")
20140 (defvar org-shiftmetaup-hook nil
20141 "Hook for functions attaching themselves to `M-S-up'.
20142 See `org-ctrl-c-ctrl-c-hook' for more information.")
20143 (defvar org-shiftmetadown-hook nil
20144 "Hook for functions attaching themselves to `M-S-down'.
20145 See `org-ctrl-c-ctrl-c-hook' for more information.")
20146 (defvar org-metareturn-hook nil
20147 "Hook for functions attaching themselves to `M-RET'.
20148 See `org-ctrl-c-ctrl-c-hook' for more information.")
20149 (defvar org-shiftup-hook nil
20150 "Hook for functions attaching themselves to `S-up'.
20151 See `org-ctrl-c-ctrl-c-hook' for more information.")
20152 (defvar org-shiftup-final-hook nil
20153 "Hook for functions attaching themselves to `S-up'.
20154 This one runs after all other options except shift-select have been excluded.
20155 See `org-ctrl-c-ctrl-c-hook' for more information.")
20156 (defvar org-shiftdown-hook nil
20157 "Hook for functions attaching themselves to `S-down'.
20158 See `org-ctrl-c-ctrl-c-hook' for more information.")
20159 (defvar org-shiftdown-final-hook nil
20160 "Hook for functions attaching themselves to `S-down'.
20161 This one runs after all other options except shift-select have been excluded.
20162 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defvar org-shiftleft-hook nil
20164 "Hook for functions attaching themselves to `S-left'.
20165 See `org-ctrl-c-ctrl-c-hook' for more information.")
20166 (defvar org-shiftleft-final-hook nil
20167 "Hook for functions attaching themselves to `S-left'.
20168 This one runs after all other options except shift-select have been excluded.
20169 See `org-ctrl-c-ctrl-c-hook' for more information.")
20170 (defvar org-shiftright-hook nil
20171 "Hook for functions attaching themselves to `S-right'.
20172 See `org-ctrl-c-ctrl-c-hook' for more information.")
20173 (defvar org-shiftright-final-hook nil
20174 "Hook for functions attaching themselves to `S-right'.
20175 This one runs after all other options except shift-select have been excluded.
20176 See `org-ctrl-c-ctrl-c-hook' for more information.")
20178 (defun org-modifier-cursor-error ()
20179 "Throw an error, a modified cursor command was applied in wrong context."
20180 (user-error "This command is active in special context like tables, headlines or items"))
20182 (defun org-shiftselect-error ()
20183 "Throw an error because Shift-Cursor command was applied in wrong context."
20184 (if (and (boundp 'shift-select-mode) shift-select-mode)
20185 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20186 (user-error "This command works only in special context like headlines or timestamps")))
20188 (defun org-call-for-shift-select (cmd)
20189 (let ((this-command-keys-shift-translated t))
20190 (call-interactively cmd)))
20192 (defun org-shifttab (&optional arg)
20193 "Global visibility cycling or move to previous table field.
20194 Call `org-table-previous-field' within a table.
20195 When ARG is nil, cycle globally through visibility states.
20196 When ARG is a numeric prefix, show contents of this level."
20197 (interactive "P")
20198 (cond
20199 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20200 ((integerp arg)
20201 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20202 (message "Content view to level: %d" arg)
20203 (org-content (prefix-numeric-value arg2))
20204 (org-cycle-show-empty-lines t)
20205 (setq org-cycle-global-status 'overview)))
20206 (t (call-interactively 'org-global-cycle))))
20208 (defun org-shiftmetaleft ()
20209 "Promote subtree or delete table column.
20210 Calls `org-promote-subtree', `org-outdent-item-tree', or
20211 `org-table-delete-column', depending on context. See the
20212 individual commands for more information."
20213 (interactive)
20214 (cond
20215 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20216 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20217 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20218 ((if (not (org-region-active-p)) (org-at-item-p)
20219 (save-excursion (goto-char (region-beginning))
20220 (org-at-item-p)))
20221 (call-interactively 'org-outdent-item-tree))
20222 (t (org-modifier-cursor-error))))
20224 (defun org-shiftmetaright ()
20225 "Demote subtree or insert table column.
20226 Calls `org-demote-subtree', `org-indent-item-tree', or
20227 `org-table-insert-column', depending on context. See the
20228 individual commands for more information."
20229 (interactive)
20230 (cond
20231 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20232 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20233 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20234 ((if (not (org-region-active-p)) (org-at-item-p)
20235 (save-excursion (goto-char (region-beginning))
20236 (org-at-item-p)))
20237 (call-interactively 'org-indent-item-tree))
20238 (t (org-modifier-cursor-error))))
20240 (defun org-shiftmetaup (&optional _arg)
20241 "Drag the line at point up.
20242 In a table, kill the current row.
20243 On a clock timestamp, update the value of the timestamp like `S-<up>'
20244 but also adjust the previous clocked item in the clock history.
20245 Everywhere else, drag the line at point up."
20246 (interactive "P")
20247 (cond
20248 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20249 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20250 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20251 (call-interactively 'org-timestamp-up)))
20252 (t (call-interactively 'org-drag-line-backward))))
20254 (defun org-shiftmetadown (&optional _arg)
20255 "Drag the line at point down.
20256 In a table, insert an empty row at the current line.
20257 On a clock timestamp, update the value of the timestamp like `S-<down>'
20258 but also adjust the previous clocked item in the clock history.
20259 Everywhere else, drag the line at point down."
20260 (interactive "P")
20261 (cond
20262 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20263 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20264 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20265 (call-interactively 'org-timestamp-down)))
20266 (t (call-interactively 'org-drag-line-forward))))
20268 (defsubst org-hidden-tree-error ()
20269 (user-error
20270 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20272 (defun org-metaleft (&optional _arg)
20273 "Promote heading, list item at point or move table column left.
20275 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20276 depending on context. With no specific context, calls the Emacs
20277 default `backward-word'. See the individual commands for more
20278 information.
20280 This function runs the hook `org-metaleft-hook' as a first step,
20281 and returns at first non-nil value."
20282 (interactive "P")
20283 (cond
20284 ((run-hook-with-args-until-success 'org-metaleft-hook))
20285 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20286 ((org-with-limited-levels
20287 (or (org-at-heading-p)
20288 (and (org-region-active-p)
20289 (save-excursion
20290 (goto-char (region-beginning))
20291 (org-at-heading-p)))))
20292 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20293 (call-interactively 'org-do-promote))
20294 ;; At an inline task.
20295 ((org-at-heading-p)
20296 (call-interactively 'org-inlinetask-promote))
20297 ((or (org-at-item-p)
20298 (and (org-region-active-p)
20299 (save-excursion
20300 (goto-char (region-beginning))
20301 (org-at-item-p))))
20302 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20303 (call-interactively 'org-outdent-item))
20304 (t (call-interactively 'backward-word))))
20306 (defun org-metaright (&optional _arg)
20307 "Demote heading, list item at point or move table column right.
20309 In front of a drawer or a block keyword, indent it correctly.
20311 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20312 `org-indent-drawer' or `org-indent-block' depending on context.
20313 With no specific context, calls the Emacs default `forward-word'.
20314 See the individual commands for more information.
20316 This function runs the hook `org-metaright-hook' as a first step,
20317 and returns at first non-nil value."
20318 (interactive "P")
20319 (cond
20320 ((run-hook-with-args-until-success 'org-metaright-hook))
20321 ((org-at-table-p) (call-interactively 'org-table-move-column))
20322 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20323 ((org-at-block-p) (call-interactively 'org-indent-block))
20324 ((org-with-limited-levels
20325 (or (org-at-heading-p)
20326 (and (org-region-active-p)
20327 (save-excursion
20328 (goto-char (region-beginning))
20329 (org-at-heading-p)))))
20330 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20331 (call-interactively 'org-do-demote))
20332 ;; At an inline task.
20333 ((org-at-heading-p)
20334 (call-interactively 'org-inlinetask-demote))
20335 ((or (org-at-item-p)
20336 (and (org-region-active-p)
20337 (save-excursion
20338 (goto-char (region-beginning))
20339 (org-at-item-p))))
20340 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20341 (call-interactively 'org-indent-item))
20342 (t (call-interactively 'forward-word))))
20344 (defun org-check-for-hidden (what)
20345 "Check if there are hidden headlines/items in the current visual line.
20346 WHAT can be either `headlines' or `items'. If the current line is
20347 an outline or item heading and it has a folded subtree below it,
20348 this function returns t, nil otherwise."
20349 (let ((re (cond
20350 ((eq what 'headlines) org-outline-regexp-bol)
20351 ((eq what 'items) (org-item-beginning-re))
20352 (t (error "This should not happen"))))
20353 beg end)
20354 (save-excursion
20355 (catch 'exit
20356 (unless (org-region-active-p)
20357 (setq beg (point-at-bol))
20358 (beginning-of-line 2)
20359 (while (and (not (eobp)) ;; this is like `next-line'
20360 (get-char-property (1- (point)) 'invisible))
20361 (beginning-of-line 2))
20362 (setq end (point))
20363 (goto-char beg)
20364 (goto-char (point-at-eol))
20365 (setq end (max end (point)))
20366 (while (re-search-forward re end t)
20367 (when (get-char-property (match-beginning 0) 'invisible)
20368 (throw 'exit t))))
20369 nil))))
20371 (defun org-metaup (&optional _arg)
20372 "Move subtree up or move table row up.
20373 Calls `org-move-subtree-up' or `org-table-move-row' or
20374 `org-move-item-up', depending on context. See the individual commands
20375 for more information."
20376 (interactive "P")
20377 (cond
20378 ((run-hook-with-args-until-success 'org-metaup-hook))
20379 ((org-region-active-p)
20380 (let* ((a (min (region-beginning) (region-end)))
20381 (b (1- (max (region-beginning) (region-end))))
20382 (c (save-excursion (goto-char a)
20383 (move-beginning-of-line 0)))
20384 (d (save-excursion (goto-char a)
20385 (move-end-of-line 0) (point))))
20386 (transpose-regions a b c d)
20387 (goto-char c)))
20388 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20389 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20390 ((org-at-item-p) (call-interactively 'org-move-item-up))
20391 (t (org-drag-element-backward))))
20393 (defun org-metadown (&optional _arg)
20394 "Move subtree down or move table row down.
20395 Calls `org-move-subtree-down' or `org-table-move-row' or
20396 `org-move-item-down', depending on context. See the individual
20397 commands for more information."
20398 (interactive "P")
20399 (cond
20400 ((run-hook-with-args-until-success 'org-metadown-hook))
20401 ((org-region-active-p)
20402 (let* ((a (min (region-beginning) (region-end)))
20403 (b (max (region-beginning) (region-end)))
20404 (c (save-excursion (goto-char b)
20405 (move-beginning-of-line 1)))
20406 (d (save-excursion (goto-char b)
20407 (move-end-of-line 1) (1+ (point)))))
20408 (transpose-regions a b c d)
20409 (goto-char d)))
20410 ((org-at-table-p) (call-interactively 'org-table-move-row))
20411 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20412 ((org-at-item-p) (call-interactively 'org-move-item-down))
20413 (t (org-drag-element-forward))))
20415 (defun org-shiftup (&optional arg)
20416 "Increase item in timestamp or increase priority of current headline.
20417 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20418 depending on context. See the individual commands for more information."
20419 (interactive "P")
20420 (cond
20421 ((run-hook-with-args-until-success 'org-shiftup-hook))
20422 ((and org-support-shift-select (org-region-active-p))
20423 (org-call-for-shift-select 'previous-line))
20424 ((org-at-timestamp-p 'lax)
20425 (call-interactively (if org-edit-timestamp-down-means-later
20426 'org-timestamp-down 'org-timestamp-up)))
20427 ((and (not (eq org-support-shift-select 'always))
20428 org-enable-priority-commands
20429 (org-at-heading-p))
20430 (call-interactively 'org-priority-up))
20431 ((and (not org-support-shift-select) (org-at-item-p))
20432 (call-interactively 'org-previous-item))
20433 ((org-clocktable-try-shift 'up arg))
20434 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20435 (org-support-shift-select
20436 (org-call-for-shift-select 'previous-line))
20437 (t (org-shiftselect-error))))
20439 (defun org-shiftdown (&optional arg)
20440 "Decrease item in timestamp or decrease priority of current headline.
20441 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20442 depending on context. See the individual commands for more information."
20443 (interactive "P")
20444 (cond
20445 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20446 ((and org-support-shift-select (org-region-active-p))
20447 (org-call-for-shift-select 'next-line))
20448 ((org-at-timestamp-p 'lax)
20449 (call-interactively (if org-edit-timestamp-down-means-later
20450 'org-timestamp-up 'org-timestamp-down)))
20451 ((and (not (eq org-support-shift-select 'always))
20452 org-enable-priority-commands
20453 (org-at-heading-p))
20454 (call-interactively 'org-priority-down))
20455 ((and (not org-support-shift-select) (org-at-item-p))
20456 (call-interactively 'org-next-item))
20457 ((org-clocktable-try-shift 'down arg))
20458 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20459 (org-support-shift-select
20460 (org-call-for-shift-select 'next-line))
20461 (t (org-shiftselect-error))))
20463 (defun org-shiftright (&optional arg)
20464 "Cycle the thing at point or in the current line, depending on context.
20465 Depending on context, this does one of the following:
20467 - switch a timestamp at point one day into the future
20468 - on a headline, switch to the next TODO keyword.
20469 - on an item, switch entire list to the next bullet type
20470 - on a property line, switch to the next allowed value
20471 - on a clocktable definition line, move time block into the future"
20472 (interactive "P")
20473 (cond
20474 ((run-hook-with-args-until-success 'org-shiftright-hook))
20475 ((and org-support-shift-select (org-region-active-p))
20476 (org-call-for-shift-select 'forward-char))
20477 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20478 ((and (not (eq org-support-shift-select 'always))
20479 (org-at-heading-p))
20480 (let ((org-inhibit-logging
20481 (not org-treat-S-cursor-todo-selection-as-state-change))
20482 (org-inhibit-blocking
20483 (not org-treat-S-cursor-todo-selection-as-state-change)))
20484 (org-call-with-arg 'org-todo 'right)))
20485 ((or (and org-support-shift-select
20486 (not (eq org-support-shift-select 'always))
20487 (org-at-item-bullet-p))
20488 (and (not org-support-shift-select) (org-at-item-p)))
20489 (org-call-with-arg 'org-cycle-list-bullet nil))
20490 ((and (not (eq org-support-shift-select 'always))
20491 (org-at-property-p))
20492 (call-interactively 'org-property-next-allowed-value))
20493 ((org-clocktable-try-shift 'right arg))
20494 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20495 (org-support-shift-select
20496 (org-call-for-shift-select 'forward-char))
20497 (t (org-shiftselect-error))))
20499 (defun org-shiftleft (&optional arg)
20500 "Cycle the thing at point or in the current line, depending on context.
20501 Depending on context, this does one of the following:
20503 - switch a timestamp at point one day into the past
20504 - on a headline, switch to the previous TODO keyword.
20505 - on an item, switch entire list to the previous bullet type
20506 - on a property line, switch to the previous allowed value
20507 - on a clocktable definition line, move time block into the past"
20508 (interactive "P")
20509 (cond
20510 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20511 ((and org-support-shift-select (org-region-active-p))
20512 (org-call-for-shift-select 'backward-char))
20513 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20514 ((and (not (eq org-support-shift-select 'always))
20515 (org-at-heading-p))
20516 (let ((org-inhibit-logging
20517 (not org-treat-S-cursor-todo-selection-as-state-change))
20518 (org-inhibit-blocking
20519 (not org-treat-S-cursor-todo-selection-as-state-change)))
20520 (org-call-with-arg 'org-todo 'left)))
20521 ((or (and org-support-shift-select
20522 (not (eq org-support-shift-select 'always))
20523 (org-at-item-bullet-p))
20524 (and (not org-support-shift-select) (org-at-item-p)))
20525 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20526 ((and (not (eq org-support-shift-select 'always))
20527 (org-at-property-p))
20528 (call-interactively 'org-property-previous-allowed-value))
20529 ((org-clocktable-try-shift 'left arg))
20530 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20531 (org-support-shift-select
20532 (org-call-for-shift-select 'backward-char))
20533 (t (org-shiftselect-error))))
20535 (defun org-shiftcontrolright ()
20536 "Switch to next TODO set."
20537 (interactive)
20538 (cond
20539 ((and org-support-shift-select (org-region-active-p))
20540 (org-call-for-shift-select 'forward-word))
20541 ((and (not (eq org-support-shift-select 'always))
20542 (org-at-heading-p))
20543 (org-call-with-arg 'org-todo 'nextset))
20544 (org-support-shift-select
20545 (org-call-for-shift-select 'forward-word))
20546 (t (org-shiftselect-error))))
20548 (defun org-shiftcontrolleft ()
20549 "Switch to previous TODO set."
20550 (interactive)
20551 (cond
20552 ((and org-support-shift-select (org-region-active-p))
20553 (org-call-for-shift-select 'backward-word))
20554 ((and (not (eq org-support-shift-select 'always))
20555 (org-at-heading-p))
20556 (org-call-with-arg 'org-todo 'previousset))
20557 (org-support-shift-select
20558 (org-call-for-shift-select 'backward-word))
20559 (t (org-shiftselect-error))))
20561 (defun org-shiftcontrolup (&optional n)
20562 "Change timestamps synchronously up in CLOCK log lines.
20563 Optional argument N tells to change by that many units."
20564 (interactive "P")
20565 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20566 (let (org-support-shift-select)
20567 (org-clock-timestamps-up n))
20568 (user-error "Not at a clock log")))
20570 (defun org-shiftcontroldown (&optional n)
20571 "Change timestamps synchronously down in CLOCK log lines.
20572 Optional argument N tells to change by that many units."
20573 (interactive "P")
20574 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20575 (let (org-support-shift-select)
20576 (org-clock-timestamps-down n))
20577 (user-error "Not at a clock log")))
20579 (defun org-increase-number-at-point (&optional inc)
20580 "Increment the number at point.
20581 With an optional prefix numeric argument INC, increment using
20582 this numeric value."
20583 (interactive "p")
20584 (if (not (number-at-point))
20585 (user-error "Not on a number")
20586 (unless inc (setq inc 1))
20587 (let ((pos (point))
20588 (beg (skip-chars-backward "-+^/*0-9eE."))
20589 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20590 (setq nap (buffer-substring-no-properties
20591 (+ pos beg) (+ pos beg end)))
20592 (delete-region (+ pos beg) (+ pos beg end))
20593 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20594 (when (org-at-table-p)
20595 (org-table-align)
20596 (org-table-end-of-field 1))))
20598 (defun org-decrease-number-at-point (&optional inc)
20599 "Decrement the number at point.
20600 With an optional prefix numeric argument INC, decrement using
20601 this numeric value."
20602 (interactive "p")
20603 (org-increase-number-at-point (- (or inc 1))))
20605 (defun org-ctrl-c-ret ()
20606 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20607 (interactive)
20608 (cond
20609 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20610 (t (call-interactively 'org-insert-heading))))
20612 (defun org-find-visible ()
20613 (let ((s (point)))
20614 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20615 (get-char-property s 'invisible)))
20617 (defun org-find-invisible ()
20618 (let ((s (point)))
20619 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20620 (not (get-char-property s 'invisible))))
20623 (defun org-copy-visible (beg end)
20624 "Copy the visible parts of the region."
20625 (interactive "r")
20626 (let ((result ""))
20627 (while (/= beg end)
20628 (when (get-char-property beg 'invisible)
20629 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20630 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20631 (setq result (concat result (buffer-substring beg next)))
20632 (setq beg next)))
20633 (kill-new result)))
20635 (defun org-copy-special ()
20636 "Copy region in table or copy current subtree.
20637 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20638 context. See the individual commands for more information."
20639 (interactive)
20640 (call-interactively
20641 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20643 (defun org-cut-special ()
20644 "Cut region in table or cut current subtree.
20645 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20646 context. See the individual commands for more information."
20647 (interactive)
20648 (call-interactively
20649 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20651 (defun org-paste-special (arg)
20652 "Paste rectangular region into table, or past subtree relative to level.
20653 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20654 See the individual commands for more information."
20655 (interactive "P")
20656 (if (org-at-table-p)
20657 (org-table-paste-rectangle)
20658 (org-paste-subtree arg)))
20660 (defun org-edit-special (&optional arg)
20661 "Call a special editor for the element at point.
20662 When at a table, call the formula editor with `org-table-edit-formulas'.
20663 When in a source code block, call `org-edit-src-code'.
20664 When in a fixed-width region, call `org-edit-fixed-width-region'.
20665 When in an export block, call `org-edit-export-block'.
20666 When in a LaTeX environment, call `org-edit-latex-environment'.
20667 When at an #+INCLUDE keyword, visit the included file.
20668 When at a footnote reference, call `org-edit-footnote-reference'
20669 On a link, call `ffap' to visit the link at point.
20670 Otherwise, return a user error."
20671 (interactive "P")
20672 (let ((element (org-element-at-point)))
20673 (barf-if-buffer-read-only)
20674 (pcase (org-element-type element)
20675 (`src-block
20676 (if (not arg) (org-edit-src-code)
20677 (let* ((info (org-babel-get-src-block-info))
20678 (lang (nth 0 info))
20679 (params (nth 2 info))
20680 (session (cdr (assq :session params))))
20681 (if (not session) (org-edit-src-code)
20682 ;; At a src-block with a session and function called with
20683 ;; an ARG: switch to the buffer related to the inferior
20684 ;; process.
20685 (switch-to-buffer
20686 (funcall (intern (concat "org-babel-prep-session:" lang))
20687 session params))))))
20688 (`keyword
20689 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20690 (org-open-link-from-string
20691 (format "[[%s]]"
20692 (expand-file-name
20693 (let ((value (org-element-property :value element)))
20694 (cond ((org-file-url-p value)
20695 (user-error "The file is specified as a URL, cannot be edited"))
20696 ((not (org-string-nw-p value))
20697 (user-error "No file to edit"))
20698 ((string-match "\\`\"\\(.*?\\)\"" value)
20699 (match-string 1 value))
20700 ((string-match "\\`[^ \t\"]\\S-*" value)
20701 (match-string 0 value))
20702 (t (user-error "No valid file specified")))))))
20703 (user-error "No special environment to edit here")))
20704 (`table
20705 (if (eq (org-element-property :type element) 'table.el)
20706 (org-edit-table.el)
20707 (call-interactively 'org-table-edit-formulas)))
20708 ;; Only Org tables contain `table-row' type elements.
20709 (`table-row (call-interactively 'org-table-edit-formulas))
20710 (`example-block (org-edit-src-code))
20711 (`export-block (org-edit-export-block))
20712 (`fixed-width (org-edit-fixed-width-region))
20713 (`latex-environment (org-edit-latex-environment))
20715 ;; No notable element at point. Though, we may be at a link or
20716 ;; a footnote reference, which are objects. Thus, scan deeper.
20717 (let ((context (org-element-context element)))
20718 (pcase (org-element-type context)
20719 (`footnote-reference (org-edit-footnote-reference))
20720 (`inline-src-block (org-edit-inline-src-code))
20721 (`link (call-interactively #'ffap))
20722 (_ (user-error "No special environment to edit here"))))))))
20724 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20725 (defun org-ctrl-c-ctrl-c (&optional arg)
20726 "Set tags in headline, or update according to changed information at point.
20728 This command does many different things, depending on context:
20730 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20731 this is what we do.
20733 - If the cursor is on a statistics cookie, update it.
20735 - If the cursor is in a headline, prompt for tags and insert them
20736 into the current line, aligned to `org-tags-column'. When called
20737 with prefix arg, realign all tags in the current buffer.
20739 - If the cursor is in one of the special #+KEYWORD lines, this
20740 triggers scanning the buffer for these lines and updating the
20741 information.
20743 - If the cursor is inside a table, realign the table. This command
20744 works even if the automatic table editor has been turned off.
20746 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20747 the entire table.
20749 - If the cursor is at a footnote reference or definition, jump to
20750 the corresponding definition or references, respectively.
20752 - If the cursor is a the beginning of a dynamic block, update it.
20754 - If the current buffer is a capture buffer, close note and file it.
20756 - If the cursor is on a <<<target>>>, update radio targets and
20757 corresponding links in this buffer.
20759 - If the cursor is on a numbered item in a plain list, renumber the
20760 ordered list.
20762 - If the cursor is on a checkbox, toggle it.
20764 - If the cursor is on a code block, evaluate it. The variable
20765 `org-confirm-babel-evaluate' can be used to control prompting
20766 before code block evaluation, by default every code block
20767 evaluation requires confirmation. Code block evaluation can be
20768 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20769 (interactive "P")
20770 (cond
20771 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20772 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20773 (org-remove-occur-highlights)
20774 (message "Temporary highlights/overlays removed from current buffer"))
20775 ((and (local-variable-p 'org-finish-function)
20776 (fboundp org-finish-function))
20777 (funcall org-finish-function))
20778 ((org-babel-hash-at-point))
20779 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20781 (let* ((context
20782 (org-element-lineage
20783 (org-element-context)
20784 ;; Limit to supported contexts.
20785 '(babel-call clock dynamic-block footnote-definition
20786 footnote-reference inline-babel-call inline-src-block
20787 inlinetask item keyword node-property paragraph
20788 plain-list property-drawer radio-target src-block
20789 statistics-cookie table table-cell table-row
20790 timestamp)
20792 (type (org-element-type context)))
20793 ;; For convenience: at the first line of a paragraph on the same
20794 ;; line as an item, apply function on that item instead.
20795 (when (eq type 'paragraph)
20796 (let ((parent (org-element-property :parent context)))
20797 (when (and (eq (org-element-type parent) 'item)
20798 (= (line-beginning-position)
20799 (org-element-property :begin parent)))
20800 (setq context parent)
20801 (setq type 'item))))
20802 ;; Act according to type of element or object at point.
20804 ;; Do nothing on a blank line, except if it is contained in
20805 ;; a src block. Hence, we first check if point is in such
20806 ;; a block and then if it is at a blank line.
20807 (pcase type
20808 ((or `inline-src-block `src-block)
20809 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20810 (org-babel-eval-wipe-error-buffer)
20811 (org-babel-execute-src-block
20812 current-prefix-arg (org-babel-get-src-block-info nil context))))
20813 ((guard (org-match-line "[ \t]*$"))
20814 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20815 (user-error
20816 (substitute-command-keys
20817 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20818 ((or `babel-call `inline-babel-call)
20819 (let ((info (org-babel-lob-get-info context)))
20820 (when info (org-babel-execute-src-block nil info))))
20821 (`clock (org-clock-update-time-maybe))
20822 (`dynamic-block
20823 (save-excursion
20824 (goto-char (org-element-property :post-affiliated context))
20825 (org-update-dblock)))
20826 (`footnote-definition
20827 (goto-char (org-element-property :post-affiliated context))
20828 (call-interactively 'org-footnote-action))
20829 (`footnote-reference (call-interactively #'org-footnote-action))
20830 ((or `headline `inlinetask)
20831 (save-excursion (goto-char (org-element-property :begin context))
20832 (call-interactively #'org-set-tags)))
20833 (`item
20834 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20835 ;; unconditionally, whereas `C-u' will toggle its presence.
20836 ;; Without a universal argument, if the item has a checkbox,
20837 ;; toggle it. Otherwise repair the list.
20838 (let* ((box (org-element-property :checkbox context))
20839 (struct (org-element-property :structure context))
20840 (old-struct (copy-tree struct))
20841 (parents (org-list-parents-alist struct))
20842 (prevs (org-list-prevs-alist struct))
20843 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20844 (org-list-set-checkbox
20845 (org-element-property :begin context) struct
20846 (cond ((equal arg '(16)) "[-]")
20847 ((and (not box) (equal arg '(4))) "[ ]")
20848 ((or (not box) (equal arg '(4))) nil)
20849 ((eq box 'on) "[ ]")
20850 (t "[X]")))
20851 ;; Mimic `org-list-write-struct' but with grabbing a return
20852 ;; value from `org-list-struct-fix-box'.
20853 (org-list-struct-fix-ind struct parents 2)
20854 (org-list-struct-fix-item-end struct)
20855 (org-list-struct-fix-bul struct prevs)
20856 (org-list-struct-fix-ind struct parents)
20857 (let ((block-item
20858 (org-list-struct-fix-box struct parents prevs orderedp)))
20859 (if (and box (equal struct old-struct))
20860 (if (equal arg '(16))
20861 (message "Checkboxes already reset")
20862 (user-error "Cannot toggle this checkbox: %s"
20863 (if (eq box 'on)
20864 "all subitems checked"
20865 "unchecked subitems")))
20866 (org-list-struct-apply-struct struct old-struct)
20867 (org-update-checkbox-count-maybe))
20868 (when block-item
20869 (message "Checkboxes were removed due to empty box at line %d"
20870 (org-current-line block-item))))))
20871 (`keyword
20872 (let ((org-inhibit-startup-visibility-stuff t)
20873 (org-startup-align-all-tables nil))
20874 (when (boundp 'org-table-coordinate-overlays)
20875 (mapc #'delete-overlay org-table-coordinate-overlays)
20876 (setq org-table-coordinate-overlays nil))
20877 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20878 (message "Local setup has been refreshed"))
20879 (`plain-list
20880 ;; At a plain list, with a double C-u argument, set
20881 ;; checkboxes of each item to "[-]", whereas a single one
20882 ;; will toggle their presence according to the state of the
20883 ;; first item in the list. Without an argument, repair the
20884 ;; list.
20885 (let* ((begin (org-element-property :contents-begin context))
20886 (beginm (move-marker (make-marker) begin))
20887 (struct (org-element-property :structure context))
20888 (old-struct (copy-tree struct))
20889 (first-box (save-excursion
20890 (goto-char begin)
20891 (looking-at org-list-full-item-re)
20892 (match-string-no-properties 3)))
20893 (new-box (cond ((equal arg '(16)) "[-]")
20894 ((equal arg '(4)) (unless first-box "[ ]"))
20895 ((equal first-box "[X]") "[ ]")
20896 (t "[X]"))))
20897 (cond
20898 (arg
20899 (dolist (pos
20900 (org-list-get-all-items
20901 begin struct (org-list-prevs-alist struct)))
20902 (org-list-set-checkbox pos struct new-box)))
20903 ((and first-box (eq (point) begin))
20904 ;; For convenience, when point is at bol on the first
20905 ;; item of the list and no argument is provided, simply
20906 ;; toggle checkbox of that item, if any.
20907 (org-list-set-checkbox begin struct new-box)))
20908 (org-list-write-struct
20909 struct (org-list-parents-alist struct) old-struct)
20910 (org-update-checkbox-count-maybe)
20911 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20912 ((or `property-drawer `node-property)
20913 (call-interactively #'org-property-action))
20914 (`radio-target
20915 (call-interactively #'org-update-radio-target-regexp))
20916 (`statistics-cookie
20917 (call-interactively #'org-update-statistics-cookies))
20918 ((or `table `table-cell `table-row)
20919 ;; At a table, recalculate every field and align it. Also
20920 ;; send the table if necessary. If the table has
20921 ;; a `table.el' type, just give up. At a table row or cell,
20922 ;; maybe recalculate line but always align table.
20923 (if (eq (org-element-property :type context) 'table.el)
20924 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20925 Use `\\[org-edit-special]' to edit table.el tables"))
20926 (if (or (eq type 'table)
20927 ;; Check if point is at a TBLFM line.
20928 (and (eq type 'table-row)
20929 (= (point) (org-element-property :end context))))
20930 (save-excursion
20931 (if (org-at-TBLFM-p)
20932 (progn (require 'org-table)
20933 (org-table-calc-current-TBLFM))
20934 (goto-char (org-element-property :contents-begin context))
20935 (org-call-with-arg 'org-table-recalculate (or arg t))
20936 (orgtbl-send-table 'maybe)))
20937 (org-table-maybe-eval-formula)
20938 (cond (arg (call-interactively #'org-table-recalculate))
20939 ((org-table-maybe-recalculate-line))
20940 (t (org-table-align))))))
20941 (`timestamp (org-timestamp-change 0 'day))
20942 ((and `nil (guard (org-at-heading-p)))
20943 ;; When point is on an unsupported object type, we can miss
20944 ;; the fact that it also is at a heading. Handle it here.
20945 (call-interactively #'org-set-tags))
20946 ((guard
20947 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20949 (user-error
20950 (substitute-command-keys
20951 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20953 (defun org-mode-restart ()
20954 (interactive)
20955 (let ((indent-status (bound-and-true-p org-indent-mode)))
20956 (funcall major-mode)
20957 (hack-local-variables)
20958 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20959 (org-indent-mode -1))
20960 (org-reset-file-cache))
20961 (message "%s restarted" major-mode))
20963 (defun org-kill-note-or-show-branches ()
20964 "Abort storing current note, or call `outline-show-branches'."
20965 (interactive)
20966 (if (not org-finish-function)
20967 (progn
20968 (outline-hide-subtree)
20969 (call-interactively 'outline-show-branches))
20970 (let ((org-note-abort t))
20971 (funcall org-finish-function))))
20973 (defun org-delete-indentation (&optional arg)
20974 "Join current line to previous and fix whitespace at join.
20976 If previous line is a headline add to headline title. Otherwise
20977 the function calls `delete-indentation'.
20979 With a non-nil optional argument, join it to the following one."
20980 (interactive "*P")
20981 (if (save-excursion
20982 (beginning-of-line (if arg 1 0))
20983 (let ((case-fold-search nil))
20984 (looking-at org-complex-heading-regexp)))
20985 ;; At headline.
20986 (let ((tags-column (when (match-beginning 5)
20987 (save-excursion (goto-char (match-beginning 5))
20988 (current-column))))
20989 (string (concat " " (progn (when arg (forward-line 1))
20990 (org-trim (delete-and-extract-region
20991 (line-beginning-position)
20992 (line-end-position)))))))
20993 (unless (bobp) (delete-region (point) (1- (point))))
20994 (goto-char (or (match-end 4)
20995 (match-beginning 5)
20996 (match-end 0)))
20997 (skip-chars-backward " \t")
20998 (save-excursion (insert string))
20999 ;; Adjust alignment of tags.
21000 (cond
21001 ((not tags-column)) ;no tags
21002 (org-auto-align-tags (org-set-tags nil t))
21003 (t (org--align-tags-here tags-column)))) ;preserve tags column
21004 (delete-indentation arg)))
21006 (defun org-open-line (n)
21007 "Insert a new row in tables, call `open-line' elsewhere.
21008 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21009 As a special case, when a document starts with a table, allow to
21010 call `open-line' on the very first character."
21011 (interactive "*p")
21012 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21013 (org-table-insert-row)
21014 (open-line n)))
21016 (defun org-return (&optional indent)
21017 "Goto next table row or insert a newline.
21019 Calls `org-table-next-row' or `newline', depending on context.
21021 When optional INDENT argument is non-nil, call
21022 `newline-and-indent' instead of `newline'.
21024 When `org-return-follows-link' is non-nil and point is on
21025 a timestamp or a link, call `org-open-at-point'. However, it
21026 will not happen if point is in a table or on a \"dead\"
21027 object (e.g., within a comment). In these case, you need to use
21028 `org-open-at-point' directly."
21029 (interactive)
21030 (let ((context (if org-return-follows-link (org-element-context)
21031 (org-element-at-point))))
21032 (cond
21033 ;; In a table, call `org-table-next-row'.
21034 ((or (and (eq (org-element-type context) 'table)
21035 (>= (point) (org-element-property :contents-begin context))
21036 (< (point) (org-element-property :contents-end context)))
21037 (org-element-lineage context '(table-row table-cell) t))
21038 (org-table-justify-field-maybe)
21039 (call-interactively #'org-table-next-row))
21040 ;; On a link or a timestamp, call `org-open-at-point' if
21041 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21042 ;; locations, e.g., in a comment, as `org-open-at-point'.
21043 ((and org-return-follows-link
21044 (or (org-in-regexp org-ts-regexp-both nil t)
21045 (org-in-regexp org-tsr-regexp-both nil t)
21046 (org-in-regexp org-any-link-re nil t)))
21047 (call-interactively #'org-open-at-point))
21048 ;; Insert newline in heading, but preserve tags.
21049 ((and (not (bolp))
21050 (save-excursion (beginning-of-line)
21051 (let ((case-fold-search nil))
21052 (looking-at org-complex-heading-regexp))))
21053 ;; At headline. Split line. However, if point is on keyword,
21054 ;; priority cookie or tags, do not break any of them: add
21055 ;; a newline after the headline instead.
21056 (let ((tags-column (and (match-beginning 5)
21057 (save-excursion (goto-char (match-beginning 5))
21058 (current-column))))
21059 (string
21060 (when (and (match-end 4) (org-point-in-group (point) 4))
21061 (delete-and-extract-region (point) (match-end 4)))))
21062 ;; Adjust tag alignment.
21063 (cond
21064 ((not (and tags-column string)))
21065 (org-auto-align-tags (org-set-tags nil t))
21066 (t (org--align-tags-here tags-column))) ;preserve tags column
21067 (end-of-line)
21068 (org-show-entry)
21069 (if indent (newline-and-indent) (newline))
21070 (when string (save-excursion (insert (org-trim string))))))
21071 ;; In a list, make sure indenting keeps trailing text within.
21072 ((and indent
21073 (not (eolp))
21074 (org-element-lineage context '(item)))
21075 (let ((trailing-data
21076 (delete-and-extract-region (point) (line-end-position))))
21077 (newline-and-indent)
21078 (save-excursion (insert trailing-data))))
21079 (t (if indent (newline-and-indent) (newline))))))
21081 (defun org-return-indent ()
21082 "Goto next table row or insert a newline and indent.
21083 Calls `org-table-next-row' or `newline-and-indent', depending on
21084 context. See the individual commands for more information."
21085 (interactive)
21086 (org-return t))
21088 (defun org-ctrl-c-star ()
21089 "Compute table, or change heading status of lines.
21090 Calls `org-table-recalculate' or `org-toggle-heading',
21091 depending on context."
21092 (interactive)
21093 (cond
21094 ((org-at-table-p)
21095 (call-interactively 'org-table-recalculate))
21097 ;; Convert all lines in region to list items
21098 (call-interactively 'org-toggle-heading))))
21100 (defun org-ctrl-c-minus ()
21101 "Insert separator line in table or modify bullet status of line.
21102 Also turns a plain line or a region of lines into list items.
21103 Calls `org-table-insert-hline', `org-toggle-item', or
21104 `org-cycle-list-bullet', depending on context."
21105 (interactive)
21106 (cond
21107 ((org-at-table-p)
21108 (call-interactively 'org-table-insert-hline))
21109 ((org-region-active-p)
21110 (call-interactively 'org-toggle-item))
21111 ((org-in-item-p)
21112 (call-interactively 'org-cycle-list-bullet))
21114 (call-interactively 'org-toggle-item))))
21116 (defun org-toggle-heading (&optional nstars)
21117 "Convert headings to normal text, or items or text to headings.
21118 If there is no active region, only convert the current line.
21120 With a `\\[universal-argument]' prefix, convert the whole list at
21121 point into heading.
21123 In a region:
21125 - If the first non blank line is a headline, remove the stars
21126 from all headlines in the region.
21128 - If it is a normal line, turn each and every normal line (i.e.,
21129 not an heading or an item) in the region into headings. If you
21130 want to convert only the first line of this region, use one
21131 universal prefix argument.
21133 - If it is a plain list item, turn all plain list items into headings.
21135 When converting a line into a heading, the number of stars is chosen
21136 such that the lines become children of the current entry. However,
21137 when a numeric prefix argument is given, its value determines the
21138 number of stars to add."
21139 (interactive "P")
21140 (let ((skip-blanks
21141 (function
21142 ;; Return beginning of first non-blank line, starting from
21143 ;; line at POS.
21144 (lambda (pos)
21145 (save-excursion
21146 (goto-char pos)
21147 (while (org-at-comment-p) (forward-line))
21148 (skip-chars-forward " \r\t\n")
21149 (point-at-bol)))))
21150 beg end toggled)
21151 ;; Determine boundaries of changes. If a universal prefix has
21152 ;; been given, put the list in a region. If region ends at a bol,
21153 ;; do not consider the last line to be in the region.
21155 (when (and current-prefix-arg (org-at-item-p))
21156 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21157 (org-mark-element))
21159 (if (org-region-active-p)
21160 (setq beg (funcall skip-blanks (region-beginning))
21161 end (copy-marker (save-excursion
21162 (goto-char (region-end))
21163 (if (bolp) (point) (point-at-eol)))))
21164 (setq beg (funcall skip-blanks (point-at-bol))
21165 end (copy-marker (point-at-eol))))
21166 ;; Ensure inline tasks don't count as headings.
21167 (org-with-limited-levels
21168 (save-excursion
21169 (goto-char beg)
21170 (cond
21171 ;; Case 1. Started at an heading: de-star headings.
21172 ((org-at-heading-p)
21173 (while (< (point) end)
21174 (when (org-at-heading-p t)
21175 (looking-at org-outline-regexp) (replace-match "")
21176 (setq toggled t))
21177 (forward-line)))
21178 ;; Case 2. Started at an item: change items into headlines.
21179 ;; One star will be added by `org-list-to-subtree'.
21180 ((org-at-item-p)
21181 (while (< (point) end)
21182 (when (org-at-item-p)
21183 ;; Pay attention to cases when region ends before list.
21184 (let* ((struct (org-list-struct))
21185 (list-end
21186 (min (org-list-get-bottom-point struct) (1+ end))))
21187 (save-restriction
21188 (narrow-to-region (point) list-end)
21189 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21190 (setq toggled t))
21191 (forward-line)))
21192 ;; Case 3. Started at normal text: make every line an heading,
21193 ;; skipping headlines and items.
21194 (t (let* ((stars
21195 (make-string
21196 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21197 (add-stars
21198 (cond (nstars "") ; stars from prefix only
21199 ((equal stars "") "*") ; before first heading
21200 (org-odd-levels-only "**") ; inside heading, odd
21201 (t "*"))) ; inside heading, oddeven
21202 (rpl (concat stars add-stars " "))
21203 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21204 (while (< (point) (if (equal nstars '(4)) lend end))
21205 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21206 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21207 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21208 (forward-line)))))))
21209 (unless toggled (message "Cannot toggle heading from here"))))
21211 (defun org-meta-return (&optional arg)
21212 "Insert a new heading or wrap a region in a table.
21213 Calls `org-insert-heading', `org-insert-item' or
21214 `org-table-wrap-region', depending on context. When called with
21215 an argument, unconditionally call `org-insert-heading'."
21216 (interactive "P")
21217 (org-check-before-invisible-edit 'insert)
21218 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21219 (call-interactively (cond (arg #'org-insert-heading)
21220 ((org-at-table-p) #'org-table-wrap-region)
21221 ((org-in-item-p) #'org-insert-item)
21222 (t #'org-insert-heading)))))
21224 ;;; Menu entries
21226 (defsubst org-in-subtree-not-table-p ()
21227 "Are we in a subtree and not in a table?"
21228 (and (not (org-before-first-heading-p))
21229 (not (org-at-table-p))))
21231 ;; Define the Org mode menus
21232 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21233 '("Tbl"
21234 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21235 ["Next Field" org-cycle (org-at-table-p)]
21236 ["Previous Field" org-shifttab (org-at-table-p)]
21237 ["Next Row" org-return (org-at-table-p)]
21238 "--"
21239 ["Blank Field" org-table-blank-field (org-at-table-p)]
21240 ["Edit Field" org-table-edit-field (org-at-table-p)]
21241 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21242 "--"
21243 ("Column"
21244 ["Move Column Left" org-metaleft (org-at-table-p)]
21245 ["Move Column Right" org-metaright (org-at-table-p)]
21246 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21247 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21248 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
21249 ("Row"
21250 ["Move Row Up" org-metaup (org-at-table-p)]
21251 ["Move Row Down" org-metadown (org-at-table-p)]
21252 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21253 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21254 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21255 "--"
21256 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21257 ("Rectangle"
21258 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21259 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21260 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21261 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21262 "--"
21263 ("Calculate"
21264 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21265 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21266 ["Edit Formulas" org-edit-special (org-at-table-p)]
21267 "--"
21268 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21269 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21270 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21271 "--"
21272 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21273 "--"
21274 ["Sum Column/Rectangle" org-table-sum
21275 (or (org-at-table-p) (org-region-active-p))]
21276 ["Which Column?" org-table-current-column (org-at-table-p)])
21277 ["Debug Formulas"
21278 org-table-toggle-formula-debugger
21279 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21280 ["Show Col/Row Numbers"
21281 org-table-toggle-coordinate-overlays
21282 :style toggle
21283 :selected (bound-and-true-p org-table-overlay-coordinates)]
21284 "--"
21285 ["Create" org-table-create (not (org-at-table-p))]
21286 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21287 ["Import from File" org-table-import (not (org-at-table-p))]
21288 ["Export to File" org-table-export (org-at-table-p)]
21289 "--"
21290 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21291 "--"
21292 ("Plot"
21293 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21294 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21296 (easy-menu-define org-org-menu org-mode-map "Org menu"
21297 '("Org"
21298 ("Show/Hide"
21299 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21300 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21301 ["Sparse Tree..." org-sparse-tree t]
21302 ["Reveal Context" org-reveal t]
21303 ["Show All" outline-show-all t]
21304 "--"
21305 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21306 "--"
21307 ["New Heading" org-insert-heading t]
21308 ("Navigate Headings"
21309 ["Up" outline-up-heading t]
21310 ["Next" outline-next-visible-heading t]
21311 ["Previous" outline-previous-visible-heading t]
21312 ["Next Same Level" outline-forward-same-level t]
21313 ["Previous Same Level" outline-backward-same-level t]
21314 "--"
21315 ["Jump" org-goto t])
21316 ("Edit Structure"
21317 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21318 "--"
21319 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21320 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21321 "--"
21322 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21323 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21324 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21325 "--"
21326 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21327 "--"
21328 ["Copy visible text" org-copy-visible t]
21329 "--"
21330 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21331 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21332 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21333 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21334 "--"
21335 ["Sort Region/Children" org-sort t]
21336 "--"
21337 ["Convert to odd levels" org-convert-to-odd-levels t]
21338 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21339 ("Editing"
21340 ["Emphasis..." org-emphasize t]
21341 ["Edit Source Example" org-edit-special t]
21342 "--"
21343 ["Footnote new/jump" org-footnote-action t]
21344 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21345 ("Archive"
21346 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21347 "--"
21348 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21349 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21350 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21352 "--"
21353 ("Hyperlinks"
21354 ["Store Link (Global)" org-store-link t]
21355 ["Find existing link to here" org-occur-link-in-agenda-files t]
21356 ["Insert Link" org-insert-link t]
21357 ["Follow Link" org-open-at-point t]
21358 "--"
21359 ["Next link" org-next-link t]
21360 ["Previous link" org-previous-link t]
21361 "--"
21362 ["Descriptive Links"
21363 org-toggle-link-display
21364 :style radio
21365 :selected org-descriptive-links
21367 ["Literal Links"
21368 org-toggle-link-display
21369 :style radio
21370 :selected (not org-descriptive-links)])
21371 "--"
21372 ("TODO Lists"
21373 ["TODO/DONE/-" org-todo t]
21374 ("Select keyword"
21375 ["Next keyword" org-shiftright (org-at-heading-p)]
21376 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21377 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21378 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21379 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21380 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21381 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21382 "--"
21383 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21384 :selected org-enforce-todo-dependencies :style toggle :active t]
21385 "Settings for tree at point"
21386 ["Do Children sequentially" org-toggle-ordered-property :style radio
21387 :selected (org-entry-get nil "ORDERED")
21388 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21389 ["Do Children parallel" org-toggle-ordered-property :style radio
21390 :selected (not (org-entry-get nil "ORDERED"))
21391 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21392 "--"
21393 ["Set Priority" org-priority t]
21394 ["Priority Up" org-shiftup t]
21395 ["Priority Down" org-shiftdown t]
21396 "--"
21397 ["Get news from all feeds" org-feed-update-all t]
21398 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21399 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21400 ("TAGS and Properties"
21401 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21402 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21403 "--"
21404 ["Set property" org-set-property (not (org-before-first-heading-p))]
21405 ["Column view of properties" org-columns t]
21406 ["Insert Column View DBlock" org-columns-insert-dblock t])
21407 ("Dates and Scheduling"
21408 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21409 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21410 ("Change Date"
21411 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21412 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21413 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21414 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21415 ["Compute Time Range" org-evaluate-time-range t]
21416 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21417 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21418 "--"
21419 ["Custom time format" org-toggle-time-stamp-overlays
21420 :style radio :selected org-display-custom-times]
21421 "--"
21422 ["Goto Calendar" org-goto-calendar t]
21423 ["Date from Calendar" org-date-from-calendar t]
21424 "--"
21425 ["Start/Restart Timer" org-timer-start t]
21426 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21427 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21428 ["Insert Timer String" org-timer t]
21429 ["Insert Timer Item" org-timer-item t])
21430 ("Logging work"
21431 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21432 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21433 ["Clock out" org-clock-out t]
21434 ["Clock cancel" org-clock-cancel t]
21435 "--"
21436 ["Mark as default task" org-clock-mark-default-task t]
21437 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21438 ["Goto running clock" org-clock-goto t]
21439 "--"
21440 ["Display times" org-clock-display t]
21441 ["Create clock table" org-clock-report t]
21442 "--"
21443 ["Record DONE time"
21444 (progn (setq org-log-done (not org-log-done))
21445 (message "Switching to %s will %s record a timestamp"
21446 (car org-done-keywords)
21447 (if org-log-done "automatically" "not")))
21448 :style toggle :selected org-log-done])
21449 "--"
21450 ["Agenda Command..." org-agenda t]
21451 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21452 ("File List for Agenda")
21453 ("Special views current file"
21454 ["TODO Tree" org-show-todo-tree t]
21455 ["Check Deadlines" org-check-deadlines t]
21456 ["Tags/Property tree" org-match-sparse-tree t])
21457 "--"
21458 ["Export/Publish..." org-export-dispatch t]
21459 ("LaTeX"
21460 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21461 :selected org-cdlatex-mode]
21462 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21463 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21464 ["Modify math symbol" org-cdlatex-math-modify
21465 (org-inside-LaTeX-fragment-p)]
21466 ["Insert citation" org-reftex-citation t])
21467 "--"
21468 ("MobileOrg"
21469 ["Push Files and Views" org-mobile-push t]
21470 ["Get Captured and Flagged" org-mobile-pull t]
21471 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21472 "--"
21473 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21474 "--"
21475 ("Documentation"
21476 ["Show Version" org-version t]
21477 ["Info Documentation" org-info t])
21478 ("Customize"
21479 ["Browse Org Group" org-customize t]
21480 "--"
21481 ["Expand This Menu" org-create-customize-menu
21482 (fboundp 'customize-menu-create)])
21483 ["Send bug report" org-submit-bug-report t]
21484 "--"
21485 ("Refresh/Reload"
21486 ["Refresh setup current buffer" org-mode-restart t]
21487 ["Reload Org (after update)" org-reload t]
21488 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21491 (defun org-info (&optional node)
21492 "Read documentation for Org in the info system.
21493 With optional NODE, go directly to that node."
21494 (interactive)
21495 (info (format "(org)%s" (or node ""))))
21497 ;;;###autoload
21498 (defun org-submit-bug-report ()
21499 "Submit a bug report on Org via mail.
21501 Don't hesitate to report any problems or inaccurate documentation.
21503 If you don't have setup sending mail from (X)Emacs, please copy the
21504 output buffer into your mail program, as it gives us important
21505 information about your Org version and configuration."
21506 (interactive)
21507 (require 'reporter)
21508 (defvar reporter-prompt-for-summary-p)
21509 (org-load-modules-maybe)
21510 (org-require-autoloaded-modules)
21511 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21512 (reporter-submit-bug-report
21513 "emacs-orgmode@gnu.org"
21514 (org-version nil 'full)
21515 (let (list)
21516 (save-window-excursion
21517 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21518 (delete-other-windows)
21519 (erase-buffer)
21520 (insert "You are about to submit a bug report to the Org mailing list.
21522 We would like to add your full Org and Outline configuration to the
21523 bug report. This greatly simplifies the work of the maintainer and
21524 other experts on the mailing list.
21526 HOWEVER, some variables you have customized may contain private
21527 information. The names of customers, colleagues, or friends, might
21528 appear in the form of file names, tags, todo states, or search strings.
21529 If you answer yes to the prompt, you might want to check and remove
21530 such private information before sending the email.")
21531 (add-text-properties (point-min) (point-max) '(face org-warning))
21532 (when (yes-or-no-p "Include your Org configuration ")
21533 (mapatoms
21534 (lambda (v)
21535 (and (boundp v)
21536 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21537 (or (and (symbol-value v)
21538 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21539 (and
21540 (get v 'custom-type) (get v 'standard-value)
21541 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21542 (push v list)))))
21543 (kill-buffer (get-buffer "*Warn about privacy*"))
21544 list))
21545 nil nil
21546 "Remember to cover the basics, that is, what you expected to happen and
21547 what in fact did happen. You don't know how to make a good report? See
21549 http://orgmode.org/manual/Feedback.html#Feedback
21551 Your bug report will be posted to the Org mailing list.
21552 ------------------------------------------------------------------------")
21553 (save-excursion
21554 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21555 (replace-match "\\1Bug: \\3 [\\2]")))))
21558 (defun org-install-agenda-files-menu ()
21559 (let ((bl (buffer-list)))
21560 (save-excursion
21561 (while bl
21562 (set-buffer (pop bl))
21563 (when (derived-mode-p 'org-mode) (setq bl nil)))
21564 (when (derived-mode-p 'org-mode)
21565 (easy-menu-change
21566 '("Org") "File List for Agenda"
21567 (append
21568 (list
21569 ["Edit File List" (org-edit-agenda-file-list) t]
21570 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21571 ["Remove Current File from List" org-remove-file t]
21572 ["Cycle through agenda files" org-cycle-agenda-files t]
21573 ["Occur in all agenda files" org-occur-in-agenda-files t]
21574 "--")
21575 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21577 ;;;; Documentation
21579 (defun org-require-autoloaded-modules ()
21580 (interactive)
21581 (mapc #'require
21582 '(org-agenda org-archive org-attach org-clock org-colview org-id
21583 org-table org-timer)))
21585 ;;;###autoload
21586 (defun org-reload (&optional uncompiled)
21587 "Reload all org lisp files.
21588 With prefix arg UNCOMPILED, load the uncompiled versions."
21589 (interactive "P")
21590 (require 'loadhist)
21591 (let* ((org-dir (org-find-library-dir "org"))
21592 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21593 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21594 (remove-re (format "\\`%s\\'"
21595 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21596 (feats (delete-dups
21597 (mapcar 'file-name-sans-extension
21598 (mapcar 'file-name-nondirectory
21599 (delq nil
21600 (mapcar 'feature-file
21601 features))))))
21602 (lfeat (append
21603 (sort
21604 (setq feats
21605 (delq nil (mapcar
21606 (lambda (f)
21607 (if (and (string-match feature-re f)
21608 (not (string-match remove-re f)))
21609 f nil))
21610 feats)))
21611 'string-lessp)
21612 (list "org-version" "org")))
21613 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21614 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21615 load-uncore load-misses)
21616 (setq load-misses
21617 (delq 't
21618 (mapcar (lambda (f)
21619 (or (org-load-noerror-mustsuffix (concat org-dir f))
21620 (and (string= org-dir contrib-dir)
21621 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21622 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21623 (add-to-list 'load-uncore f 'append)
21626 lfeat)))
21627 (when load-uncore
21628 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21629 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21630 (if load-misses
21631 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21632 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21633 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21635 ;;;###autoload
21636 (defun org-customize ()
21637 "Call the customize function with org as argument."
21638 (interactive)
21639 (org-load-modules-maybe)
21640 (org-require-autoloaded-modules)
21641 (customize-browse 'org))
21643 (defun org-create-customize-menu ()
21644 "Create a full customization menu for Org mode, insert it into the menu."
21645 (interactive)
21646 (org-load-modules-maybe)
21647 (org-require-autoloaded-modules)
21648 (if (fboundp 'customize-menu-create)
21649 (progn
21650 (easy-menu-change
21651 '("Org") "Customize"
21652 `(["Browse Org group" org-customize t]
21653 "--"
21654 ,(customize-menu-create 'org)
21655 ["Set" Custom-set t]
21656 ["Save" Custom-save t]
21657 ["Reset to Current" Custom-reset-current t]
21658 ["Reset to Saved" Custom-reset-saved t]
21659 ["Reset to Standard Settings" Custom-reset-standard t]))
21660 (message "\"Org\"-menu now contains full customization menu"))
21661 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21663 ;;;; Miscellaneous stuff
21665 ;;; Generally useful functions
21667 (defun org-get-at-eol (property n)
21668 "Get text property PROPERTY at the end of line less N characters."
21669 (get-text-property (- (point-at-eol) n) property))
21671 (defun org-find-text-property-in-string (prop s)
21672 "Return the first non-nil value of property PROP in string S."
21673 (or (get-text-property 0 prop s)
21674 (get-text-property (or (next-single-property-change 0 prop s) 0)
21675 prop s)))
21677 (defun org-display-warning (message)
21678 "Display the given MESSAGE as a warning."
21679 (display-warning 'org message :warning))
21681 (defun org-eval (form)
21682 "Eval FORM and return result."
21683 (condition-case error
21684 (eval form)
21685 (error (format "%%![Error: %s]" error))))
21687 (defun org-in-clocktable-p ()
21688 "Check if the cursor is in a clocktable."
21689 (let ((pos (point)) start)
21690 (save-excursion
21691 (end-of-line 1)
21692 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21693 (setq start (match-beginning 0))
21694 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21695 (>= (match-end 0) pos)
21696 start))))
21698 (defun org-in-verbatim-emphasis ()
21699 (save-match-data
21700 (and (org-in-regexp org-verbatim-re 2)
21701 (>= (point) (match-beginning 3))
21702 (<= (point) (match-end 4)))))
21704 (defun org-overlay-display (ovl text &optional face evap)
21705 "Make overlay OVL display TEXT with face FACE."
21706 (overlay-put ovl 'display text)
21707 (if face (overlay-put ovl 'face face))
21708 (if evap (overlay-put ovl 'evaporate t)))
21710 (defun org-overlay-before-string (ovl text &optional face evap)
21711 "Make overlay OVL display TEXT with face FACE."
21712 (if face (org-add-props text nil 'face face))
21713 (overlay-put ovl 'before-string text)
21714 (if evap (overlay-put ovl 'evaporate t)))
21716 (defun org-find-overlays (prop &optional pos delete)
21717 "Find all overlays specifying PROP at POS or point.
21718 If DELETE is non-nil, delete all those overlays."
21719 (let (found)
21720 (dolist (ov (overlays-at (or pos (point))) found)
21721 (cond ((not (overlay-get ov prop)))
21722 (delete (delete-overlay ov))
21723 (t (push ov found))))))
21725 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21726 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21727 (if (and marker (marker-buffer marker)
21728 (buffer-live-p (marker-buffer marker)))
21729 (progn
21730 (pop-to-buffer-same-window (marker-buffer marker))
21731 (when (or (> marker (point-max)) (< marker (point-min)))
21732 (widen))
21733 (goto-char marker)
21734 (org-show-context 'org-goto))
21735 (if bookmark
21736 (bookmark-jump bookmark)
21737 (error "Cannot find location"))))
21739 (defun org-quote-csv-field (s)
21740 "Quote field for inclusion in CSV material."
21741 (if (string-match "[\",]" s)
21742 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21745 (defun org-force-self-insert (N)
21746 "Needed to enforce self-insert under remapping."
21747 (interactive "p")
21748 (self-insert-command N))
21750 (defun org-shorten-string (s maxlength)
21751 "Shorten string S so that it is no longer than MAXLENGTH characters.
21752 If the string is shorter or has length MAXLENGTH, just return the
21753 original string. If it is longer, the functions finds a space in the
21754 string, breaks this string off at that locations and adds three dots
21755 as ellipsis. Including the ellipsis, the string will not be longer
21756 than MAXLENGTH. If finding a good breaking point in the string does
21757 not work, the string is just chopped off in the middle of a word
21758 if necessary."
21759 (if (<= (length s) maxlength)
21761 (let* ((n (max (- maxlength 4) 1))
21762 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21763 (if (string-match re s)
21764 (concat (match-string 1 s) "...")
21765 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21767 (defun org-get-indentation (&optional line)
21768 "Get the indentation of the current line, interpreting tabs.
21769 When LINE is given, assume it represents a line and compute its indentation."
21770 (if line
21771 (when (string-match "^ *" (org-remove-tabs line))
21772 (match-end 0))
21773 (save-excursion
21774 (beginning-of-line 1)
21775 (skip-chars-forward " \t")
21776 (current-column))))
21778 (defun org-get-string-indentation (s)
21779 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21780 (let ((n -1) (i 0) (w tab-width) c)
21781 (catch 'exit
21782 (while (< (setq n (1+ n)) (length s))
21783 (setq c (aref s n))
21784 (cond ((= c ?\ ) (setq i (1+ i)))
21785 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21786 (t (throw 'exit t)))))
21789 (defun org-remove-tabs (s &optional width)
21790 "Replace tabulators in S with spaces.
21791 Assumes that s is a single line, starting in column 0."
21792 (setq width (or width tab-width))
21793 (while (string-match "\t" s)
21794 (setq s (replace-match
21795 (make-string
21796 (- (* width (/ (+ (match-beginning 0) width) width))
21797 (match-beginning 0)) ?\ )
21798 t t s)))
21801 (defun org-fix-indentation (line ind)
21802 "Fix indentation in LINE.
21803 IND is a cons cell with target and minimum indentation.
21804 If the current indentation in LINE is smaller than the minimum,
21805 leave it alone. If it is larger than ind, set it to the target."
21806 (let* ((l (org-remove-tabs line))
21807 (i (org-get-indentation l))
21808 (i1 (car ind)) (i2 (cdr ind)))
21809 (when (>= i i2) (setq l (substring line i2)))
21810 (if (> i1 0)
21811 (concat (make-string i1 ?\ ) l)
21812 l)))
21814 (defun org-remove-indentation (code &optional n)
21815 "Remove maximum common indentation in string CODE and return it.
21816 N may optionally be the number of columns to remove. Return CODE
21817 as-is if removal failed."
21818 (with-temp-buffer
21819 (insert code)
21820 (if (org-do-remove-indentation n) (buffer-string) code)))
21822 (defun org-do-remove-indentation (&optional n)
21823 "Remove the maximum common indentation from the buffer.
21824 When optional argument N is a positive integer, remove exactly
21825 that much characters from indentation, if possible. Return nil
21826 if it fails."
21827 (catch :exit
21828 (goto-char (point-min))
21829 ;; Find maximum common indentation, if not specified.
21830 (let ((n (or n
21831 (let ((min-ind (point-max)))
21832 (save-excursion
21833 (while (re-search-forward "^[ \t]*\\S-" nil t)
21834 (let ((ind (1- (current-column))))
21835 (if (zerop ind) (throw :exit nil)
21836 (setq min-ind (min min-ind ind))))))
21837 min-ind))))
21838 (if (zerop n) (throw :exit nil)
21839 ;; Remove exactly N indentation, but give up if not possible.
21840 (while (not (eobp))
21841 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21842 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21843 ((< ind n) (throw :exit nil))
21844 (t (indent-line-to (- ind n))))
21845 (forward-line)))
21846 ;; Signal success.
21847 t))))
21849 (defun org-fill-template (template alist)
21850 "Find each %key of ALIST in TEMPLATE and replace it."
21851 (let ((case-fold-search nil))
21852 (dolist (entry (sort (copy-sequence alist)
21853 (lambda (a b) (< (length (car a)) (length (car b))))))
21854 (setq template
21855 (replace-regexp-in-string
21856 (concat "%" (regexp-quote (car entry)))
21857 (or (cdr entry) "") template t t)))
21858 template))
21860 (defun org-base-buffer (buffer)
21861 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21862 (if (not buffer)
21863 buffer
21864 (or (buffer-base-buffer buffer)
21865 buffer)))
21867 (defun org-wrap (string &optional width lines)
21868 "Wrap string to either a number of lines, or a width in characters.
21869 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21870 that costs. If there is a word longer than WIDTH, the text is actually
21871 wrapped to the length of that word.
21872 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21873 many lines, whatever width that takes.
21874 The return value is a list of lines, without newlines at the end."
21875 (let* ((words (split-string string))
21876 (maxword (apply 'max (mapcar 'org-string-width words)))
21877 w ll)
21878 (cond (width
21879 (org-do-wrap words (max maxword width)))
21880 (lines
21881 (setq w maxword)
21882 (setq ll (org-do-wrap words maxword))
21883 (if (<= (length ll) lines)
21885 (setq ll words)
21886 (while (> (length ll) lines)
21887 (setq w (1+ w))
21888 (setq ll (org-do-wrap words w)))
21889 ll))
21890 (t (error "Cannot wrap this")))))
21892 (defun org-do-wrap (words width)
21893 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21894 (let (lines line)
21895 (while words
21896 (setq line (pop words))
21897 (while (and words (< (+ (length line) (length (car words))) width))
21898 (setq line (concat line " " (pop words))))
21899 (setq lines (push line lines)))
21900 (nreverse lines)))
21902 (defun org-quote-vert (s)
21903 "Replace \"|\" with \"\\vert\"."
21904 (while (string-match "|" s)
21905 (setq s (replace-match "\\vert" t t s)))
21908 (defun org-uuidgen-p (s)
21909 "Is S an ID created by UUIDGEN?"
21910 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21912 (defun org-in-src-block-p (&optional inside)
21913 "Whether point is in a code source block.
21914 When INSIDE is non-nil, don't consider we are within a src block
21915 when point is at #+BEGIN_SRC or #+END_SRC."
21916 (let ((case-fold-search t))
21917 (or (and (eq (get-char-property (point) 'src-block) t))
21918 (and (not inside)
21919 (save-match-data
21920 (save-excursion
21921 (beginning-of-line)
21922 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21924 (defun org-context ()
21925 "Return a list of contexts of the current cursor position.
21926 If several contexts apply, all are returned.
21927 Each context entry is a list with a symbol naming the context, and
21928 two positions indicating start and end of the context. Possible
21929 contexts are:
21931 :headline anywhere in a headline
21932 :headline-stars on the leading stars in a headline
21933 :todo-keyword on a TODO keyword (including DONE) in a headline
21934 :tags on the TAGS in a headline
21935 :priority on the priority cookie in a headline
21936 :item on the first line of a plain list item
21937 :item-bullet on the bullet/number of a plain list item
21938 :checkbox on the checkbox in a plain list item
21939 :table in an Org table
21940 :table-special on a special filed in a table
21941 :table-table in a table.el table
21942 :clocktable in a clocktable
21943 :src-block in a source block
21944 :link on a hyperlink
21945 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21946 :target on a <<target>>
21947 :radio-target on a <<<radio-target>>>
21948 :latex-fragment on a LaTeX fragment
21949 :latex-preview on a LaTeX fragment with overlaid preview image
21951 This function expects the position to be visible because it uses font-lock
21952 faces as a help to recognize the following contexts: :table-special, :link,
21953 and :keyword."
21954 (let* ((f (get-text-property (point) 'face))
21955 (faces (if (listp f) f (list f)))
21956 (case-fold-search t)
21957 (p (point)) clist o)
21958 ;; First the large context
21959 (cond
21960 ((org-at-heading-p t)
21961 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21962 (when (progn
21963 (beginning-of-line 1)
21964 (looking-at org-todo-line-tags-regexp))
21965 (push (org-point-in-group p 1 :headline-stars) clist)
21966 (push (org-point-in-group p 2 :todo-keyword) clist)
21967 (push (org-point-in-group p 4 :tags) clist))
21968 (goto-char p)
21969 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21970 (when (looking-at "\\[#[A-Z0-9]\\]")
21971 (push (org-point-in-group p 0 :priority) clist)))
21973 ((org-at-item-p)
21974 (push (org-point-in-group p 2 :item-bullet) clist)
21975 (push (list :item (point-at-bol)
21976 (save-excursion (org-end-of-item) (point)))
21977 clist)
21978 (and (org-at-item-checkbox-p)
21979 (push (org-point-in-group p 0 :checkbox) clist)))
21981 ((org-at-table-p)
21982 (push (list :table (org-table-begin) (org-table-end)) clist)
21983 (when (memq 'org-formula faces)
21984 (push (list :table-special
21985 (previous-single-property-change p 'face)
21986 (next-single-property-change p 'face)) clist)))
21987 ((org-at-table-p 'any)
21988 (push (list :table-table) clist)))
21989 (goto-char p)
21991 (let ((case-fold-search t))
21992 ;; New the "medium" contexts: clocktables, source blocks
21993 (cond ((org-in-clocktable-p)
21994 (push (list :clocktable
21995 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21996 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21997 (match-beginning 1))
21998 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21999 (match-end 0))) clist))
22000 ((org-in-src-block-p)
22001 (push (list :src-block
22002 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22003 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22004 (match-beginning 1))
22005 (and (search-forward "#+END_SRC" nil t)
22006 (match-beginning 0))) clist))))
22007 (goto-char p)
22009 ;; Now the small context
22010 (cond
22011 ((org-at-timestamp-p)
22012 (push (org-point-in-group p 0 :timestamp) clist))
22013 ((memq 'org-link faces)
22014 (push (list :link
22015 (previous-single-property-change p 'face)
22016 (next-single-property-change p 'face)) clist))
22017 ((memq 'org-special-keyword faces)
22018 (push (list :keyword
22019 (previous-single-property-change p 'face)
22020 (next-single-property-change p 'face)) clist))
22021 ((org-at-target-p)
22022 (push (org-point-in-group p 0 :target) clist)
22023 (goto-char (1- (match-beginning 0)))
22024 (when (looking-at org-radio-target-regexp)
22025 (push (org-point-in-group p 0 :radio-target) clist))
22026 (goto-char p))
22027 ((setq o (cl-some
22028 (lambda (o)
22029 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22031 (overlays-at (point))))
22032 (push (list :latex-fragment
22033 (overlay-start o) (overlay-end o)) clist)
22034 (push (list :latex-preview
22035 (overlay-start o) (overlay-end o)) clist))
22036 ((org-inside-LaTeX-fragment-p)
22037 ;; FIXME: positions wrong.
22038 (push (list :latex-fragment (point) (point)) clist)))
22040 (setq clist (nreverse (delq nil clist)))
22041 clist))
22043 (defun org-in-regexp (regexp &optional nlines visually)
22044 "Check if point is inside a match of REGEXP.
22046 Normally only the current line is checked, but you can include
22047 NLINES extra lines around point into the search. If VISUALLY is
22048 set, require that the cursor is not after the match but really
22049 on, so that the block visually is on the match.
22051 Return nil or a cons cell (BEG . END) where BEG and END are,
22052 respectively, the positions at the beginning and the end of the
22053 match."
22054 (catch :exit
22055 (let ((pos (point))
22056 (eol (line-end-position (if nlines (1+ nlines) 1))))
22057 (save-excursion
22058 (beginning-of-line (- 1 (or nlines 0)))
22059 (while (and (re-search-forward regexp eol t)
22060 (<= (match-beginning 0) pos))
22061 (let ((end (match-end 0)))
22062 (when (or (> end pos) (and (= end pos) (not visually)))
22063 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22065 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22066 "Non-nil when point is between matches of START-RE and END-RE.
22068 Also return a non-nil value when point is on one of the matches.
22070 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22071 buffer positions. Default values are the positions of headlines
22072 surrounding the point.
22074 The functions returns a cons cell whose car (resp. cdr) is the
22075 position before START-RE (resp. after END-RE)."
22076 (save-match-data
22077 (let ((pos (point))
22078 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22079 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22080 beg end)
22081 (save-excursion
22082 ;; Point is on a block when on START-RE or if START-RE can be
22083 ;; found before it...
22084 (and (or (org-in-regexp start-re)
22085 (re-search-backward start-re limit-up t))
22086 (setq beg (match-beginning 0))
22087 ;; ... and END-RE after it...
22088 (goto-char (match-end 0))
22089 (re-search-forward end-re limit-down t)
22090 (> (setq end (match-end 0)) pos)
22091 ;; ... without another START-RE in-between.
22092 (goto-char (match-beginning 0))
22093 (not (re-search-backward start-re (1+ beg) t))
22094 ;; Return value.
22095 (cons beg end))))))
22097 (defun org-in-block-p (names)
22098 "Non-nil when point belongs to a block whose name belongs to NAMES.
22100 NAMES is a list of strings containing names of blocks.
22102 Return first block name matched, or nil. Beware that in case of
22103 nested blocks, the returned name may not belong to the closest
22104 block from point."
22105 (save-match-data
22106 (catch 'exit
22107 (let ((case-fold-search t)
22108 (lim-up (save-excursion (outline-previous-heading)))
22109 (lim-down (save-excursion (outline-next-heading))))
22110 (dolist (name names)
22111 (let ((n (regexp-quote name)))
22112 (when (org-between-regexps-p
22113 (concat "^[ \t]*#\\+begin_" n)
22114 (concat "^[ \t]*#\\+end_" n)
22115 lim-up lim-down)
22116 (throw 'exit n)))))
22117 nil)))
22119 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22120 "Call `multi-occur' with buffers for all agenda files."
22121 (interactive "sOrg-files matching: ")
22122 (let* ((files (org-agenda-files))
22123 (tnames (mapcar #'file-truename files))
22124 (extra org-agenda-text-search-extra-files))
22125 (when (eq (car extra) 'agenda-archives)
22126 (setq extra (cdr extra))
22127 (setq files (org-add-archive-files files)))
22128 (dolist (f extra)
22129 (unless (member (file-truename f) tnames)
22130 (unless (member f files) (setq files (append files (list f))))
22131 (setq tnames (append tnames (list (file-truename f))))))
22132 (multi-occur
22133 (mapcar (lambda (x)
22134 (with-current-buffer
22135 ;; FIXME: Why not just (find-file-noselect x)?
22136 ;; Is it to avoid the "revert buffer" prompt?
22137 (or (get-file-buffer x) (find-file-noselect x))
22138 (widen)
22139 (current-buffer)))
22140 files)
22141 regexp)))
22143 (add-hook 'occur-mode-find-occurrence-hook
22144 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22146 (defun org-occur-link-in-agenda-files ()
22147 "Create a link and search for it in the agendas.
22148 The link is not stored in `org-stored-links', it is just created
22149 for the search purpose."
22150 (interactive)
22151 (let ((link (condition-case nil
22152 (org-store-link nil)
22153 (error "Unable to create a link to here"))))
22154 (org-occur-in-agenda-files (regexp-quote link))))
22156 (defun org-reverse-string (string)
22157 "Return the reverse of STRING."
22158 (apply 'string (reverse (string-to-list string))))
22160 ;; defsubst org-uniquify must be defined before first use
22162 (defun org-uniquify-alist (alist)
22163 "Merge elements of ALIST with the same key.
22165 For example, in this alist:
22167 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22168 => \\='((a 1 3) (b 2))
22170 merge (a 1) and (a 3) into (a 1 3).
22172 The function returns the new ALIST."
22173 (let (rtn)
22174 (dolist (e alist rtn)
22175 (let (n)
22176 (if (not (assoc (car e) rtn))
22177 (push e rtn)
22178 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22179 (setq rtn (assq-delete-all (car e) rtn))
22180 (push n rtn))))))
22182 (defun org-delete-all (elts list)
22183 "Remove all elements in ELTS from LIST.
22184 Comparison is done with `equal'. It is a destructive operation
22185 that may remove elements by altering the list structure."
22186 (while elts
22187 (setq list (delete (pop elts) list)))
22188 list)
22190 (defun org-back-over-empty-lines ()
22191 "Move backwards over whitespace, to the beginning of the first empty line.
22192 Returns the number of empty lines passed."
22193 (let ((pos (point)))
22194 (if (cdr (assq 'heading org-blank-before-new-entry))
22195 (skip-chars-backward " \t\n\r")
22196 (unless (eobp)
22197 (forward-line -1)))
22198 (beginning-of-line 2)
22199 (goto-char (min (point) pos))
22200 (count-lines (point) pos)))
22202 (defun org-skip-whitespace ()
22203 (skip-chars-forward " \t\n\r"))
22205 (defun org-point-in-group (point group &optional context)
22206 "Check if POINT is in match-group GROUP.
22207 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22208 match. If the match group does not exist or point is not inside it,
22209 return nil."
22210 (and (match-beginning group)
22211 (>= point (match-beginning group))
22212 (<= point (match-end group))
22213 (if context
22214 (list context (match-beginning group) (match-end group))
22215 t)))
22217 (defun org-switch-to-buffer-other-window (&rest args)
22218 "Switch to buffer in a second window on the current frame.
22219 In particular, do not allow pop-up frames.
22220 Returns the newly created buffer."
22221 (org-no-popups
22222 (apply 'switch-to-buffer-other-window args)))
22224 (defun org-combine-plists (&rest plists)
22225 "Create a single property list from all plists in PLISTS.
22226 The process starts by copying the first list, and then setting properties
22227 from the other lists. Settings in the last list are the most significant
22228 ones and overrule settings in the other lists."
22229 (let ((rtn (copy-sequence (pop plists)))
22230 p v ls)
22231 (while plists
22232 (setq ls (pop plists))
22233 (while ls
22234 (setq p (pop ls) v (pop ls))
22235 (setq rtn (plist-put rtn p v))))
22236 rtn))
22238 (defun org-replace-escapes (string table)
22239 "Replace %-escapes in STRING with values in TABLE.
22240 TABLE is an association list with keys like \"%a\" and string values.
22241 The sequences in STRING may contain normal field width and padding information,
22242 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22243 so values can contain further %-escapes if they are define later in TABLE."
22244 (let ((tbl (copy-alist table))
22245 (case-fold-search nil)
22246 (pchg 0)
22247 re rpl)
22248 (dolist (e tbl)
22249 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22250 (when (and (cdr e) (string-match re (cdr e)))
22251 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22252 (safe "SREF"))
22253 (add-text-properties 0 3 (list 'sref sref) safe)
22254 (setcdr e (replace-match safe t t (cdr e)))))
22255 (while (string-match re string)
22256 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22257 (cdr e)))
22258 (setq string (replace-match rpl t t string))))
22259 (while (setq pchg (next-property-change pchg string))
22260 (let ((sref (get-text-property pchg 'sref string)))
22261 (when (and sref (string-match "SREF" string pchg))
22262 (setq string (replace-match sref t t string)))))
22263 string))
22265 (defun org-find-base-buffer-visiting (file)
22266 "Like `find-buffer-visiting' but always return the base buffer and
22267 not an indirect buffer."
22268 (let ((buf (or (get-file-buffer file)
22269 (find-buffer-visiting file))))
22270 (if buf
22271 (or (buffer-base-buffer buf) buf)
22272 nil)))
22274 ;;; TODO: Only called once, from ox-odt which should probably use
22275 ;;; org-export-inline-image-p or something.
22276 (defun org-file-image-p (file)
22277 "Return non-nil if FILE is an image."
22278 (save-match-data
22279 (string-match (image-file-name-regexp) file)))
22281 (defun org-get-cursor-date (&optional with-time)
22282 "Return the date at cursor in as a time.
22283 This works in the calendar and in the agenda, anywhere else it just
22284 returns the current time.
22285 If WITH-TIME is non-nil, returns the time of the event at point (in
22286 the agenda) or the current time of the day."
22287 (let (date day defd tp hod mod)
22288 (when with-time
22289 (setq tp (get-text-property (point) 'time))
22290 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22291 (setq hod (string-to-number (match-string 1 tp))
22292 mod (string-to-number (match-string 2 tp))))
22293 (or tp (let ((now (decode-time)))
22294 (setq hod (nth 2 now)
22295 mod (nth 1 now)))))
22296 (cond
22297 ((eq major-mode 'calendar-mode)
22298 (setq date (calendar-cursor-to-date)
22299 defd (encode-time 0 (or mod 0) (or hod 0)
22300 (nth 1 date) (nth 0 date) (nth 2 date))))
22301 ((eq major-mode 'org-agenda-mode)
22302 (setq day (get-text-property (point) 'day))
22303 (when day
22304 (setq date (calendar-gregorian-from-absolute day)
22305 defd (encode-time 0 (or mod 0) (or hod 0)
22306 (nth 1 date) (nth 0 date) (nth 2 date))))))
22307 (or defd (current-time))))
22309 (defun org-mark-subtree (&optional up)
22310 "Mark the current subtree.
22311 This puts point at the start of the current subtree, and mark at
22312 the end. If a numeric prefix UP is given, move up into the
22313 hierarchy of headlines by UP levels before marking the subtree."
22314 (interactive "P")
22315 (org-with-limited-levels
22316 (cond ((org-at-heading-p) (beginning-of-line))
22317 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22318 (t (outline-previous-visible-heading 1))))
22319 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22320 (if (called-interactively-p 'any)
22321 (call-interactively 'org-mark-element)
22322 (org-mark-element)))
22324 (defun org-file-newer-than-p (file time)
22325 "Non-nil if FILE is newer than TIME.
22326 FILE is a filename, as a string, TIME is a list of integers, as
22327 returned by, e.g., `current-time'."
22328 (and (file-exists-p file)
22329 ;; Only compare times up to whole seconds as some file-systems
22330 ;; (e.g. HFS+) do not retain any finer granularity. As
22331 ;; a consequence, make sure we return non-nil when the two
22332 ;; times are equal.
22333 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22334 (cl-subseq time 0 2)))))
22336 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22337 "Compile a SOURCE file using PROCESS.
22339 PROCESS is either a function or a list of shell commands, as
22340 strings. EXT is a file extension, without the leading dot, as
22341 a string. It is used to check if the process actually succeeded.
22343 PROCESS must create a file with the same base name and directory
22344 as SOURCE, but ending with EXT. The function then returns its
22345 filename. Otherwise, it raises an error. The error message can
22346 then be refined by providing string ERR-MSG, which is appended to
22347 the standard message.
22349 If PROCESS is a function, it is called with a single argument:
22350 the SOURCE file.
22352 If it is a list of commands, each of them is called using
22353 `shell-command'. By default, in each command, %b, %f, %F, %o and
22354 %O are replaced with, respectively, SOURCE base name, name, full
22355 name, directory and absolute output file name. It is possible,
22356 however, to use more place-holders by specifying them in optional
22357 argument SPEC, as an alist following the pattern
22359 (CHARACTER . REPLACEMENT-STRING).
22361 When PROCESS is a list of commands, optional argument LOG-BUF can
22362 be set to a buffer or a buffer name. `shell-command' then uses
22363 it for output."
22364 (let* ((base-name (file-name-base source))
22365 (full-name (file-truename source))
22366 (out-dir (or (file-name-directory source) "./"))
22367 (output (expand-file-name (concat base-name "." ext) out-dir))
22368 (time (current-time))
22369 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22370 (save-window-excursion
22371 (pcase process
22372 ((pred functionp) (funcall process (shell-quote-argument source)))
22373 ((pred consp)
22374 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22375 (spec (append spec
22376 `((?b . ,(shell-quote-argument base-name))
22377 (?f . ,(shell-quote-argument source))
22378 (?F . ,(shell-quote-argument full-name))
22379 (?o . ,(shell-quote-argument out-dir))
22380 (?O . ,(shell-quote-argument output))))))
22381 (dolist (command process)
22382 (shell-command (format-spec command spec) log-buf))
22383 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22384 (_ (error "No valid command to process %S%s" source err-msg))))
22385 ;; Check for process failure. Output file is expected to be
22386 ;; located in the same directory as SOURCE.
22387 (unless (org-file-newer-than-p output time)
22388 (error (format "File %S wasn't produced%s" output err-msg)))
22389 output))
22391 ;;; Indentation
22393 (defvar org-element-greater-elements)
22394 (defun org--get-expected-indentation (element contentsp)
22395 "Expected indentation column for current line, according to ELEMENT.
22396 ELEMENT is an element containing point. CONTENTSP is non-nil
22397 when indentation is to be computed according to contents of
22398 ELEMENT."
22399 (let ((type (org-element-type element))
22400 (start (org-element-property :begin element))
22401 (post-affiliated (org-element-property :post-affiliated element)))
22402 (org-with-wide-buffer
22403 (cond
22404 (contentsp
22405 (cl-case type
22406 ((diary-sexp footnote-definition) 0)
22407 ((headline inlinetask nil)
22408 (if (not org-adapt-indentation) 0
22409 (let ((level (org-current-level)))
22410 (if level (1+ level) 0))))
22411 ((item plain-list) (org-list-item-body-column post-affiliated))
22413 (goto-char start)
22414 (org-get-indentation))))
22415 ((memq type '(headline inlinetask nil))
22416 (if (org-match-line "[ \t]*$")
22417 (org--get-expected-indentation element t)
22419 ((memq type '(diary-sexp footnote-definition)) 0)
22420 ;; First paragraph of a footnote definition or an item.
22421 ;; Indent like parent.
22422 ((< (line-beginning-position) start)
22423 (org--get-expected-indentation
22424 (org-element-property :parent element) t))
22425 ;; At first line: indent according to previous sibling, if any,
22426 ;; ignoring footnote definitions and inline tasks, or parent's
22427 ;; contents.
22428 ((= (line-beginning-position) start)
22429 (catch 'exit
22430 (while t
22431 (if (= (point-min) start) (throw 'exit 0)
22432 (goto-char (1- start))
22433 (let* ((previous (org-element-at-point))
22434 (parent previous))
22435 (while (and parent (<= (org-element-property :end parent) start))
22436 (setq previous parent
22437 parent (org-element-property :parent parent)))
22438 (cond
22439 ((not previous) (throw 'exit 0))
22440 ((> (org-element-property :end previous) start)
22441 (throw 'exit (org--get-expected-indentation previous t)))
22442 ((memq (org-element-type previous)
22443 '(footnote-definition inlinetask))
22444 (setq start (org-element-property :begin previous)))
22445 (t (goto-char (org-element-property :begin previous))
22446 (throw 'exit
22447 (if (bolp) (org-get-indentation)
22448 ;; At first paragraph in an item or
22449 ;; a footnote definition.
22450 (org--get-expected-indentation
22451 (org-element-property :parent previous) t))))))))))
22452 ;; Otherwise, move to the first non-blank line above.
22454 (beginning-of-line)
22455 (let ((pos (point)))
22456 (skip-chars-backward " \r\t\n")
22457 (cond
22458 ;; Two blank lines end a footnote definition or a plain
22459 ;; list. When we indent an empty line after them, the
22460 ;; containing list or footnote definition is over, so it
22461 ;; qualifies as a previous sibling. Therefore, we indent
22462 ;; like its first line.
22463 ((and (memq type '(footnote-definition plain-list))
22464 (> (count-lines (point) pos) 2))
22465 (goto-char start)
22466 (org-get-indentation))
22467 ;; Line above is the first one of a paragraph at the
22468 ;; beginning of an item or a footnote definition. Indent
22469 ;; like parent.
22470 ((< (line-beginning-position) start)
22471 (org--get-expected-indentation
22472 (org-element-property :parent element) t))
22473 ;; Line above is the beginning of an element, i.e., point
22474 ;; was originally on the blank lines between element's start
22475 ;; and contents.
22476 ((= (line-beginning-position) post-affiliated)
22477 (org--get-expected-indentation element t))
22478 ;; POS is after contents in a greater element. Indent like
22479 ;; the beginning of the element.
22480 ((and (memq type org-element-greater-elements)
22481 (let ((cend (org-element-property :contents-end element)))
22482 (and cend (<= cend pos))))
22483 ;; As a special case, if point is at the end of a footnote
22484 ;; definition or an item, indent like the very last element
22485 ;; within. If that last element is an item, indent like
22486 ;; its contents.
22487 (if (memq type '(footnote-definition item plain-list))
22488 (let ((last (org-element-at-point)))
22489 (goto-char pos)
22490 (org--get-expected-indentation
22491 last (eq (org-element-type last) 'item)))
22492 (goto-char start)
22493 (org-get-indentation)))
22494 ;; In any other case, indent like the current line.
22495 (t (org-get-indentation)))))))))
22497 (defun org--align-node-property ()
22498 "Align node property at point.
22499 Alignment is done according to `org-property-format', which see."
22500 (when (save-excursion
22501 (beginning-of-line)
22502 (looking-at org-property-re))
22503 (replace-match
22504 (concat (match-string 4)
22505 (org-trim
22506 (format org-property-format (match-string 1) (match-string 3))))
22507 t t)))
22509 (defun org-indent-line ()
22510 "Indent line depending on context.
22512 Indentation is done according to the following rules:
22514 - Footnote definitions, diary sexps, headlines and inline tasks
22515 have to start at column 0.
22517 - On the very first line of an element, consider, in order, the
22518 next rules until one matches:
22520 1. If there's a sibling element before, ignoring footnote
22521 definitions and inline tasks, indent like its first line.
22523 2. If element has a parent, indent like its contents. More
22524 precisely, if parent is an item, indent after the
22525 description part, if any, or the bullet (see
22526 `org-list-description-max-indent'). Else, indent like
22527 parent's first line.
22529 3. Otherwise, indent relatively to current level, if
22530 `org-adapt-indentation' is non-nil, or to left margin.
22532 - On a blank line at the end of an element, indent according to
22533 the type of the element. More precisely
22535 1. If element is a plain list, an item, or a footnote
22536 definition, indent like the very last element within.
22538 2. If element is a paragraph, indent like its last non blank
22539 line.
22541 3. Otherwise, indent like its very first line.
22543 - In the code part of a source block, use language major mode
22544 to indent current line if `org-src-tab-acts-natively' is
22545 non-nil. If it is nil, do nothing.
22547 - Otherwise, indent like the first non-blank line above.
22549 The function doesn't indent an item as it could break the whole
22550 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22551 `\\[org-shiftmetaright]'.
22553 Also align node properties according to `org-property-format'."
22554 (interactive)
22555 (cond
22556 (orgstruct-is-++
22557 (let ((indent-line-function
22558 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22559 (indent-according-to-mode)))
22560 ((org-at-heading-p) 'noindent)
22562 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22563 (type (org-element-type element)))
22564 (cond ((and (memq type '(plain-list item))
22565 (= (line-beginning-position)
22566 (org-element-property :post-affiliated element)))
22567 'noindent)
22568 ((and (eq type 'latex-environment)
22569 (>= (point) (org-element-property :post-affiliated element))
22570 (< (point) (org-with-wide-buffer
22571 (goto-char (org-element-property :end element))
22572 (skip-chars-backward " \r\t\n")
22573 (line-beginning-position 2))))
22574 'noindent)
22575 ((and (eq type 'src-block)
22576 org-src-tab-acts-natively
22577 (> (line-beginning-position)
22578 (org-element-property :post-affiliated element))
22579 (< (line-beginning-position)
22580 (org-with-wide-buffer
22581 (goto-char (org-element-property :end element))
22582 (skip-chars-backward " \r\t\n")
22583 (line-beginning-position))))
22584 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22586 (let ((column (org--get-expected-indentation element nil)))
22587 ;; Preserve current column.
22588 (if (<= (current-column) (current-indentation))
22589 (indent-line-to column)
22590 (save-excursion (indent-line-to column))))
22591 ;; Align node property. Also preserve current column.
22592 (when (eq type 'node-property)
22593 (let ((column (current-column)))
22594 (org--align-node-property)
22595 (org-move-to-column column)))))))))
22597 (defun org-indent-region (start end)
22598 "Indent each non-blank line in the region.
22599 Called from a program, START and END specify the region to
22600 indent. The function will not indent contents of example blocks,
22601 verse blocks and export blocks as leading white spaces are
22602 assumed to be significant there."
22603 (interactive "r")
22604 (save-excursion
22605 (goto-char start)
22606 (skip-chars-forward " \r\t\n")
22607 (unless (eobp) (beginning-of-line))
22608 (let ((indent-to
22609 (lambda (ind pos)
22610 ;; Set IND as indentation for all lines between point and
22611 ;; POS. Blank lines are ignored. Leave point after POS
22612 ;; once done.
22613 (let ((limit (copy-marker pos)))
22614 (while (< (point) limit)
22615 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22616 (forward-line))
22617 (set-marker limit nil))))
22618 (end (copy-marker end)))
22619 (while (< (point) end)
22620 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22621 (let* ((element (org-element-at-point))
22622 (type (org-element-type element))
22623 (element-end (copy-marker (org-element-property :end element)))
22624 (ind (org--get-expected-indentation element nil)))
22625 (cond
22626 ;; Element indented as a single block. Example blocks
22627 ;; preserving indentation are a special case since the
22628 ;; "contents" must not be indented whereas the block
22629 ;; boundaries can.
22630 ((or (memq type '(export-block latex-environment))
22631 (and (eq type 'example-block)
22632 (not
22633 (or org-src-preserve-indentation
22634 (org-element-property :preserve-indent element)))))
22635 (let ((offset (- ind (org-get-indentation))))
22636 (unless (zerop offset)
22637 (indent-rigidly (org-element-property :begin element)
22638 (org-element-property :end element)
22639 offset)))
22640 (goto-char element-end))
22641 ;; Elements indented line wise. Be sure to exclude
22642 ;; example blocks (preserving indentation) and source
22643 ;; blocks from this category as they are treated
22644 ;; specially later.
22645 ((or (memq type '(paragraph table table-row))
22646 (not (or (org-element-property :contents-begin element)
22647 (memq type '(example-block src-block)))))
22648 (when (eq type 'node-property)
22649 (org--align-node-property)
22650 (beginning-of-line))
22651 (funcall indent-to ind (min element-end end)))
22652 ;; Elements consisting of three parts: before the
22653 ;; contents, the contents, and after the contents. The
22654 ;; contents are treated specially, according to the
22655 ;; element type, or not indented at all. Other parts are
22656 ;; indented as a single block.
22658 (let* ((post (copy-marker
22659 (org-element-property :post-affiliated element)))
22660 (cbeg
22661 (copy-marker
22662 (cond
22663 ((not (org-element-property :contents-begin element))
22664 ;; Fake contents for source blocks.
22665 (org-with-wide-buffer
22666 (goto-char post)
22667 (line-beginning-position 2)))
22668 ((memq type '(footnote-definition item plain-list))
22669 ;; Contents in these elements could start on
22670 ;; the same line as the beginning of the
22671 ;; element. Make sure we start indenting
22672 ;; from the second line.
22673 (org-with-wide-buffer
22674 (goto-char post)
22675 (end-of-line)
22676 (skip-chars-forward " \r\t\n")
22677 (if (eobp) (point) (line-beginning-position))))
22678 (t (org-element-property :contents-begin element)))))
22679 (cend (copy-marker
22680 (or (org-element-property :contents-end element)
22681 ;; Fake contents for source blocks.
22682 (org-with-wide-buffer
22683 (goto-char element-end)
22684 (skip-chars-backward " \r\t\n")
22685 (line-beginning-position)))
22686 t)))
22687 ;; Do not change items indentation individually as it
22688 ;; might break the list as a whole. On the other
22689 ;; hand, when at a plain list, indent it as a whole.
22690 (cond ((eq type 'plain-list)
22691 (let ((offset (- ind (org-get-indentation))))
22692 (unless (zerop offset)
22693 (indent-rigidly (org-element-property :begin element)
22694 (org-element-property :end element)
22695 offset))
22696 (goto-char cbeg)))
22697 ((eq type 'item) (goto-char cbeg))
22698 (t (funcall indent-to ind (min cbeg end))))
22699 (when (< (point) end)
22700 (cl-case type
22701 ((example-block verse-block))
22702 (src-block
22703 ;; In a source block, indent source code
22704 ;; according to language major mode, but only if
22705 ;; `org-src-tab-acts-natively' is non-nil.
22706 (when (and (< (point) end) org-src-tab-acts-natively)
22707 (ignore-errors
22708 (org-babel-do-in-edit-buffer
22709 (indent-region (point-min) (point-max))))))
22710 (t (org-indent-region (point) (min cend end))))
22711 (goto-char (min cend end))
22712 (when (< (point) end)
22713 (funcall indent-to ind (min element-end end))))
22714 (set-marker post nil)
22715 (set-marker cbeg nil)
22716 (set-marker cend nil))))
22717 (set-marker element-end nil))))
22718 (set-marker end nil))))
22720 (defun org-indent-drawer ()
22721 "Indent the drawer at point."
22722 (interactive)
22723 (unless (save-excursion
22724 (beginning-of-line)
22725 (looking-at-p org-drawer-regexp))
22726 (user-error "Not at a drawer"))
22727 (let ((element (org-element-at-point)))
22728 (unless (memq (org-element-type element) '(drawer property-drawer))
22729 (user-error "Not at a drawer"))
22730 (org-with-wide-buffer
22731 (org-indent-region (org-element-property :begin element)
22732 (org-element-property :end element))))
22733 (message "Drawer at point indented"))
22735 (defun org-indent-block ()
22736 "Indent the block at point."
22737 (interactive)
22738 (unless (save-excursion
22739 (beginning-of-line)
22740 (let ((case-fold-search t))
22741 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22742 (user-error "Not at a block"))
22743 (let ((element (org-element-at-point)))
22744 (unless (memq (org-element-type element)
22745 '(comment-block center-block dynamic-block example-block
22746 export-block quote-block special-block
22747 src-block verse-block))
22748 (user-error "Not at a block"))
22749 (org-with-wide-buffer
22750 (org-indent-region (org-element-property :begin element)
22751 (org-element-property :end element))))
22752 (message "Block at point indented"))
22755 ;;; Filling
22757 ;; We use our own fill-paragraph and auto-fill functions.
22759 ;; `org-fill-paragraph' relies on adaptive filling and context
22760 ;; checking. Appropriate `fill-prefix' is computed with
22761 ;; `org-adaptive-fill-function'.
22763 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22764 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22765 ;; `org-adaptive-fill-function' value. Internally,
22766 ;; `org-comment-line-break-function' breaks the line.
22768 ;; `org-setup-filling' installs filling and auto-filling related
22769 ;; variables during `org-mode' initialization.
22771 (defvar org-element-paragraph-separate) ; org-element.el
22772 (defun org-setup-filling ()
22773 (require 'org-element)
22774 ;; Prevent auto-fill from inserting unwanted new items.
22775 (when (boundp 'fill-nobreak-predicate)
22776 (setq-local
22777 fill-nobreak-predicate
22778 (org-uniquify
22779 (append fill-nobreak-predicate
22780 '(org-fill-line-break-nobreak-p
22781 org-fill-n-macro-as-item-nobreak-p
22782 org-fill-paragraph-with-timestamp-nobreak-p)))))
22783 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22784 (setq-local paragraph-start paragraph-ending)
22785 (setq-local paragraph-separate paragraph-ending))
22786 (setq-local fill-paragraph-function 'org-fill-paragraph)
22787 (setq-local auto-fill-inhibit-regexp nil)
22788 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22789 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22790 (setq-local comment-line-break-function 'org-comment-line-break-function))
22792 (defun org-fill-line-break-nobreak-p ()
22793 "Non-nil when a new line at point would create an Org line break."
22794 (save-excursion
22795 (skip-chars-backward "[ \t]")
22796 (skip-chars-backward "\\\\")
22797 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22799 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22800 "Non-nil when a new line at point would split a timestamp."
22801 (and (org-at-timestamp-p 'lax)
22802 (not (looking-at org-ts-regexp-both))))
22804 (defun org-fill-n-macro-as-item-nobreak-p ()
22805 "Non-nil when a new line at point would create a new list."
22806 ;; During export, a "n" macro followed by a dot or a closing
22807 ;; parenthesis can end up being parsed as a new list item.
22808 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22810 (declare-function message-in-body-p "message" ())
22811 (defvar orgtbl-line-start-regexp) ; From org-table.el
22812 (defun org-adaptive-fill-function ()
22813 "Compute a fill prefix for the current line.
22814 Return fill prefix, as a string, or nil if current line isn't
22815 meant to be filled. For convenience, if `adaptive-fill-regexp'
22816 matches in paragraphs or comments, use it."
22817 (catch 'exit
22818 (when (derived-mode-p 'message-mode)
22819 (save-excursion
22820 (beginning-of-line)
22821 (cond ((not (message-in-body-p)) (throw 'exit nil))
22822 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22823 ((looking-at message-cite-prefix-regexp)
22824 (throw 'exit (match-string-no-properties 0)))
22825 ((looking-at org-outline-regexp)
22826 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22827 (org-with-wide-buffer
22828 (unless (org-at-heading-p)
22829 (let* ((p (line-beginning-position))
22830 (element (save-excursion
22831 (beginning-of-line)
22832 (org-element-at-point)))
22833 (type (org-element-type element))
22834 (post-affiliated (org-element-property :post-affiliated element)))
22835 (unless (< p post-affiliated)
22836 (cl-case type
22837 (comment
22838 (save-excursion
22839 (beginning-of-line)
22840 (looking-at "[ \t]*")
22841 (concat (match-string 0) "# ")))
22842 (footnote-definition "")
22843 ((item plain-list)
22844 (make-string (org-list-item-body-column post-affiliated) ?\s))
22845 (paragraph
22846 ;; Fill prefix is usually the same as the current line,
22847 ;; unless the paragraph is at the beginning of an item.
22848 (let ((parent (org-element-property :parent element)))
22849 (save-excursion
22850 (beginning-of-line)
22851 (cond ((eq (org-element-type parent) 'item)
22852 (make-string (org-list-item-body-column
22853 (org-element-property :begin parent))
22854 ?\s))
22855 ((and adaptive-fill-regexp
22856 ;; Locally disable
22857 ;; `adaptive-fill-function' to let
22858 ;; `fill-context-prefix' handle
22859 ;; `adaptive-fill-regexp' variable.
22860 (let (adaptive-fill-function)
22861 (fill-context-prefix
22862 post-affiliated
22863 (org-element-property :end element)))))
22864 ((looking-at "[ \t]+") (match-string 0))
22865 (t "")))))
22866 (comment-block
22867 ;; Only fill contents if P is within block boundaries.
22868 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22869 (forward-line)
22870 (point)))
22871 (cend (save-excursion
22872 (goto-char (org-element-property :end element))
22873 (skip-chars-backward " \r\t\n")
22874 (line-beginning-position))))
22875 (when (and (>= p cbeg) (< p cend))
22876 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22877 (match-string 0)
22878 "")))))))))))
22880 (declare-function message-goto-body "message" ())
22881 (defvar message-cite-prefix-regexp) ; From message.el
22883 (defun org-fill-element (&optional justify)
22884 "Fill element at point, when applicable.
22886 This function only applies to comment blocks, comments, example
22887 blocks and paragraphs. Also, as a special case, re-align table
22888 when point is at one.
22890 If JUSTIFY is non-nil (interactively, with prefix argument),
22891 justify as well. If `sentence-end-double-space' is non-nil, then
22892 period followed by one space does not end a sentence, so don't
22893 break a line there. The variable `fill-column' controls the
22894 width for filling.
22896 For convenience, when point is at a plain list, an item or
22897 a footnote definition, try to fill the first paragraph within."
22898 (with-syntax-table org-mode-transpose-word-syntax-table
22899 ;; Move to end of line in order to get the first paragraph within
22900 ;; a plain list or a footnote definition.
22901 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22902 ;; First check if point is in a blank line at the beginning of
22903 ;; the buffer. In that case, ignore filling.
22904 (cl-case (org-element-type element)
22905 ;; Use major mode filling function is src blocks.
22906 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22907 ;; Align Org tables, leave table.el tables as-is.
22908 (table-row (org-table-align) t)
22909 (table
22910 (when (eq (org-element-property :type element) 'org)
22911 (save-excursion
22912 (goto-char (org-element-property :post-affiliated element))
22913 (org-table-align)))
22915 (paragraph
22916 ;; Paragraphs may contain `line-break' type objects.
22917 (let ((beg (max (point-min)
22918 (org-element-property :contents-begin element)))
22919 (end (min (point-max)
22920 (org-element-property :contents-end element))))
22921 ;; Do nothing if point is at an affiliated keyword.
22922 (if (< (line-end-position) beg) t
22923 (when (derived-mode-p 'message-mode)
22924 ;; In `message-mode', do not fill following citation
22925 ;; in current paragraph nor text before message body.
22926 (let ((body-start (save-excursion (message-goto-body))))
22927 (when body-start (setq beg (max body-start beg))))
22928 (when (save-excursion
22929 (re-search-forward
22930 (concat "^" message-cite-prefix-regexp) end t))
22931 (setq end (match-beginning 0))))
22932 ;; Fill paragraph, taking line breaks into account.
22933 (save-excursion
22934 (goto-char beg)
22935 (let ((cuts (list beg)))
22936 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22937 (when (eq 'line-break
22938 (org-element-type
22939 (save-excursion (backward-char)
22940 (org-element-context))))
22941 (push (point) cuts)))
22942 (dolist (c (delq end cuts))
22943 (fill-region-as-paragraph c end justify)
22944 (setq end c))))
22945 t)))
22946 ;; Contents of `comment-block' type elements should be
22947 ;; filled as plain text, but only if point is within block
22948 ;; markers.
22949 (comment-block
22950 (let* ((case-fold-search t)
22951 (beg (save-excursion
22952 (goto-char (org-element-property :begin element))
22953 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22954 (forward-line)
22955 (point)))
22956 (end (save-excursion
22957 (goto-char (org-element-property :end element))
22958 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22959 (line-beginning-position))))
22960 (if (or (< (point) beg) (> (point) end)) t
22961 (fill-region-as-paragraph
22962 (save-excursion (end-of-line)
22963 (re-search-backward "^[ \t]*$" beg 'move)
22964 (line-beginning-position))
22965 (save-excursion (beginning-of-line)
22966 (re-search-forward "^[ \t]*$" end 'move)
22967 (line-beginning-position))
22968 justify))))
22969 ;; Fill comments.
22970 (comment
22971 (let ((begin (org-element-property :post-affiliated element))
22972 (end (org-element-property :end element)))
22973 (when (and (>= (point) begin) (<= (point) end))
22974 (let ((begin (save-excursion
22975 (end-of-line)
22976 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22977 (progn (forward-line) (point))
22978 begin)))
22979 (end (save-excursion
22980 (end-of-line)
22981 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22982 (1- (line-beginning-position))
22983 (skip-chars-backward " \r\t\n")
22984 (line-end-position)))))
22985 ;; Do not fill comments when at a blank line.
22986 (when (> end begin)
22987 (let ((fill-prefix
22988 (save-excursion
22989 (beginning-of-line)
22990 (looking-at "[ \t]*#")
22991 (let ((comment-prefix (match-string 0)))
22992 (goto-char (match-end 0))
22993 (if (looking-at adaptive-fill-regexp)
22994 (concat comment-prefix (match-string 0))
22995 (concat comment-prefix " "))))))
22996 (save-excursion
22997 (fill-region-as-paragraph begin end justify))))))
22999 ;; Ignore every other element.
23000 (otherwise t)))))
23002 (defun org-fill-paragraph (&optional justify region)
23003 "Fill element at point, when applicable.
23005 This function only applies to comment blocks, comments, example
23006 blocks and paragraphs. Also, as a special case, re-align table
23007 when point is at one.
23009 For convenience, when point is at a plain list, an item or
23010 a footnote definition, try to fill the first paragraph within.
23012 If JUSTIFY is non-nil (interactively, with prefix argument),
23013 justify as well. If `sentence-end-double-space' is non-nil, then
23014 period followed by one space does not end a sentence, so don't
23015 break a line there. The variable `fill-column' controls the
23016 width for filling.
23018 The REGION argument is non-nil if called interactively; in that
23019 case, if Transient Mark mode is enabled and the mark is active,
23020 fill each of the elements in the active region, instead of just
23021 filling the current element."
23022 (interactive (progn
23023 (barf-if-buffer-read-only)
23024 (list (if current-prefix-arg 'full) t)))
23025 (cond
23026 ((and (derived-mode-p 'message-mode)
23027 (or (not (message-in-body-p))
23028 (save-excursion (move-beginning-of-line 1)
23029 (looking-at message-cite-prefix-regexp))))
23030 ;; First ensure filling is correct in message-mode.
23031 (let ((fill-paragraph-function
23032 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23033 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23034 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23035 (paragraph-separate
23036 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23037 (fill-paragraph nil)))
23038 ((and region transient-mark-mode mark-active
23039 (not (eq (region-beginning) (region-end))))
23040 (let ((origin (point-marker))
23041 (start (region-beginning)))
23042 (unwind-protect
23043 (progn
23044 (goto-char (region-end))
23045 (while (> (point) start)
23046 (org-backward-paragraph)
23047 (org-fill-element justify)))
23048 (goto-char origin)
23049 (set-marker origin nil))))
23050 (t (org-fill-element justify))))
23051 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23053 (defun org-auto-fill-function ()
23054 "Auto-fill function."
23055 ;; Check if auto-filling is meaningful.
23056 (let ((fc (current-fill-column)))
23057 (when (and fc (> (current-column) fc))
23058 (let* ((fill-prefix (org-adaptive-fill-function))
23059 ;; Enforce empty fill prefix, if required. Otherwise, it
23060 ;; will be computed again.
23061 (adaptive-fill-mode (not (equal fill-prefix ""))))
23062 (when fill-prefix (do-auto-fill))))))
23064 (defun org-comment-line-break-function (&optional soft)
23065 "Break line at point and indent, continuing comment if within one.
23066 The inserted newline is marked hard if variable
23067 `use-hard-newlines' is true, unless optional argument SOFT is
23068 non-nil."
23069 (if soft (insert-and-inherit ?\n) (newline 1))
23070 (save-excursion (forward-char -1) (delete-horizontal-space))
23071 (delete-horizontal-space)
23072 (indent-to-left-margin)
23073 (insert-before-markers-and-inherit fill-prefix))
23076 ;;; Fixed Width Areas
23078 (defun org-toggle-fixed-width ()
23079 "Toggle fixed-width markup.
23081 Add or remove fixed-width markup on current line, whenever it
23082 makes sense. Return an error otherwise.
23084 If a region is active and if it contains only fixed-width areas
23085 or blank lines, remove all fixed-width markup in it. If the
23086 region contains anything else, convert all non-fixed-width lines
23087 to fixed-width ones.
23089 Blank lines at the end of the region are ignored unless the
23090 region only contains such lines."
23091 (interactive)
23092 (if (not (org-region-active-p))
23093 ;; No region:
23095 ;; Remove fixed width marker only in a fixed-with element.
23097 ;; Add fixed width maker in paragraphs, in blank lines after
23098 ;; elements or at the beginning of a headline or an inlinetask,
23099 ;; and before any one-line elements (e.g., a clock).
23100 (progn
23101 (beginning-of-line)
23102 (let* ((element (org-element-at-point))
23103 (type (org-element-type element)))
23104 (cond
23105 ((and (eq type 'fixed-width)
23106 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23107 (replace-match
23108 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23109 ((and (memq type '(babel-call clock comment diary-sexp headline
23110 horizontal-rule keyword paragraph
23111 planning))
23112 (<= (org-element-property :post-affiliated element) (point)))
23113 (skip-chars-forward " \t")
23114 (insert ": "))
23115 ((and (looking-at-p "[ \t]*$")
23116 (or (eq type 'inlinetask)
23117 (save-excursion
23118 (skip-chars-forward " \r\t\n")
23119 (<= (org-element-property :end element) (point)))))
23120 (delete-region (point) (line-end-position))
23121 (org-indent-line)
23122 (insert ": "))
23123 (t (user-error "Cannot insert a fixed-width line here")))))
23124 ;; Region active.
23125 (let* ((begin (save-excursion
23126 (goto-char (region-beginning))
23127 (line-beginning-position)))
23128 (end (copy-marker
23129 (save-excursion
23130 (goto-char (region-end))
23131 (unless (eolp) (beginning-of-line))
23132 (if (save-excursion (re-search-backward "\\S-" begin t))
23133 (progn (skip-chars-backward " \r\t\n") (point))
23134 (point)))))
23135 (all-fixed-width-p
23136 (catch 'not-all-p
23137 (save-excursion
23138 (goto-char begin)
23139 (skip-chars-forward " \r\t\n")
23140 (when (eobp) (throw 'not-all-p nil))
23141 (while (< (point) end)
23142 (let ((element (org-element-at-point)))
23143 (if (eq (org-element-type element) 'fixed-width)
23144 (goto-char (org-element-property :end element))
23145 (throw 'not-all-p nil))))
23146 t))))
23147 (if all-fixed-width-p
23148 (save-excursion
23149 (goto-char begin)
23150 (while (< (point) end)
23151 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23152 (replace-match
23153 "" nil nil nil
23154 (if (= (line-end-position) (match-end 0)) 0 1)))
23155 (forward-line)))
23156 (let ((min-ind (point-max)))
23157 ;; Find minimum indentation across all lines.
23158 (save-excursion
23159 (goto-char begin)
23160 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23161 (setq min-ind 0)
23162 (catch 'zerop
23163 (while (< (point) end)
23164 (unless (looking-at-p "[ \t]*$")
23165 (let ((ind (org-get-indentation)))
23166 (setq min-ind (min min-ind ind))
23167 (when (zerop ind) (throw 'zerop t))))
23168 (forward-line)))))
23169 ;; Loop over all lines and add fixed-width markup everywhere
23170 ;; but in fixed-width lines.
23171 (save-excursion
23172 (goto-char begin)
23173 (while (< (point) end)
23174 (cond
23175 ((org-at-heading-p)
23176 (insert ": ")
23177 (forward-line)
23178 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23179 (insert ":")
23180 (forward-line)))
23181 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23182 (let* ((element (org-element-at-point))
23183 (element-end (org-element-property :end element)))
23184 (if (eq (org-element-type element) 'fixed-width)
23185 (progn (goto-char element-end)
23186 (skip-chars-backward " \r\t\n")
23187 (forward-line))
23188 (let ((limit (min end element-end)))
23189 (while (< (point) limit)
23190 (org-move-to-column min-ind t)
23191 (insert ": ")
23192 (forward-line))))))
23194 (org-move-to-column min-ind t)
23195 (insert ": ")
23196 (forward-line)))))))
23197 (set-marker end nil))))
23200 ;;; Comments
23202 ;; Org comments syntax is quite complex. It requires the entire line
23203 ;; to be just a comment. Also, even with the right syntax at the
23204 ;; beginning of line, some elements (e.g., verse-block or
23205 ;; example-block) don't accept comments. Usual Emacs comment commands
23206 ;; cannot cope with those requirements. Therefore, Org replaces them.
23208 ;; Org still relies on `comment-dwim', but cannot trust
23209 ;; `comment-only-p'. So, `comment-region-function' and
23210 ;; `uncomment-region-function' both point
23211 ;; to`org-comment-or-uncomment-region'. Eventually,
23212 ;; `org-insert-comment' takes care of insertion of comments at the
23213 ;; beginning of line.
23215 ;; `org-setup-comments-handling' install comments related variables
23216 ;; during `org-mode' initialization.
23218 (defun org-setup-comments-handling ()
23219 (interactive)
23220 (setq-local comment-use-syntax nil)
23221 (setq-local comment-start "# ")
23222 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23223 (setq-local comment-insert-comment-function 'org-insert-comment)
23224 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23225 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23227 (defun org-insert-comment ()
23228 "Insert an empty comment above current line.
23229 If the line is empty, insert comment at its beginning. When
23230 point is within a source block, comment according to the related
23231 major mode."
23232 (if (let ((element (org-element-at-point)))
23233 (and (eq (org-element-type element) 'src-block)
23234 (< (save-excursion
23235 (goto-char (org-element-property :post-affiliated element))
23236 (line-end-position))
23237 (point))
23238 (> (save-excursion
23239 (goto-char (org-element-property :end element))
23240 (skip-chars-backward " \r\t\n")
23241 (line-beginning-position))
23242 (point))))
23243 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23244 (beginning-of-line)
23245 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23246 (open-line 1))
23247 (org-indent-line)
23248 (insert "# ")))
23250 (defvar comment-empty-lines) ; From newcomment.el.
23251 (defun org-comment-or-uncomment-region (beg end &rest _)
23252 "Comment or uncomment each non-blank line in the region.
23253 Uncomment each non-blank line between BEG and END if it only
23254 contains commented lines. Otherwise, comment them. If region is
23255 strictly within a source block, use appropriate comment syntax."
23256 (if (let ((element (org-element-at-point)))
23257 (and (eq (org-element-type element) 'src-block)
23258 (< (save-excursion
23259 (goto-char (org-element-property :post-affiliated element))
23260 (line-end-position))
23261 beg)
23262 (>= (save-excursion
23263 (goto-char (org-element-property :end element))
23264 (skip-chars-backward " \r\t\n")
23265 (line-beginning-position))
23266 end)))
23267 ;; Translate region boundaries for the Org buffer to the source
23268 ;; buffer.
23269 (let ((offset (- end beg)))
23270 (save-excursion
23271 (goto-char beg)
23272 (org-babel-do-in-edit-buffer
23273 (comment-or-uncomment-region (point) (+ offset (point))))))
23274 (save-restriction
23275 ;; Restrict region
23276 (narrow-to-region (save-excursion (goto-char beg)
23277 (skip-chars-forward " \r\t\n" end)
23278 (line-beginning-position))
23279 (save-excursion (goto-char end)
23280 (skip-chars-backward " \r\t\n" beg)
23281 (line-end-position)))
23282 (let ((uncommentp
23283 ;; UNCOMMENTP is non-nil when every non blank line between
23284 ;; BEG and END is a comment.
23285 (save-excursion
23286 (goto-char (point-min))
23287 (while (and (not (eobp))
23288 (let ((element (org-element-at-point)))
23289 (and (eq (org-element-type element) 'comment)
23290 (goto-char (min (point-max)
23291 (org-element-property
23292 :end element)))))))
23293 (eobp))))
23294 (if uncommentp
23295 ;; Only blank lines and comments in region: uncomment it.
23296 (save-excursion
23297 (goto-char (point-min))
23298 (while (not (eobp))
23299 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23300 (replace-match "" nil nil nil 1))
23301 (forward-line)))
23302 ;; Comment each line in region.
23303 (let ((min-indent (point-max)))
23304 ;; First find the minimum indentation across all lines.
23305 (save-excursion
23306 (goto-char (point-min))
23307 (while (and (not (eobp)) (not (zerop min-indent)))
23308 (unless (looking-at "[ \t]*$")
23309 (setq min-indent (min min-indent (current-indentation))))
23310 (forward-line)))
23311 ;; Then loop over all lines.
23312 (save-excursion
23313 (goto-char (point-min))
23314 (while (not (eobp))
23315 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23316 ;; Don't get fooled by invisible text (e.g. link path)
23317 ;; when moving to column MIN-INDENT.
23318 (let ((buffer-invisibility-spec nil))
23319 (org-move-to-column min-indent t))
23320 (insert comment-start))
23321 (forward-line)))))))))
23323 (defun org-comment-dwim (_arg)
23324 "Call `comment-dwim' within a source edit buffer if needed."
23325 (interactive "*P")
23326 (if (org-in-src-block-p)
23327 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23328 (call-interactively 'comment-dwim)))
23331 ;;; Timestamps API
23333 ;; This section contains tools to operate on timestamp objects, as
23334 ;; returned by, e.g. `org-element-context'.
23336 (defun org-timestamp--to-internal-time (timestamp &optional end)
23337 "Encode TIMESTAMP object into Emacs internal time.
23338 Use end of date range or time range when END is non-nil."
23339 (apply #'encode-time
23340 (cons 0
23341 (mapcar
23342 (lambda (prop) (or (org-element-property prop timestamp) 0))
23343 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23344 '(:minute-start :hour-start :day-start :month-start
23345 :year-start))))))
23347 (defun org-timestamp-has-time-p (timestamp)
23348 "Non-nil when TIMESTAMP has a time specified."
23349 (org-element-property :hour-start timestamp))
23351 (defun org-timestamp-format (timestamp format &optional end utc)
23352 "Format a TIMESTAMP object into a string.
23354 FORMAT is a format specifier to be passed to
23355 `format-time-string'.
23357 When optional argument END is non-nil, use end of date-range or
23358 time-range, if possible.
23360 When optional argument UTC is non-nil, time will be expressed as
23361 Universal Time."
23362 (format-time-string
23363 format (org-timestamp--to-internal-time timestamp end)
23364 (and utc t)))
23366 (defun org-timestamp-split-range (timestamp &optional end)
23367 "Extract a TIMESTAMP object from a date or time range.
23369 END, when non-nil, means extract the end of the range.
23370 Otherwise, extract its start.
23372 Return a new timestamp object."
23373 (let ((type (org-element-property :type timestamp)))
23374 (if (memq type '(active inactive diary)) timestamp
23375 (let ((split-ts (org-element-copy timestamp)))
23376 ;; Set new type.
23377 (org-element-put-property
23378 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23379 ;; Copy start properties over end properties if END is
23380 ;; non-nil. Otherwise, copy end properties over `start' ones.
23381 (let ((p-alist '((:minute-start . :minute-end)
23382 (:hour-start . :hour-end)
23383 (:day-start . :day-end)
23384 (:month-start . :month-end)
23385 (:year-start . :year-end))))
23386 (dolist (p-cell p-alist)
23387 (org-element-put-property
23388 split-ts
23389 (funcall (if end #'car #'cdr) p-cell)
23390 (org-element-property
23391 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23392 ;; Eventually refresh `:raw-value'.
23393 (org-element-put-property split-ts :raw-value nil)
23394 (org-element-put-property
23395 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23397 (defun org-timestamp-translate (timestamp &optional boundary)
23398 "Translate TIMESTAMP object to custom format.
23400 Format string is defined in `org-time-stamp-custom-formats',
23401 which see.
23403 When optional argument BOUNDARY is non-nil, it is either the
23404 symbol `start' or `end'. In this case, only translate the
23405 starting or ending part of TIMESTAMP if it is a date or time
23406 range. Otherwise, translate both parts.
23408 Return timestamp as-is if `org-display-custom-times' is nil or if
23409 it has a `diary' type."
23410 (let ((type (org-element-property :type timestamp)))
23411 (if (or (not org-display-custom-times) (eq type 'diary))
23412 (org-element-interpret-data timestamp)
23413 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23414 org-time-stamp-custom-formats)))
23415 (if (and (not boundary) (memq type '(active-range inactive-range)))
23416 (concat (org-timestamp-format timestamp fmt)
23417 "--"
23418 (org-timestamp-format timestamp fmt t))
23419 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23423 ;;; Other stuff.
23425 (defvar reftex-docstruct-symbol)
23426 (defvar org--rds)
23428 (defun org-reftex-citation ()
23429 "Use reftex-citation to insert a citation into the buffer.
23430 This looks for a line like
23432 #+BIBLIOGRAPHY: foo plain option:-d
23434 and derives from it that foo.bib is the bibliography file relevant
23435 for this document. It then installs the necessary environment for RefTeX
23436 to work in this buffer and calls `reftex-citation' to insert a citation
23437 into the buffer.
23439 Export of such citations to both LaTeX and HTML is handled by the contributed
23440 package ox-bibtex by Taru Karttunen."
23441 (interactive)
23442 (let ((reftex-docstruct-symbol 'org--rds)
23443 org--rds bib)
23444 (org-with-wide-buffer
23445 (let ((case-fold-search t)
23446 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23447 (if (not (save-excursion
23448 (or (re-search-forward re nil t)
23449 (re-search-backward re nil t))))
23450 (user-error "No bibliography defined in file")
23451 (setq bib (concat (match-string 1) ".bib")
23452 org--rds (list (list 'bib bib))))))
23453 (call-interactively 'reftex-citation)))
23455 ;;;; Functions extending outline functionality
23457 (defun org-beginning-of-line (&optional n)
23458 "Go to the beginning of the current visible line.
23460 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23461 tags on the first attempt, and only move to after the tags when
23462 the cursor is already beyond the end of the headline.
23464 With argument N not nil or 1, move forward N - 1 lines first."
23465 (interactive "^p")
23466 (let ((origin (point))
23467 (special (pcase org-special-ctrl-a/e
23468 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23469 deactivate-mark)
23470 ;; First move to a visible line.
23471 (if (bound-and-true-p visual-line-mode)
23472 (beginning-of-visual-line n)
23473 (move-beginning-of-line n)
23474 ;; `move-beginning-of-line' may leave point after invisible
23475 ;; characters if line starts with such of these (e.g., with
23476 ;; a link at column 0). Really move to the beginning of the
23477 ;; current visible line.
23478 (beginning-of-line))
23479 (cond
23480 ;; No special behavior. Point is already at the beginning of
23481 ;; a line, logical or visual.
23482 ((not special))
23483 ;; `beginning-of-visual-line' left point before logical beginning
23484 ;; of line: point is at the beginning of a visual line. Bail
23485 ;; out.
23486 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23487 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23488 ;; At a headline, special position is before the title, but
23489 ;; after any TODO keyword or priority cookie.
23490 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23491 (line-end-position)))
23492 (bol (point)))
23493 (if (eq special 'reversed)
23494 (when (and (= origin bol) (eq last-command this-command))
23495 (goto-char refpos))
23496 (when (or (> origin refpos) (= origin bol))
23497 (goto-char refpos)))))
23498 ((and (looking-at org-list-full-item-re)
23499 (memq (org-element-type (save-match-data (org-element-at-point)))
23500 '(item plain-list)))
23501 ;; Set special position at first white space character after
23502 ;; bullet, and check-box, if any.
23503 (let ((after-bullet
23504 (let ((box (match-end 3)))
23505 (cond ((not box) (match-end 1))
23506 ((eq (char-after box) ?\s) (1+ box))
23507 (t box)))))
23508 (if (eq special 'reversed)
23509 (when (and (= (point) origin) (eq last-command this-command))
23510 (goto-char after-bullet))
23511 (when (or (> origin after-bullet) (= (point) origin))
23512 (goto-char after-bullet)))))
23513 ;; No special context. Point is already at beginning of line.
23514 (t nil))))
23516 (defun org-end-of-line (&optional n)
23517 "Go to the end of the line, but before ellipsis, if any.
23519 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23520 tags on the first attempt, and only move to after the tags when
23521 the cursor is already beyond the end of the headline.
23523 With argument N not nil or 1, move forward N - 1 lines first."
23524 (interactive "^p")
23525 (let ((origin (point))
23526 (special (pcase org-special-ctrl-a/e
23527 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23528 deactivate-mark)
23529 ;; First move to a visible line.
23530 (if (bound-and-true-p visual-line-mode)
23531 (beginning-of-visual-line n)
23532 (move-beginning-of-line n))
23533 (cond
23534 ;; At a headline, with tags.
23535 ((and special
23536 (save-excursion
23537 (beginning-of-line)
23538 (let ((case-fold-search nil))
23539 (looking-at org-complex-heading-regexp)))
23540 (match-end 5))
23541 (let ((tags (save-excursion
23542 (goto-char (match-beginning 5))
23543 (skip-chars-backward " \t")
23544 (point)))
23545 (visual-end (and (bound-and-true-p visual-line-mode)
23546 (save-excursion
23547 (end-of-visual-line)
23548 (point)))))
23549 ;; If `end-of-visual-line' brings us before end of line or
23550 ;; even tags, i.e., the headline spans over multiple visual
23551 ;; lines, move there.
23552 (cond ((and visual-end
23553 (< visual-end tags)
23554 (<= origin visual-end))
23555 (goto-char visual-end))
23556 ((eq special 'reversed)
23557 (if (and (= origin (line-end-position))
23558 (eq this-command last-command))
23559 (goto-char tags)
23560 (end-of-line)))
23562 (if (or (< origin tags) (= origin (line-end-position)))
23563 (goto-char tags)
23564 (end-of-line))))))
23565 ((bound-and-true-p visual-line-mode)
23566 (let ((bol (line-beginning-position)))
23567 (end-of-visual-line)
23568 ;; If `end-of-visual-line' gets us past the ellipsis at the
23569 ;; end of a line, backtrack and use `end-of-line' instead.
23570 (when (/= bol (line-beginning-position))
23571 (goto-char bol)
23572 (end-of-line))))
23573 (t (end-of-line)))))
23575 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23576 (define-key org-mode-map "\C-e" 'org-end-of-line)
23578 (defun org-backward-sentence (&optional _arg)
23579 "Go to beginning of sentence, or beginning of table field.
23580 This will call `backward-sentence' or `org-table-beginning-of-field',
23581 depending on context."
23582 (interactive)
23583 (let* ((element (org-element-at-point))
23584 (contents-begin (org-element-property :contents-begin element))
23585 (table (org-element-lineage element '(table) t)))
23586 (if (and table
23587 (> (point) contents-begin)
23588 (<= (point) (org-element-property :contents-end table)))
23589 (call-interactively #'org-table-beginning-of-field)
23590 (save-restriction
23591 (when (and contents-begin
23592 (< (point-min) contents-begin)
23593 (> (point) contents-begin))
23594 (narrow-to-region contents-begin
23595 (org-element-property :contents-end element)))
23596 (call-interactively #'backward-sentence)))))
23598 (defun org-forward-sentence (&optional _arg)
23599 "Go to end of sentence, or end of table field.
23600 This will call `forward-sentence' or `org-table-end-of-field',
23601 depending on context."
23602 (interactive)
23603 (let* ((element (org-element-at-point))
23604 (contents-end (org-element-property :contents-end element))
23605 (table (org-element-lineage element '(table) t)))
23606 (if (and table
23607 (>= (point) (org-element-property :contents-begin table))
23608 (< (point) contents-end))
23609 (call-interactively #'org-table-end-of-field)
23610 (save-restriction
23611 (when (and contents-end
23612 (> (point-max) contents-end)
23613 ;; Skip blank lines between elements.
23614 (< (org-element-property :end element)
23615 (save-excursion (goto-char contents-end)
23616 (skip-chars-forward " \r\t\n"))))
23617 (narrow-to-region (org-element-property :contents-begin element)
23618 contents-end))
23619 (call-interactively #'forward-sentence)))))
23621 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23622 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23624 (defun org-kill-line (&optional _arg)
23625 "Kill line, to tags or end of line."
23626 (interactive)
23627 (cond
23628 ((or (not org-special-ctrl-k)
23629 (bolp)
23630 (not (org-at-heading-p)))
23631 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23632 org-ctrl-k-protect-subtree
23633 (or (eq org-ctrl-k-protect-subtree 'error)
23634 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23635 (user-error "C-k aborted as it would kill a hidden subtree"))
23636 (call-interactively
23637 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23638 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23639 (kill-region (point) (match-beginning 1))
23640 (org-set-tags nil t))
23641 (t (kill-region (point) (point-at-eol)))))
23643 (define-key org-mode-map "\C-k" 'org-kill-line)
23645 (defun org-yank (&optional arg)
23646 "Yank. If the kill is a subtree, treat it specially.
23647 This command will look at the current kill and check if is a single
23648 subtree, or a series of subtrees[1]. If it passes the test, and if the
23649 cursor is at the beginning of a line or after the stars of a currently
23650 empty headline, then the yank is handled specially. How exactly depends
23651 on the value of the following variables.
23653 `org-yank-folded-subtrees'
23654 By default, this variable is non-nil, which results in
23655 subtree(s) being folded after insertion, except if doing so
23656 would swallow text after the yanked text.
23658 `org-yank-adjusted-subtrees'
23659 When non-nil (the default value is nil), the subtree will be
23660 promoted or demoted in order to fit into the local outline tree
23661 structure, which means that the level will be adjusted so that it
23662 becomes the smaller one of the two *visible* surrounding headings.
23664 Any prefix to this command will cause `yank' to be called directly with
23665 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23666 will just
23667 plainly yank the text as it is.
23669 \[1] The test checks if the first non-white line is a heading
23670 and if there are no other headings with fewer stars."
23671 (interactive "P")
23672 (org-yank-generic 'yank arg))
23674 (defun org-yank-generic (command arg)
23675 "Perform some yank-like command.
23677 This function implements the behavior described in the `org-yank'
23678 documentation. However, it has been generalized to work for any
23679 interactive command with similar behavior."
23681 ;; pretend to be command COMMAND
23682 (setq this-command command)
23684 (if arg
23685 (call-interactively command)
23687 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23688 (and (org-kill-is-subtree-p)
23689 (or (bolp)
23690 (and (looking-at "[ \t]*$")
23691 (string-match
23692 "\\`\\*+\\'"
23693 (buffer-substring (point-at-bol) (point)))))))
23694 swallowp)
23695 (cond
23696 ((and subtreep org-yank-folded-subtrees)
23697 (let ((beg (point))
23698 end)
23699 (if (and subtreep org-yank-adjusted-subtrees)
23700 (org-paste-subtree nil nil 'for-yank)
23701 (call-interactively command))
23703 (setq end (point))
23704 (goto-char beg)
23705 (when (and (bolp) subtreep
23706 (not (setq swallowp
23707 (org-yank-folding-would-swallow-text beg end))))
23708 (org-with-limited-levels
23709 (or (looking-at org-outline-regexp)
23710 (re-search-forward org-outline-regexp-bol end t))
23711 (while (and (< (point) end) (looking-at org-outline-regexp))
23712 (outline-hide-subtree)
23713 (org-cycle-show-empty-lines 'folded)
23714 (condition-case nil
23715 (outline-forward-same-level 1)
23716 (error (goto-char end))))))
23717 (when swallowp
23718 (message
23719 "Inserted text not folded because that would swallow text"))
23721 (goto-char end)
23722 (skip-chars-forward " \t\n\r")
23723 (beginning-of-line 1)
23724 (push-mark beg 'nomsg)))
23725 ((and subtreep org-yank-adjusted-subtrees)
23726 (let ((beg (point-at-bol)))
23727 (org-paste-subtree nil nil 'for-yank)
23728 (push-mark beg 'nomsg)))
23730 (call-interactively command))))))
23732 (defun org-yank-folding-would-swallow-text (beg end)
23733 "Would hide-subtree at BEG swallow any text after END?"
23734 (let (level)
23735 (org-with-limited-levels
23736 (save-excursion
23737 (goto-char beg)
23738 (when (or (looking-at org-outline-regexp)
23739 (re-search-forward org-outline-regexp-bol end t))
23740 (setq level (org-outline-level)))
23741 (goto-char end)
23742 (skip-chars-forward " \t\r\n\v\f")
23743 (not (or (eobp)
23744 (and (bolp) (looking-at-p org-outline-regexp)
23745 (<= (org-outline-level) level))))))))
23747 (define-key org-mode-map "\C-y" 'org-yank)
23749 (defun org-truely-invisible-p ()
23750 "Check if point is at a character currently not visible.
23751 This version does not only check the character property, but also
23752 `visible-mode'."
23753 (unless (bound-and-true-p visible-mode)
23754 (org-invisible-p)))
23756 (defun org-invisible-p2 ()
23757 "Check if point is at a character currently not visible.
23759 If the point is at EOL (and not at the beginning of a buffer too),
23760 move it back by one char before doing this check."
23761 (save-excursion
23762 (when (and (eolp) (not (bobp)))
23763 (backward-char 1))
23764 (org-invisible-p)))
23766 (defun org-back-to-heading (&optional invisible-ok)
23767 "Call `outline-back-to-heading', but provide a better error message."
23768 (condition-case nil
23769 (outline-back-to-heading invisible-ok)
23770 (error (error "Before first headline at position %d in buffer %s"
23771 (point) (current-buffer)))))
23773 (defun org-before-first-heading-p ()
23774 "Before first heading?"
23775 (save-excursion
23776 (end-of-line)
23777 (null (re-search-backward org-outline-regexp-bol nil t))))
23779 (defun org-at-heading-p (&optional ignored)
23780 (outline-on-heading-p t))
23782 (defun org-in-commented-heading-p (&optional no-inheritance)
23783 "Non-nil if point is under a commented heading.
23784 This function also checks ancestors of the current headline,
23785 unless optional argument NO-INHERITANCE is non-nil."
23786 (cond
23787 ((org-before-first-heading-p) nil)
23788 ((let ((headline (nth 4 (org-heading-components))))
23789 (and headline
23790 (let ((case-fold-search nil))
23791 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23792 headline)))))
23793 (no-inheritance nil)
23795 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23797 (defun org-at-comment-p nil
23798 "Is cursor in a commented line?"
23799 (save-excursion
23800 (save-match-data
23801 (beginning-of-line)
23802 (looking-at "^[ \t]*# "))))
23804 (defun org-at-drawer-p nil
23805 "Is cursor at a drawer keyword?"
23806 (save-excursion
23807 (move-beginning-of-line 1)
23808 (looking-at org-drawer-regexp)))
23810 (defun org-at-block-p nil
23811 "Is cursor at a block keyword?"
23812 (save-excursion
23813 (move-beginning-of-line 1)
23814 (looking-at org-block-regexp)))
23816 (defun org-point-at-end-of-empty-headline ()
23817 "If point is at the end of an empty headline, return t, else nil.
23818 If the heading only contains a TODO keyword, it is still still considered
23819 empty."
23820 (let ((case-fold-search nil))
23821 (and (looking-at "[ \t]*$")
23822 org-todo-line-regexp
23823 (save-excursion
23824 (beginning-of-line)
23825 (looking-at org-todo-line-regexp)
23826 (string= (match-string 3) "")))))
23828 (defun org-at-heading-or-item-p ()
23829 (or (org-at-heading-p) (org-at-item-p)))
23831 (defun org-at-target-p ()
23832 (or (org-in-regexp org-radio-target-regexp)
23833 (org-in-regexp org-target-regexp)))
23834 ;; Compatibility alias with Org versions < 7.8.03
23835 (defalias 'org-on-target-p 'org-at-target-p)
23837 (defun org-up-heading-all (arg)
23838 "Move to the heading line of which the present line is a subheading.
23839 This function considers both visible and invisible heading lines.
23840 With argument, move up ARG levels."
23841 (outline-up-heading arg t))
23843 (defun org-up-heading-safe ()
23844 "Move to the heading line of which the present line is a subheading.
23845 This version will not throw an error. It will return the level of the
23846 headline found, or nil if no higher level is found.
23848 Also, this function will be a lot faster than `outline-up-heading',
23849 because it relies on stars being the outline starters. This can really
23850 make a significant difference in outlines with very many siblings."
23851 (when (ignore-errors (org-back-to-heading t))
23852 (let ((level-up (1- (funcall outline-level))))
23853 (and (> level-up 0)
23854 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23855 (funcall outline-level)))))
23857 (defun org-first-sibling-p ()
23858 "Is this heading the first child of its parents?"
23859 (interactive)
23860 (let ((re org-outline-regexp-bol)
23861 level l)
23862 (unless (org-at-heading-p t)
23863 (user-error "Not at a heading"))
23864 (setq level (funcall outline-level))
23865 (save-excursion
23866 (if (not (re-search-backward re nil t))
23868 (setq l (funcall outline-level))
23869 (< l level)))))
23871 (defun org-goto-sibling (&optional previous)
23872 "Goto the next sibling, even if it is invisible.
23873 When PREVIOUS is set, go to the previous sibling instead. Returns t
23874 when a sibling was found. When none is found, return nil and don't
23875 move point."
23876 (let ((fun (if previous 're-search-backward 're-search-forward))
23877 (pos (point))
23878 (re org-outline-regexp-bol)
23879 level l)
23880 (when (ignore-errors (org-back-to-heading t))
23881 (setq level (funcall outline-level))
23882 (catch 'exit
23883 (or previous (forward-char 1))
23884 (while (funcall fun re nil t)
23885 (setq l (funcall outline-level))
23886 (when (< l level) (goto-char pos) (throw 'exit nil))
23887 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23888 (goto-char pos)
23889 nil))))
23891 (defun org-show-siblings ()
23892 "Show all siblings of the current headline."
23893 (save-excursion
23894 (while (org-goto-sibling) (org-flag-heading nil)))
23895 (save-excursion
23896 (while (org-goto-sibling 'previous)
23897 (org-flag-heading nil))))
23899 (defun org-goto-first-child ()
23900 "Goto the first child, even if it is invisible.
23901 Return t when a child was found. Otherwise don't move point and
23902 return nil."
23903 (let (level (pos (point)) (re org-outline-regexp-bol))
23904 (when (ignore-errors (org-back-to-heading t))
23905 (setq level (outline-level))
23906 (forward-char 1)
23907 (if (and (re-search-forward re nil t) (> (outline-level) level))
23908 (progn (goto-char (match-beginning 0)) t)
23909 (goto-char pos) nil))))
23911 (defun org-show-hidden-entry ()
23912 "Show an entry where even the heading is hidden."
23913 (save-excursion
23914 (org-show-entry)))
23916 (defun org-flag-heading (flag &optional entry)
23917 "Flag the current heading. FLAG non-nil means make invisible.
23918 When ENTRY is non-nil, show the entire entry."
23919 (save-excursion
23920 (org-back-to-heading t)
23921 ;; Check if we should show the entire entry
23922 (if entry
23923 (progn
23924 (org-show-entry)
23925 (save-excursion
23926 (and (outline-next-heading)
23927 (org-flag-heading nil))))
23928 (outline-flag-region (max (point-min) (1- (point)))
23929 (save-excursion (outline-end-of-heading) (point))
23930 flag))))
23932 (defun org-get-next-sibling ()
23933 "Move to next heading of the same level, and return point.
23934 If there is no such heading, return nil.
23935 This is like outline-next-sibling, but invisible headings are ok."
23936 (let ((level (funcall outline-level)))
23937 (outline-next-heading)
23938 (while (and (not (eobp)) (> (funcall outline-level) level))
23939 (outline-next-heading))
23940 (unless (or (eobp) (< (funcall outline-level) level))
23941 (point))))
23943 (defun org-get-last-sibling ()
23944 "Move to previous heading of the same level, and return point.
23945 If there is no such heading, return nil."
23946 (let ((opoint (point))
23947 (level (funcall outline-level)))
23948 (outline-previous-heading)
23949 (when (and (/= (point) opoint) (outline-on-heading-p t))
23950 (while (and (> (funcall outline-level) level)
23951 (not (bobp)))
23952 (outline-previous-heading))
23953 (unless (< (funcall outline-level) level)
23954 (point)))))
23956 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23957 "Goto to the end of a subtree."
23958 ;; This contains an exact copy of the original function, but it uses
23959 ;; `org-back-to-heading', to make it work also in invisible
23960 ;; trees. And is uses an invisible-ok argument.
23961 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23962 ;; Furthermore, when used inside Org, finding the end of a large subtree
23963 ;; with many children and grandchildren etc, this can be much faster
23964 ;; than the outline version.
23965 (org-back-to-heading invisible-ok)
23966 (let ((first t)
23967 (level (funcall outline-level)))
23968 (if (and (derived-mode-p 'org-mode) (< level 1000))
23969 ;; A true heading (not a plain list item), in Org
23970 ;; This means we can easily find the end by looking
23971 ;; only for the right number of stars. Using a regexp to do
23972 ;; this is so much faster than using a Lisp loop.
23973 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23974 (forward-char 1)
23975 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23976 ;; something else, do it the slow way
23977 (while (and (not (eobp))
23978 (or first (> (funcall outline-level) level)))
23979 (setq first nil)
23980 (outline-next-heading)))
23981 (unless to-heading
23982 (when (memq (preceding-char) '(?\n ?\^M))
23983 ;; Go to end of line before heading
23984 (forward-char -1)
23985 (when (memq (preceding-char) '(?\n ?\^M))
23986 ;; leave blank line before heading
23987 (forward-char -1)))))
23988 (point))
23990 (defun org-end-of-meta-data (&optional full)
23991 "Skip planning line and properties drawer in current entry.
23992 When optional argument FULL is non-nil, also skip empty lines,
23993 clocking lines and regular drawers at the beginning of the
23994 entry."
23995 (org-back-to-heading t)
23996 (forward-line)
23997 (when (looking-at-p org-planning-line-re) (forward-line))
23998 (when (looking-at org-property-drawer-re)
23999 (goto-char (match-end 0))
24000 (forward-line))
24001 (when (and full (not (org-at-heading-p)))
24002 (catch 'exit
24003 (let ((end (save-excursion (outline-next-heading) (point)))
24004 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24005 (while (not (eobp))
24006 (cond ((looking-at-p org-drawer-regexp)
24007 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24008 (forward-line)
24009 (throw 'exit t)))
24010 ((looking-at-p re) (forward-line))
24011 (t (throw 'exit t))))))))
24013 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24014 "Move forward to the ARG'th subheading at same level as this one.
24015 Stop at the first and last subheadings of a superior heading.
24016 Normally this only looks at visible headings, but when INVISIBLE-OK is
24017 non-nil it will also look at invisible ones."
24018 (interactive "p")
24019 (let ((backward? (and arg (< arg 0))))
24020 (if (org-before-first-heading-p)
24021 (if backward? (goto-char (point-min)) (outline-next-heading))
24022 (org-back-to-heading invisible-ok)
24023 (unless backward? (end-of-line)) ;do not match current headline
24024 (let ((level (- (match-end 0) (match-beginning 0) 1))
24025 (f (if backward? #'re-search-backward #'re-search-forward))
24026 (count (if arg (abs arg) 1))
24027 (result (point)))
24028 (while (and (> count 0)
24029 (funcall f org-outline-regexp-bol nil 'move))
24030 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24031 (cond ((< l level) (setq count 0))
24032 ((and (= l level)
24033 (or invisible-ok
24034 (not (org-invisible-p
24035 (line-beginning-position)))))
24036 (cl-decf count)
24037 (when (= l level) (setq result (point)))))))
24038 (goto-char result))
24039 (beginning-of-line))))
24041 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24042 "Move backward to the ARG'th subheading at same level as this one.
24043 Stop at the first and last subheadings of a superior heading."
24044 (interactive "p")
24045 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24047 (defun org-next-visible-heading (arg)
24048 "Move to the next visible heading.
24050 This function wraps `outline-next-visible-heading' with
24051 `org-with-limited-levels' in order to skip over inline tasks and
24052 respect customization of `org-odd-levels-only'."
24053 (interactive "p")
24054 (org-with-limited-levels
24055 (outline-next-visible-heading arg)))
24057 (defun org-previous-visible-heading (arg)
24058 "Move to the previous visible heading.
24060 This function wraps `outline-previous-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-previous-visible-heading arg)))
24067 (defun org-next-block (arg &optional backward block-regexp)
24068 "Jump to the next block.
24070 With a prefix argument ARG, jump forward ARG many blocks.
24072 When BACKWARD is non-nil, jump to the previous block.
24074 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24075 Match data is set according to this regexp when the function
24076 returns.
24078 Return point at beginning of the opening line of found block.
24079 Throw an error if no block is found."
24080 (interactive "p")
24081 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24082 (case-fold-search t)
24083 (search-fn (if backward #'re-search-backward #'re-search-forward))
24084 (count (or arg 1))
24085 (origin (point))
24086 last-element)
24087 (if backward (beginning-of-line) (end-of-line))
24088 (while (and (> count 0) (funcall search-fn re nil t))
24089 (let ((element (save-excursion
24090 (goto-char (match-beginning 0))
24091 (save-match-data (org-element-at-point)))))
24092 (when (and (memq (org-element-type element)
24093 '(center-block comment-block dynamic-block
24094 example-block export-block quote-block
24095 special-block src-block verse-block))
24096 (<= (match-beginning 0)
24097 (org-element-property :post-affiliated element)))
24098 (setq last-element element)
24099 (cl-decf count))))
24100 (if (= count 0)
24101 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24102 (save-match-data (org-show-context)))
24103 (goto-char origin)
24104 (user-error "No %s code blocks" (if backward "previous" "further")))))
24106 (defun org-previous-block (arg &optional block-regexp)
24107 "Jump to the previous block.
24108 With a prefix argument ARG, jump backward ARG many source blocks.
24109 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24110 (interactive "p")
24111 (org-next-block arg t block-regexp))
24113 (defun org-forward-paragraph ()
24114 "Move forward to beginning of next paragraph or equivalent.
24116 The function moves point to the beginning of the next visible
24117 structural element, which can be a paragraph, a table, a list
24118 item, etc. It also provides some special moves for convenience:
24120 - On an affiliated keyword, jump to the beginning of the
24121 relative element.
24122 - On an item or a footnote definition, move to the second
24123 element inside, if any.
24124 - On a table or a property drawer, jump after it.
24125 - On a verse or source block, stop after blank lines."
24126 (interactive)
24127 (unless (eobp)
24128 (let* ((deactivate-mark nil)
24129 (element (org-element-at-point))
24130 (type (org-element-type element))
24131 (post-affiliated (org-element-property :post-affiliated element))
24132 (contents-begin (org-element-property :contents-begin element))
24133 (contents-end (org-element-property :contents-end element))
24134 (end (let ((end (org-element-property :end element)) (parent element))
24135 (while (and (setq parent (org-element-property :parent parent))
24136 (= (org-element-property :contents-end parent) end))
24137 (setq end (org-element-property :end parent)))
24138 end)))
24139 (cond ((not element)
24140 (skip-chars-forward " \r\t\n")
24141 (or (eobp) (beginning-of-line)))
24142 ;; On affiliated keywords, move to element's beginning.
24143 ((< (point) post-affiliated)
24144 (goto-char post-affiliated))
24145 ;; At a table row, move to the end of the table. Similarly,
24146 ;; at a node property, move to the end of the property
24147 ;; drawer.
24148 ((memq type '(node-property table-row))
24149 (goto-char (org-element-property
24150 :end (org-element-property :parent element))))
24151 ((memq type '(property-drawer table)) (goto-char end))
24152 ;; Consider blank lines as separators in verse and source
24153 ;; blocks to ease editing.
24154 ((memq type '(src-block verse-block))
24155 (when (eq type 'src-block)
24156 (setq contents-end
24157 (save-excursion (goto-char end)
24158 (skip-chars-backward " \r\t\n")
24159 (line-beginning-position))))
24160 (beginning-of-line)
24161 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24162 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24163 (goto-char end)
24164 (skip-chars-forward " \r\t\n")
24165 (if (= (point) contents-end) (goto-char end)
24166 (beginning-of-line))))
24167 ;; With no contents, just skip element.
24168 ((not contents-begin) (goto-char end))
24169 ;; If contents are invisible, skip the element altogether.
24170 ((org-invisible-p (line-end-position))
24171 (cl-case type
24172 (headline
24173 (org-with-limited-levels (outline-next-visible-heading 1)))
24174 ;; At a plain list, make sure we move to the next item
24175 ;; instead of skipping the whole list.
24176 (plain-list (forward-char)
24177 (org-forward-paragraph))
24178 (otherwise (goto-char end))))
24179 ((>= (point) contents-end) (goto-char end))
24180 ((>= (point) contents-begin)
24181 ;; This can only happen on paragraphs and plain lists.
24182 (cl-case type
24183 (paragraph (goto-char end))
24184 ;; At a plain list, try to move to second element in
24185 ;; first item, if possible.
24186 (plain-list (end-of-line)
24187 (org-forward-paragraph))))
24188 ;; When contents start on the middle of a line (e.g. in
24189 ;; items and footnote definitions), try to reach first
24190 ;; element starting after current line.
24191 ((> (line-end-position) contents-begin)
24192 (end-of-line)
24193 (org-forward-paragraph))
24194 (t (goto-char contents-begin))))))
24196 (defun org-backward-paragraph ()
24197 "Move backward to start of previous paragraph or equivalent.
24199 The function moves point to the beginning of the current
24200 structural element, which can be a paragraph, a table, a list
24201 item, etc., or to the beginning of the previous visible one if
24202 point is already there. It also provides some special moves for
24203 convenience:
24205 - On an affiliated keyword, jump to the first one.
24206 - On a table or a property drawer, move to its beginning.
24207 - On a verse or source block, stop before blank lines."
24208 (interactive)
24209 (unless (bobp)
24210 (let* ((deactivate-mark nil)
24211 (element (org-element-at-point))
24212 (type (org-element-type element))
24213 (contents-begin (org-element-property :contents-begin element))
24214 (contents-end (org-element-property :contents-end element))
24215 (post-affiliated (org-element-property :post-affiliated element))
24216 (begin (org-element-property :begin element)))
24217 (cond
24218 ((not element) (goto-char (point-min)))
24219 ((= (point) begin)
24220 (backward-char)
24221 (org-backward-paragraph))
24222 ((<= (point) post-affiliated) (goto-char begin))
24223 ((memq type '(node-property table-row))
24224 (goto-char (org-element-property
24225 :post-affiliated (org-element-property :parent element))))
24226 ((memq type '(property-drawer table)) (goto-char begin))
24227 ((memq type '(src-block verse-block))
24228 (when (eq type 'src-block)
24229 (setq contents-begin
24230 (save-excursion (goto-char begin) (forward-line) (point))))
24231 (if (= (point) contents-begin) (goto-char post-affiliated)
24232 ;; Inside a verse block, see blank lines as paragraph
24233 ;; separators.
24234 (let ((origin (point)))
24235 (skip-chars-backward " \r\t\n" contents-begin)
24236 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24237 (skip-chars-forward " \r\t\n" origin)
24238 (if (= (point) origin) (goto-char contents-begin)
24239 (beginning-of-line))))))
24240 ((not contents-begin) (goto-char (or post-affiliated begin)))
24241 ((eq type 'paragraph)
24242 (goto-char contents-begin)
24243 ;; When at first paragraph in an item or a footnote definition,
24244 ;; move directly to beginning of line.
24245 (let ((parent-contents
24246 (org-element-property
24247 :contents-begin (org-element-property :parent element))))
24248 (when (and parent-contents (= parent-contents contents-begin))
24249 (beginning-of-line))))
24250 ;; At the end of a greater element, move to the beginning of the
24251 ;; last element within.
24252 ((>= (point) contents-end)
24253 (goto-char (1- contents-end))
24254 (org-backward-paragraph))
24255 (t (goto-char (or post-affiliated begin))))
24256 ;; Ensure we never leave point invisible.
24257 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24259 (defun org-forward-element ()
24260 "Move forward by one element.
24261 Move to the next element at the same level, when possible."
24262 (interactive)
24263 (cond ((eobp) (user-error "Cannot move further down"))
24264 ((org-with-limited-levels (org-at-heading-p))
24265 (let ((origin (point)))
24266 (goto-char (org-end-of-subtree nil t))
24267 (unless (org-with-limited-levels (org-at-heading-p))
24268 (goto-char origin)
24269 (user-error "Cannot move further down"))))
24271 (let* ((elem (org-element-at-point))
24272 (end (org-element-property :end elem))
24273 (parent (org-element-property :parent elem)))
24274 (cond ((and parent (= (org-element-property :contents-end parent) end))
24275 (goto-char (org-element-property :end parent)))
24276 ((integer-or-marker-p end) (goto-char end))
24277 (t (message "No element at point")))))))
24279 (defun org-backward-element ()
24280 "Move backward by one element.
24281 Move to the previous element at the same level, when possible."
24282 (interactive)
24283 (cond ((bobp) (user-error "Cannot move further up"))
24284 ((org-with-limited-levels (org-at-heading-p))
24285 ;; At a headline, move to the previous one, if any, or stay
24286 ;; here.
24287 (let ((origin (point)))
24288 (org-with-limited-levels (org-backward-heading-same-level 1))
24289 ;; When current headline has no sibling above, move to its
24290 ;; parent.
24291 (when (= (point) origin)
24292 (or (org-with-limited-levels (org-up-heading-safe))
24293 (progn (goto-char origin)
24294 (user-error "Cannot move further up"))))))
24296 (let* ((elem (org-element-at-point))
24297 (beg (org-element-property :begin elem)))
24298 (cond
24299 ;; Move to beginning of current element if point isn't
24300 ;; there already.
24301 ((null beg) (message "No element at point"))
24302 ((/= (point) beg) (goto-char beg))
24303 (t (goto-char beg)
24304 (skip-chars-backward " \r\t\n")
24305 (unless (bobp)
24306 (let ((prev (org-element-at-point)))
24307 (goto-char (org-element-property :begin prev))
24308 (while (and (setq prev (org-element-property :parent prev))
24309 (<= (org-element-property :end prev) beg))
24310 (goto-char (org-element-property :begin prev)))))))))))
24312 (defun org-up-element ()
24313 "Move to upper element."
24314 (interactive)
24315 (if (org-with-limited-levels (org-at-heading-p))
24316 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24317 (let* ((elem (org-element-at-point))
24318 (parent (org-element-property :parent elem)))
24319 (if parent (goto-char (org-element-property :begin parent))
24320 (if (org-with-limited-levels (org-before-first-heading-p))
24321 (user-error "No surrounding element")
24322 (org-with-limited-levels (org-back-to-heading)))))))
24324 (defun org-down-element ()
24325 "Move to inner element."
24326 (interactive)
24327 (let ((element (org-element-at-point)))
24328 (cond
24329 ((memq (org-element-type element) '(plain-list table))
24330 (goto-char (org-element-property :contents-begin element))
24331 (forward-char))
24332 ((memq (org-element-type element) org-element-greater-elements)
24333 ;; If contents are hidden, first disclose them.
24334 (when (org-invisible-p (line-end-position)) (org-cycle))
24335 (goto-char (or (org-element-property :contents-begin element)
24336 (user-error "No content for this element"))))
24337 (t (user-error "No inner element")))))
24339 (defun org-drag-element-backward ()
24340 "Move backward element at point."
24341 (interactive)
24342 (let ((elem (or (org-element-at-point)
24343 (user-error "No element at point"))))
24344 (if (eq (org-element-type elem) 'headline)
24345 ;; Preserve point when moving a whole tree, even if point was
24346 ;; on blank lines below the headline.
24347 (let ((offset (skip-chars-backward " \t\n")))
24348 (unwind-protect (org-move-subtree-up)
24349 (forward-char (- offset))))
24350 (let ((prev-elem
24351 (save-excursion
24352 (goto-char (org-element-property :begin elem))
24353 (skip-chars-backward " \r\t\n")
24354 (unless (bobp)
24355 (let* ((beg (org-element-property :begin elem))
24356 (prev (org-element-at-point))
24357 (up prev))
24358 (while (and (setq up (org-element-property :parent up))
24359 (<= (org-element-property :end up) beg))
24360 (setq prev up))
24361 prev)))))
24362 ;; Error out if no previous element or previous element is
24363 ;; a parent of the current one.
24364 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24365 (user-error "Cannot drag element backward")
24366 (let ((pos (point)))
24367 (org-element-swap-A-B prev-elem elem)
24368 (goto-char (+ (org-element-property :begin prev-elem)
24369 (- pos (org-element-property :begin elem))))))))))
24371 (defun org-drag-element-forward ()
24372 "Move forward element at point."
24373 (interactive)
24374 (let* ((pos (point))
24375 (elem (or (org-element-at-point)
24376 (user-error "No element at point"))))
24377 (when (= (point-max) (org-element-property :end elem))
24378 (user-error "Cannot drag element forward"))
24379 (goto-char (org-element-property :end elem))
24380 (let ((next-elem (org-element-at-point)))
24381 (when (or (org-element-nested-p elem next-elem)
24382 (and (eq (org-element-type next-elem) 'headline)
24383 (not (eq (org-element-type elem) 'headline))))
24384 (goto-char pos)
24385 (user-error "Cannot drag element forward"))
24386 ;; Compute new position of point: it's shifted by NEXT-ELEM
24387 ;; body's length (without final blanks) and by the length of
24388 ;; blanks between ELEM and NEXT-ELEM.
24389 (let ((size-next (- (save-excursion
24390 (goto-char (org-element-property :end next-elem))
24391 (skip-chars-backward " \r\t\n")
24392 (forward-line)
24393 ;; Small correction if buffer doesn't end
24394 ;; with a newline character.
24395 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24396 (org-element-property :begin next-elem)))
24397 (size-blank (- (org-element-property :end elem)
24398 (save-excursion
24399 (goto-char (org-element-property :end elem))
24400 (skip-chars-backward " \r\t\n")
24401 (forward-line)
24402 (point)))))
24403 (org-element-swap-A-B elem next-elem)
24404 (goto-char (+ pos size-next size-blank))))))
24406 (defun org-drag-line-forward (arg)
24407 "Drag the line at point ARG lines forward."
24408 (interactive "p")
24409 (dotimes (_ (abs arg))
24410 (let ((c (current-column)))
24411 (if (< 0 arg)
24412 (progn
24413 (beginning-of-line 2)
24414 (transpose-lines 1)
24415 (beginning-of-line 0))
24416 (transpose-lines 1)
24417 (beginning-of-line -1))
24418 (org-move-to-column c))))
24420 (defun org-drag-line-backward (arg)
24421 "Drag the line at point ARG lines backward."
24422 (interactive "p")
24423 (org-drag-line-forward (- arg)))
24425 (defun org-mark-element ()
24426 "Put point at beginning of this element, mark at end.
24428 Interactively, if this command is repeated or (in Transient Mark
24429 mode) if the mark is active, it marks the next element after the
24430 ones already marked."
24431 (interactive)
24432 (let (deactivate-mark)
24433 (if (and (called-interactively-p 'any)
24434 (or (and (eq last-command this-command) (mark t))
24435 (and transient-mark-mode mark-active)))
24436 (set-mark
24437 (save-excursion
24438 (goto-char (mark))
24439 (goto-char (org-element-property :end (org-element-at-point)))))
24440 (let ((element (org-element-at-point)))
24441 (end-of-line)
24442 (push-mark (org-element-property :end element) t t)
24443 (goto-char (org-element-property :begin element))))))
24445 (defun org-narrow-to-element ()
24446 "Narrow buffer to current element."
24447 (interactive)
24448 (let ((elem (org-element-at-point)))
24449 (cond
24450 ((eq (car elem) 'headline)
24451 (narrow-to-region
24452 (org-element-property :begin elem)
24453 (org-element-property :end elem)))
24454 ((memq (car elem) org-element-greater-elements)
24455 (narrow-to-region
24456 (org-element-property :contents-begin elem)
24457 (org-element-property :contents-end elem)))
24459 (narrow-to-region
24460 (org-element-property :begin elem)
24461 (org-element-property :end elem))))))
24463 (defun org-transpose-element ()
24464 "Transpose current and previous elements, keeping blank lines between.
24465 Point is moved after both elements."
24466 (interactive)
24467 (org-skip-whitespace)
24468 (let ((end (org-element-property :end (org-element-at-point))))
24469 (org-drag-element-backward)
24470 (goto-char end)))
24472 (defun org-unindent-buffer ()
24473 "Un-indent the visible part of the buffer.
24474 Relative indentation (between items, inside blocks, etc.) isn't
24475 modified."
24476 (interactive)
24477 (unless (eq major-mode 'org-mode)
24478 (user-error "Cannot un-indent a buffer not in Org mode"))
24479 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24480 (unindent-tree
24481 (lambda (contents)
24482 (dolist (element (reverse contents))
24483 (if (memq (org-element-type element) '(headline section))
24484 (funcall unindent-tree (org-element-contents element))
24485 (save-excursion
24486 (save-restriction
24487 (narrow-to-region
24488 (org-element-property :begin element)
24489 (org-element-property :end element))
24490 (org-do-remove-indentation))))))))
24491 (funcall unindent-tree (org-element-contents parse-tree))))
24493 (defun org-show-children (&optional level)
24494 "Show all direct subheadings of this heading.
24495 Prefix arg LEVEL is how many levels below the current level
24496 should be shown. Default is enough to cause the following
24497 heading to appear."
24498 (interactive "p")
24499 ;; If `orgstruct-mode' is active, use the slower version.
24500 (if orgstruct-mode (call-interactively #'outline-show-children)
24501 (save-excursion
24502 (org-back-to-heading t)
24503 (let* ((current-level (funcall outline-level))
24504 (max-level (org-get-valid-level
24505 current-level
24506 (if level (prefix-numeric-value level) 1)))
24507 (end (save-excursion (org-end-of-subtree t t)))
24508 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24509 (past-first-child nil)
24510 ;; Make sure to skip inlinetasks.
24511 (re (format regexp-fmt
24512 current-level
24513 (cond
24514 ((not (featurep 'org-inlinetask)) "")
24515 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24517 (t (1- org-inlinetask-min-level))))))
24518 ;; Display parent heading.
24519 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24520 (forward-line)
24521 ;; Display children. First child may be deeper than expected
24522 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24523 ;; MAX-LEVEL accordingly.
24524 (while (re-search-forward re end t)
24525 (unless past-first-child
24526 (setq re (format regexp-fmt
24527 current-level
24528 (max (funcall outline-level) max-level)))
24529 (setq past-first-child t))
24530 (outline-flag-region
24531 (line-end-position 0) (line-end-position) nil))))))
24533 (defun org-show-subtree ()
24534 "Show everything after this heading at deeper levels."
24535 (interactive)
24536 (outline-flag-region
24537 (point)
24538 (save-excursion
24539 (org-end-of-subtree t t))
24540 nil))
24542 (defun org-show-entry ()
24543 "Show the body directly following this heading.
24544 Show the heading too, if it is currently invisible."
24545 (interactive)
24546 (save-excursion
24547 (ignore-errors
24548 (org-back-to-heading t)
24549 (outline-flag-region
24550 (max (point-min) (1- (point)))
24551 (save-excursion
24552 (if (re-search-forward
24553 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24554 (match-beginning 1)
24555 (point-max)))
24556 nil)
24557 (org-cycle-hide-drawers 'children))))
24559 (defun org-make-options-regexp (kwds &optional extra)
24560 "Make a regular expression for keyword lines.
24561 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24562 when non-nil, is a regexp matching keywords names."
24563 (concat "^[ \t]*#\\+\\("
24564 (regexp-opt kwds)
24565 (and extra (concat (and kwds "\\|") extra))
24566 "\\):[ \t]*\\(.*\\)"))
24568 ;;;; Integration with and fixes for other packages
24570 ;;; Imenu support
24572 (defvar-local org-imenu-markers nil
24573 "All markers currently used by Imenu.")
24575 (defun org-imenu-new-marker (&optional pos)
24576 "Return a new marker for use by Imenu, and remember the marker."
24577 (let ((m (make-marker)))
24578 (move-marker m (or pos (point)))
24579 (push m org-imenu-markers)
24582 (defun org-imenu-get-tree ()
24583 "Produce the index for Imenu."
24584 (dolist (x org-imenu-markers) (move-marker x nil))
24585 (setq org-imenu-markers nil)
24586 (let* ((case-fold-search nil)
24587 (n org-imenu-depth)
24588 (re (concat "^" (org-get-limited-outline-regexp)))
24589 (subs (make-vector (1+ n) nil))
24590 (last-level 0)
24591 m level head0 head)
24592 (org-with-wide-buffer
24593 (goto-char (point-max))
24594 (while (re-search-backward re nil t)
24595 (setq level (org-reduced-level (funcall outline-level)))
24596 (when (and (<= level n)
24597 (looking-at org-complex-heading-regexp)
24598 (setq head0 (match-string-no-properties 4)))
24599 (setq head (org-link-display-format head0)
24600 m (org-imenu-new-marker))
24601 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24602 (if (>= level last-level)
24603 (push (cons head m) (aref subs level))
24604 (push (cons head (aref subs (1+ level))) (aref subs level))
24605 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24606 (setq last-level level))))
24607 (aref subs 1)))
24609 (eval-after-load "imenu"
24610 '(progn
24611 (add-hook 'imenu-after-jump-hook
24612 (lambda ()
24613 (when (derived-mode-p 'org-mode)
24614 (org-show-context 'org-goto))))))
24616 (defun org-link-display-format (s)
24617 "Replace links in string S with their description.
24618 If there is no description, use the link target."
24619 (save-match-data
24620 (replace-regexp-in-string
24621 org-bracket-link-analytic-regexp
24622 (lambda (m)
24623 (if (match-end 5) (match-string 5 m)
24624 (concat (match-string 1 m) (match-string 3 m))))
24625 s nil t)))
24627 (defun org-toggle-link-display ()
24628 "Toggle the literal or descriptive display of links."
24629 (interactive)
24630 (if org-descriptive-links
24631 (progn (org-remove-from-invisibility-spec '(org-link))
24632 (org-restart-font-lock)
24633 (setq org-descriptive-links nil))
24634 (progn (add-to-invisibility-spec '(org-link))
24635 (org-restart-font-lock)
24636 (setq org-descriptive-links t))))
24638 ;; Speedbar support
24640 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24641 "Overlay marking the agenda restriction line in speedbar.")
24642 (overlay-put org-speedbar-restriction-lock-overlay
24643 'face 'org-agenda-restriction-lock)
24644 (overlay-put org-speedbar-restriction-lock-overlay
24645 'help-echo "Agendas are currently limited to this item.")
24646 (delete-overlay org-speedbar-restriction-lock-overlay)
24648 (defun org-speedbar-set-agenda-restriction ()
24649 "Restrict future agenda commands to the location at point in speedbar.
24650 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24651 (interactive)
24652 (require 'org-agenda)
24653 (let (p m tp np dir txt)
24654 (cond
24655 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24656 'org-imenu t))
24657 (setq m (get-text-property p 'org-imenu-marker))
24658 (with-current-buffer (marker-buffer m)
24659 (goto-char m)
24660 (org-agenda-set-restriction-lock 'subtree)))
24661 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24662 'speedbar-function 'speedbar-find-file))
24663 (setq tp (previous-single-property-change
24664 (1+ p) 'speedbar-function)
24665 np (next-single-property-change
24666 tp 'speedbar-function)
24667 dir (speedbar-line-directory)
24668 txt (buffer-substring-no-properties (or tp (point-min))
24669 (or np (point-max))))
24670 (with-current-buffer (find-file-noselect
24671 (let ((default-directory dir))
24672 (expand-file-name txt)))
24673 (unless (derived-mode-p 'org-mode)
24674 (user-error "Cannot restrict to non-Org mode file"))
24675 (org-agenda-set-restriction-lock 'file)))
24676 (t (user-error "Don't know how to restrict Org mode agenda")))
24677 (move-overlay org-speedbar-restriction-lock-overlay
24678 (point-at-bol) (point-at-eol))
24679 (setq current-prefix-arg nil)
24680 (org-agenda-maybe-redo)))
24682 (defvar speedbar-file-key-map)
24683 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24684 (eval-after-load "speedbar"
24685 '(progn
24686 (speedbar-add-supported-extension ".org")
24687 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24688 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24689 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24690 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24691 (add-hook 'speedbar-visiting-tag-hook
24692 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24694 ;;; Fixes and Hacks for problems with other packages
24696 (defun org--flyspell-object-check-p (element)
24697 "Non-nil when Flyspell can check object at point.
24698 ELEMENT is the element at point."
24699 (let ((object (save-excursion
24700 (when (looking-at-p "\\>") (backward-char))
24701 (org-element-context element))))
24702 (cl-case (org-element-type object)
24703 ;; Prevent checks in links due to keybinding conflict with
24704 ;; Flyspell.
24705 ((code entity export-snippet inline-babel-call
24706 inline-src-block line-break latex-fragment link macro
24707 statistics-cookie target timestamp verbatim)
24708 nil)
24709 (footnote-reference
24710 ;; Only in inline footnotes, within the definition.
24711 (and (eq (org-element-property :type object) 'inline)
24712 (< (save-excursion
24713 (goto-char (org-element-property :begin object))
24714 (search-forward ":" nil t 2))
24715 (point))))
24716 (otherwise t))))
24718 (defun org-mode-flyspell-verify ()
24719 "Function used for `flyspell-generic-check-word-predicate'."
24720 (if (org-at-heading-p)
24721 ;; At a headline or an inlinetask, check title only. This is
24722 ;; faster than relying on `org-element-at-point'.
24723 (and (save-excursion (beginning-of-line)
24724 (and (let ((case-fold-search t))
24725 (not (looking-at-p "\\*+ END[ \t]*$")))
24726 (let ((case-fold-search nil))
24727 (looking-at org-complex-heading-regexp))))
24728 (match-beginning 4)
24729 (>= (point) (match-beginning 4))
24730 (or (not (match-beginning 5))
24731 (< (point) (match-beginning 5))))
24732 (let* ((element (org-element-at-point))
24733 (post-affiliated (org-element-property :post-affiliated element)))
24734 (cond
24735 ;; Ignore checks in all affiliated keywords but captions.
24736 ((< (point) post-affiliated)
24737 (and (save-excursion
24738 (beginning-of-line)
24739 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24740 (> (point) (match-end 0))
24741 (org--flyspell-object-check-p element)))
24742 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24743 ((let ((log (org-log-into-drawer)))
24744 (and log
24745 (let ((drawer (org-element-lineage element '(drawer))))
24746 (and drawer
24747 (eq (compare-strings
24748 log nil nil
24749 (org-element-property :drawer-name drawer) nil nil t)
24750 t)))))
24751 nil)
24753 (cl-case (org-element-type element)
24754 ((comment quote-section) t)
24755 (comment-block
24756 ;; Allow checks between block markers, not on them.
24757 (and (> (line-beginning-position) post-affiliated)
24758 (save-excursion
24759 (end-of-line)
24760 (skip-chars-forward " \r\t\n")
24761 (< (point) (org-element-property :end element)))))
24762 ;; Arbitrary list of keywords where checks are meaningful.
24763 ;; Make sure point is on the value part of the element.
24764 (keyword
24765 (and (member (org-element-property :key element)
24766 '("DESCRIPTION" "TITLE"))
24767 (save-excursion
24768 (search-backward ":" (line-beginning-position) t))))
24769 ;; Check is globally allowed in paragraphs verse blocks and
24770 ;; table rows (after affiliated keywords) but some objects
24771 ;; must not be affected.
24772 ((paragraph table-row verse-block)
24773 (let ((cbeg (org-element-property :contents-begin element))
24774 (cend (org-element-property :contents-end element)))
24775 (and cbeg (>= (point) cbeg) (< (point) cend)
24776 (org--flyspell-object-check-p element))))))))))
24777 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24779 (defun org-remove-flyspell-overlays-in (beg end)
24780 "Remove flyspell overlays in region."
24781 (and (bound-and-true-p flyspell-mode)
24782 (fboundp 'flyspell-delete-region-overlays)
24783 (flyspell-delete-region-overlays beg end)))
24785 (defvar flyspell-delayed-commands)
24786 (eval-after-load "flyspell"
24787 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24789 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24790 (eval-after-load "bookmark"
24791 '(if (boundp 'bookmark-after-jump-hook)
24792 ;; We can use the hook
24793 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24794 ;; Hook not available, use advice
24795 (defadvice bookmark-jump (after org-make-visible activate)
24796 "Make the position visible."
24797 (org-bookmark-jump-unhide))))
24799 ;; Make sure saveplace shows the location if it was hidden
24800 (eval-after-load "saveplace"
24801 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24802 "Make the position visible."
24803 (org-bookmark-jump-unhide)))
24805 ;; Make sure ecb shows the location if it was hidden
24806 (eval-after-load "ecb"
24807 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24808 "Make hierarchy visible when jumping into location from ECB tree buffer."
24809 (when (derived-mode-p 'org-mode)
24810 (org-show-context))))
24812 (defun org-bookmark-jump-unhide ()
24813 "Unhide the current position, to show the bookmark location."
24814 (and (derived-mode-p 'org-mode)
24815 (or (org-invisible-p)
24816 (save-excursion (goto-char (max (point-min) (1- (point))))
24817 (org-invisible-p)))
24818 (org-show-context 'bookmark-jump)))
24820 (defun org-mark-jump-unhide ()
24821 "Make the point visible with `org-show-context' after jumping to the mark."
24822 (when (and (derived-mode-p 'org-mode)
24823 (org-invisible-p))
24824 (org-show-context 'mark-goto)))
24826 (eval-after-load "simple"
24827 '(defadvice pop-to-mark-command (after org-make-visible activate)
24828 "Make the point visible with `org-show-context'."
24829 (org-mark-jump-unhide)))
24831 (eval-after-load "simple"
24832 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24833 "Make the point visible with `org-show-context'."
24834 (org-mark-jump-unhide)))
24836 (eval-after-load "simple"
24837 '(defadvice pop-global-mark (after org-make-visible activate)
24838 "Make the point visible with `org-show-context'."
24839 (org-mark-jump-unhide)))
24841 ;; Make session.el ignore our circular variable
24842 (defvar session-globals-exclude)
24843 (eval-after-load "session"
24844 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24846 ;;;; Finish up
24848 (provide 'org)
24850 (run-hooks 'org-load-hook)
24852 ;;; org.el ends here