Fix `org-backward-paragraph' on block opening line
[org-mode/org-tableheadings.git] / lisp / org.el
blob35405b4bf81a7a4425c4b210e98ec335917f2d6e
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp) ;Silence byte-compiler
187 (defsubst org-uniquify (list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list))) (delete-dups res)))
191 (defsubst org-get-at-bol (property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property))
195 (defsubst org-trim (s &optional keep-lead)
196 "Remove whitespace at the beginning and the end of string S.
197 When optional argument KEEP-LEAD is non-nil, removing blank lines
198 at the beginning of the string does not affect leading indentation."
199 (replace-regexp-in-string
200 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
201 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
203 ;; load languages based on value of `org-babel-load-languages'
204 (defvar org-babel-load-languages)
206 ;;;###autoload
207 (defun org-babel-do-load-languages (sym value)
208 "Load the languages defined in `org-babel-load-languages'."
209 (set-default sym value)
210 (dolist (pair org-babel-load-languages)
211 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
212 (if active
213 (require (intern (concat "ob-" lang)))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang)))))))
219 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
220 ;;;###autoload
221 (defun org-babel-load-file (file &optional compile)
222 "Load Emacs Lisp source code blocks in the Org FILE.
223 This function exports the source code using `org-babel-tangle'
224 and then loads the resulting file using `load-file'. With prefix
225 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
226 file to byte-code before it is loaded."
227 (interactive "fFile to load: \nP")
228 (let* ((age (lambda (file)
229 (float-time
230 (time-subtract (current-time)
231 (nth 5 (or (file-attributes (file-truename file))
232 (file-attributes file)))))))
233 (base-name (file-name-sans-extension file))
234 (exported-file (concat base-name ".el")))
235 ;; tangle if the Org file is newer than the elisp file
236 (unless (and (file-exists-p exported-file)
237 (> (funcall age file) (funcall age exported-file)))
238 ;; Tangle-file traversal returns reversed list of tangled files
239 ;; and we want to evaluate the first target.
240 (setq exported-file
241 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
242 (message "%s %s"
243 (if compile
244 (progn (byte-compile-file exported-file 'load)
245 "Compiled and loaded")
246 (progn (load-file exported-file) "Loaded"))
247 exported-file)))
249 (defcustom org-babel-load-languages '((emacs-lisp . t))
250 "Languages which can be evaluated in Org buffers.
251 This list can be used to load support for any of the languages
252 below, note that each language will depend on a different set of
253 system executables and/or Emacs modes. When a language is
254 \"loaded\", then code blocks in that language can be evaluated
255 with `org-babel-execute-src-block' bound by default to C-c
256 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
257 be set to remove code block evaluation from the C-c C-c
258 keybinding. By default only Emacs Lisp (which has no
259 requirements) is loaded."
260 :group 'org-babel
261 :set 'org-babel-do-load-languages
262 :version "24.1"
263 :type '(alist :tag "Babel Languages"
264 :key-type
265 (choice
266 (const :tag "Awk" awk)
267 (const :tag "C" C)
268 (const :tag "R" R)
269 (const :tag "Asymptote" asymptote)
270 (const :tag "Calc" calc)
271 (const :tag "Clojure" clojure)
272 (const :tag "CSS" css)
273 (const :tag "Ditaa" ditaa)
274 (const :tag "Dot" dot)
275 (const :tag "Ebnf2ps" ebnf2ps)
276 (const :tag "Emacs Lisp" emacs-lisp)
277 (const :tag "Forth" forth)
278 (const :tag "Fortran" fortran)
279 (const :tag "Gnuplot" gnuplot)
280 (const :tag "Haskell" haskell)
281 (const :tag "hledger" hledger)
282 (const :tag "IO" io)
283 (const :tag "J" J)
284 (const :tag "Java" java)
285 (const :tag "Javascript" js)
286 (const :tag "LaTeX" latex)
287 (const :tag "Ledger" ledger)
288 (const :tag "Lilypond" lilypond)
289 (const :tag "Lisp" lisp)
290 (const :tag "Makefile" makefile)
291 (const :tag "Maxima" maxima)
292 (const :tag "Matlab" matlab)
293 (const :tag "Mscgen" mscgen)
294 (const :tag "Ocaml" ocaml)
295 (const :tag "Octave" octave)
296 (const :tag "Org" org)
297 (const :tag "Perl" perl)
298 (const :tag "Pico Lisp" picolisp)
299 (const :tag "PlantUML" plantuml)
300 (const :tag "Python" python)
301 (const :tag "Ruby" ruby)
302 (const :tag "Sass" sass)
303 (const :tag "Scala" scala)
304 (const :tag "Scheme" scheme)
305 (const :tag "Screen" screen)
306 (const :tag "Shell Script" shell)
307 (const :tag "Shen" shen)
308 (const :tag "Sql" sql)
309 (const :tag "Sqlite" sqlite)
310 (const :tag "Stan" stan)
311 (const :tag "Vala" vala))
312 :value-type (boolean :tag "Activate" :value t)))
314 ;;;; Customization variables
315 (defcustom org-clone-delete-id nil
316 "Remove ID property of clones of a subtree.
317 When non-nil, clones of a subtree don't inherit the ID property.
318 Otherwise they inherit the ID property with a new unique
319 identifier."
320 :type 'boolean
321 :version "24.1"
322 :group 'org-id)
324 ;;; Version
325 (org-check-version)
327 ;;;###autoload
328 (defun org-version (&optional here full message)
329 "Show the Org version.
330 Interactively, or when MESSAGE is non-nil, show it in echo area.
331 With prefix argument, or when HERE is non-nil, insert it at point.
332 In non-interactive uses, a reduced version string is output unless
333 FULL is given."
334 (interactive (list current-prefix-arg t (not current-prefix-arg)))
335 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
336 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
337 (load-suffixes (list ".el"))
338 (org-install-dir
339 (ignore-errors (org-find-library-dir "org-loaddefs"))))
340 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
341 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
342 (let* ((load-suffixes save-load-suffixes)
343 (release (org-release))
344 (git-version (org-git-version))
345 (version (format "Org mode version %s (%s @ %s)"
346 release
347 git-version
348 (if org-install-dir
349 (if (string= org-dir org-install-dir)
350 org-install-dir
351 (concat "mixed installation! "
352 org-install-dir
353 " and "
354 org-dir))
355 "org-loaddefs.el can not be found!")))
356 (version1 (if full version release)))
357 (when here (insert version1))
358 (when message (message "%s" version1))
359 version1)))
361 (defconst org-version (org-version))
364 ;;; Syntax Constants
366 ;;;; Block
368 (defconst org-block-regexp
369 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
370 "Regular expression for hiding blocks.")
372 (defconst org-dblock-start-re
373 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
374 "Matches the start line of a dynamic block, with parameters.")
376 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
377 "Matches the end of a dynamic block.")
379 ;;;; Clock and Planning
381 (defconst org-clock-string "CLOCK:"
382 "String used as prefix for timestamps clocking work hours on an item.")
384 (defvar org-closed-string "CLOSED:"
385 "String used as the prefix for timestamps logging closing a TODO entry.")
387 (defvar org-deadline-string "DEADLINE:"
388 "String to mark deadline entries.
389 \\<org-mode-map>
390 A deadline is this string, followed by a time stamp. It must be
391 a word, terminated by a colon. You can insert a schedule keyword
392 and a timestamp with `\\[org-deadline]'.")
394 (defvar org-scheduled-string "SCHEDULED:"
395 "String to mark scheduled TODO entries.
396 \\<org-mode-map>
397 A schedule is this string, followed by a time stamp. It must be
398 a word, terminated by a colon. You can insert a schedule keyword
399 and a timestamp with `\\[org-schedule]'.")
401 (defconst org-ds-keyword-length
402 (+ 2
403 (apply #'max
404 (mapcar #'length
405 (list org-deadline-string org-scheduled-string
406 org-clock-string org-closed-string))))
407 "Maximum length of the DEADLINE and SCHEDULED keywords.")
409 (defconst org-planning-line-re
410 (concat "^[ \t]*"
411 (regexp-opt
412 (list org-closed-string org-deadline-string org-scheduled-string)
414 "Matches a line with planning info.
415 Matched keyword is in group 1.")
417 (defconst org-clock-line-re
418 (concat "^[ \t]*" org-clock-string)
419 "Matches a line with clock info.")
421 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
422 "Matches the DEADLINE keyword.")
424 (defconst org-deadline-time-regexp
425 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
426 "Matches the DEADLINE keyword together with a time stamp.")
428 (defconst org-deadline-time-hour-regexp
429 (concat "\\<" org-deadline-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
433 (defconst org-deadline-line-regexp
434 (concat "\\<\\(" org-deadline-string "\\).*")
435 "Matches the DEADLINE keyword and the rest of the line.")
437 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
438 "Matches the SCHEDULED keyword.")
440 (defconst org-scheduled-time-regexp
441 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
442 "Matches the SCHEDULED keyword together with a time stamp.")
444 (defconst org-scheduled-time-hour-regexp
445 (concat "\\<" org-scheduled-string
446 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
447 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
449 (defconst org-closed-time-regexp
450 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
451 "Matches the CLOSED keyword together with a time stamp.")
453 (defconst org-keyword-time-regexp
454 (concat "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string
457 org-clock-string)
459 " *[[<]\\([^]>]+\\)[]>]")
460 "Matches any of the 4 keywords, together with the time stamp.")
462 (defconst org-keyword-time-not-clock-regexp
463 (concat
464 "\\<"
465 (regexp-opt
466 (list org-scheduled-string org-deadline-string org-closed-string) t)
467 " *[[<]\\([^]>]+\\)[]>]")
468 "Matches any of the 3 keywords, together with the time stamp.")
470 (defconst org-maybe-keyword-time-regexp
471 (concat "\\(\\<"
472 (regexp-opt
473 (list org-scheduled-string org-deadline-string org-closed-string
474 org-clock-string)
476 "\\)?"
477 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
478 "\\|"
479 "<%%([^\r\n>]*>\\)")
480 "Matches a timestamp, possibly preceded by a keyword.")
482 (defconst org-all-time-keywords
483 (mapcar (lambda (w) (substring w 0 -1))
484 (list org-scheduled-string org-deadline-string
485 org-clock-string org-closed-string))
486 "List of time keywords.")
488 ;;;; Drawer
490 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
491 "Matches first or last line of a hidden block.
492 Group 1 contains drawer's name or \"END\".")
494 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
495 "Regular expression matching the first line of a property drawer.")
497 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
498 "Regular expression matching the last line of a property drawer.")
500 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
501 "Regular expression matching the first line of a clock drawer.")
503 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
504 "Regular expression matching the last line of a clock drawer.")
506 (defconst org-property-drawer-re
507 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
508 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
509 "[ \t]*:END:[ \t]*$")
510 "Matches an entire property drawer.")
512 (defconst org-clock-drawer-re
513 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
514 org-clock-drawer-end-re "\\)\n?")
515 "Matches an entire clock drawer.")
517 ;;;; Headline
519 (defconst org-heading-keyword-regexp-format
520 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
521 "Printf format for a regexp matching a headline with some keyword.
522 This regexp will match the headline of any node which has the
523 exact keyword that is put into the format. The keyword isn't in
524 any group by default, but the stars and the body are.")
526 (defconst org-heading-keyword-maybe-regexp-format
527 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
528 "Printf format for a regexp matching a headline, possibly with some keyword.
529 This regexp can match any headline with the specified keyword, or
530 without a keyword. The keyword isn't in any group by default,
531 but the stars and the body are.")
533 (defconst org-archive-tag "ARCHIVE"
534 "The tag that marks a subtree as archived.
535 An archived subtree does not open during visibility cycling, and does
536 not contribute to the agenda listings.")
538 (eval-and-compile
539 (defconst org-comment-string "COMMENT"
540 "Entries starting with this keyword will never be exported.
541 \\<org-mode-map>
542 An entry can be toggled between COMMENT and normal with
543 `\\[org-toggle-comment]'."))
546 ;;;; LaTeX Environments and Fragments
548 (defconst org-latex-regexps
549 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
550 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
551 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
552 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
554 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
555 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
556 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
557 "Regular expressions for matching embedded LaTeX.")
559 ;;;; Node Property
561 (defconst org-effort-property "Effort"
562 "The property that is being used to keep track of effort estimates.
563 Effort estimates given in this property need to have the format H:MM.")
565 ;;;; Table
567 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
568 "Detect an org-type or table-type table.")
570 (defconst org-table-line-regexp "^[ \t]*|"
571 "Detect an org-type table line.")
573 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
574 "Detect an org-type table line.")
576 (defconst org-table-hline-regexp "^[ \t]*|-"
577 "Detect an org-type table hline.")
579 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
580 "Detect a table-type table hline.")
582 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
583 "Detect the first line outside a table when searching from within it.
584 This works for both table types.")
586 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
587 "Detect a #+TBLFM line.")
589 ;;;; Timestamp
591 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
592 "Regular expression for fast time stamp matching.")
594 (defconst org-ts-regexp-inactive
595 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
596 "Regular expression for fast inactive time stamp matching.")
598 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
599 "Regular expression for fast time stamp matching.")
601 (defconst org-ts-regexp0
602 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
603 "Regular expression matching time strings for analysis.
604 This one does not require the space after the date, so it can be used
605 on a string that terminates immediately after the date.")
607 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
608 "Regular expression matching time strings for analysis.")
610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
611 "Regular expression matching time stamps, with groups.")
613 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
614 "Regular expression matching time stamps (also [..]), with groups.")
616 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
617 "Regular expression matching a time stamp range.")
619 (defconst org-tr-regexp-both
620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
621 "Regular expression matching a time stamp range.")
623 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
624 org-ts-regexp "\\)?")
625 "Regular expression matching a time stamp or time stamp range.")
627 (defconst org-tsr-regexp-both
628 (concat org-ts-regexp-both "\\(--?-?"
629 org-ts-regexp-both "\\)?")
630 "Regular expression matching a time stamp or time stamp range.
631 The time stamps may be either active or inactive.")
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
639 "Formats for `format-time-string' which are used for time stamps.")
642 ;;; The custom variables
644 (defgroup org nil
645 "Outline-based notes management and organizer."
646 :tag "Org"
647 :group 'outlines
648 :group 'calendar)
650 (defcustom org-mode-hook nil
651 "Mode hook for Org mode, run after the mode was turned on."
652 :group 'org
653 :type 'hook)
655 (defcustom org-load-hook nil
656 "Hook that is run after org.el has been loaded."
657 :group 'org
658 :type 'hook)
660 (defcustom org-log-buffer-setup-hook nil
661 "Hook that is run after an Org log buffer is created."
662 :group 'org
663 :version "24.1"
664 :type 'hook)
666 (defvar org-modules) ; defined below
667 (defvar org-modules-loaded nil
668 "Have the modules been loaded already?")
670 (defun org-load-modules-maybe (&optional force)
671 "Load all extensions listed in `org-modules'."
672 (when (or force (not org-modules-loaded))
673 (dolist (ext org-modules)
674 (condition-case nil (require ext)
675 (error (message "Problems while trying to load feature `%s'" ext))))
676 (setq org-modules-loaded t)))
678 (defun org-set-modules (var value)
679 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
680 (set var value)
681 (when (featurep 'org)
682 (org-load-modules-maybe 'force)
683 (org-element-cache-reset 'all)))
685 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
686 "Modules that should always be loaded together with org.el.
688 If a description starts with <C>, the file is not part of Emacs
689 and loading it will require that you have downloaded and properly
690 installed the Org mode distribution.
692 You can also use this system to load external packages (i.e. neither Org
693 core modules, nor modules from the CONTRIB directory). Just add symbols
694 to the end of the list. If the package is called org-xyz.el, then you need
695 to add the symbol `xyz', and the package must have a call to:
697 (provide \\='org-xyz)
699 For export specific modules, see also `org-export-backends'."
700 :group 'org
701 :set 'org-set-modules
702 :version "24.4"
703 :package-version '(Org . "8.0")
704 :type
705 '(set :greedy t
706 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
707 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
708 (const :tag " crypt: Encryption of subtrees" org-crypt)
709 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
710 (const :tag " docview: Links to doc-view buffers" org-docview)
711 (const :tag " eww: Store link to url of eww" org-eww)
712 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
713 (const :tag " habit: Track your consistency with habits" org-habit)
714 (const :tag " id: Global IDs for identifying entries" org-id)
715 (const :tag " info: Links to Info nodes" org-info)
716 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
717 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
718 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
719 (const :tag " mouse: Additional mouse support" org-mouse)
720 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
721 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
722 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
724 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
725 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
726 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
727 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
728 (const :tag "C collector: Collect properties into tables" org-collector)
729 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
730 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
731 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
732 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
733 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
734 (const :tag "C eval: Include command output as text" org-eval)
735 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
736 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
737 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
738 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
739 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
740 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
741 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
742 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
743 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
744 (const :tag "C man: Support for links to manpages in Org mode" org-man)
745 (const :tag "C mew: Links to Mew folders/messages" org-mew)
746 (const :tag "C mtags: Support for muse-like tags" org-mtags)
747 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
748 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
749 (const :tag "C registry: A registry for Org links" org-registry)
750 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
751 (const :tag "C secretary: Team management with org-mode" org-secretary)
752 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
753 (const :tag "C toc: Table of contents for Org buffer" org-toc)
754 (const :tag "C track: Keep up with Org mode development" org-track)
755 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
756 (const :tag "C vm: Links to VM folders/messages" org-vm)
757 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
758 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
759 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
761 (defvar org-export-registered-backends) ; From ox.el.
762 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
763 (declare-function org-export-backend-name "ox" (backend) t)
764 (defcustom org-export-backends '(ascii html icalendar latex odt)
765 "List of export back-ends that should be always available.
767 If a description starts with <C>, the file is not part of Emacs
768 and loading it will require that you have downloaded and properly
769 installed the Org mode distribution.
771 Unlike to `org-modules', libraries in this list will not be
772 loaded along with Org, but only once the export framework is
773 needed.
775 This variable needs to be set before org.el is loaded. If you
776 need to make a change while Emacs is running, use the customize
777 interface or run the following code, where VAL stands for the new
778 value of the variable, after updating it:
780 (progn
781 (setq org-export-registered-backends
782 (cl-remove-if-not
783 (lambda (backend)
784 (let ((name (org-export-backend-name backend)))
785 (or (memq name val)
786 (catch \\='parentp
787 (dolist (b val)
788 (and (org-export-derived-backend-p b name)
789 (throw \\='parentp t)))))))
790 org-export-registered-backends))
791 (let ((new-list (mapcar #\\='org-export-backend-name
792 org-export-registered-backends)))
793 (dolist (backend val)
794 (cond
795 ((not (load (format \"ox-%s\" backend) t t))
796 (message \"Problems while trying to load export back-end \\=`%s\\='\"
797 backend))
798 ((not (memq backend new-list)) (push backend new-list))))
799 (set-default \\='org-export-backends new-list)))
801 Adding a back-end to this list will also pull the back-end it
802 depends on, if any."
803 :group 'org
804 :group 'org-export
805 :version "26.1"
806 :package-version '(Org . "9.0")
807 :initialize 'custom-initialize-set
808 :set (lambda (var val)
809 (if (not (featurep 'ox)) (set-default var val)
810 ;; Any back-end not required anymore (not present in VAL and not
811 ;; a parent of any back-end in the new value) is removed from the
812 ;; list of registered back-ends.
813 (setq org-export-registered-backends
814 (cl-remove-if-not
815 (lambda (backend)
816 (let ((name (org-export-backend-name backend)))
817 (or (memq name val)
818 (catch 'parentp
819 (dolist (b val)
820 (and (org-export-derived-backend-p b name)
821 (throw 'parentp t)))))))
822 org-export-registered-backends))
823 ;; Now build NEW-LIST of both new back-ends and required
824 ;; parents.
825 (let ((new-list (mapcar #'org-export-backend-name
826 org-export-registered-backends)))
827 (dolist (backend val)
828 (cond
829 ((not (load (format "ox-%s" backend) t t))
830 (message "Problems while trying to load export back-end `%s'"
831 backend))
832 ((not (memq backend new-list)) (push backend new-list))))
833 ;; Set VAR to that list with fixed dependencies.
834 (set-default var new-list))))
835 :type '(set :greedy t
836 (const :tag " ascii Export buffer to ASCII format" ascii)
837 (const :tag " beamer Export buffer to Beamer presentation" beamer)
838 (const :tag " html Export buffer to HTML format" html)
839 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
840 (const :tag " latex Export buffer to LaTeX format" latex)
841 (const :tag " man Export buffer to MAN format" man)
842 (const :tag " md Export buffer to Markdown format" md)
843 (const :tag " odt Export buffer to ODT format" odt)
844 (const :tag " org Export buffer to Org format" org)
845 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
846 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
847 (const :tag "C deck Export buffer to deck.js presentations" deck)
848 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
849 (const :tag "C groff Export buffer to Groff format" groff)
850 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
851 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
852 (const :tag "C s5 Export buffer to s5 presentations" s5)
853 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
855 (eval-after-load 'ox
856 '(dolist (backend org-export-backends)
857 (condition-case nil (require (intern (format "ox-%s" backend)))
858 (error (message "Problems while trying to load export back-end `%s'"
859 backend)))))
861 (defcustom org-support-shift-select nil
862 "Non-nil means make shift-cursor commands select text when possible.
863 \\<org-mode-map>\
865 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
866 start selecting a region, or enlarge regions started in this way.
867 In Org mode, in special contexts, these same keys are used for
868 other purposes, important enough to compete with shift selection.
869 Org tries to balance these needs by supporting `shift-select-mode'
870 outside these special contexts, under control of this variable.
872 The default of this variable is nil, to avoid confusing behavior. Shifted
873 cursor keys will then execute Org commands in the following contexts:
874 - on a headline, changing TODO state (left/right) and priority (up/down)
875 - on a time stamp, changing the time
876 - in a plain list item, changing the bullet type
877 - in a property definition line, switching between allowed values
878 - in the BEGIN line of a clock table (changing the time block).
879 Outside these contexts, the commands will throw an error.
881 When this variable is t and the cursor is not in a special
882 context, Org mode will support shift-selection for making and
883 enlarging regions. To make this more effective, the bullet
884 cycling will no longer happen anywhere in an item line, but only
885 if the cursor is exactly on the bullet.
887 If you set this variable to the symbol `always', then the keys
888 will not be special in headlines, property lines, and item lines,
889 to make shift selection work there as well. If this is what you
890 want, you can use the following alternative commands:
891 `\\[org-todo]' and `\\[org-priority]' \
892 to change TODO state and priority,
893 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
894 can be used to switch TODO sets,
895 `\\[org-ctrl-c-minus]' to cycle item bullet types,
896 and properties can be edited by hand or in column view.
898 However, when the cursor is on a timestamp, shift-cursor commands
899 will still edit the time stamp - this is just too good to give up."
900 :group 'org
901 :type '(choice
902 (const :tag "Never" nil)
903 (const :tag "When outside special context" t)
904 (const :tag "Everywhere except timestamps" always)))
906 (defcustom org-loop-over-headlines-in-active-region nil
907 "Shall some commands act upon headlines in the active region?
909 When set to t, some commands will be performed in all headlines
910 within the active region.
912 When set to `start-level', some commands will be performed in all
913 headlines within the active region, provided that these headlines
914 are of the same level than the first one.
916 When set to a string, those commands will be performed on the
917 matching headlines within the active region. Such string must be
918 a tags/property/todo match as it is used in the agenda tags view.
920 The list of commands is: `org-schedule', `org-deadline',
921 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
922 `org-archive-to-archive-sibling'. The archiving commands skip
923 already archived entries."
924 :type '(choice (const :tag "Don't loop" nil)
925 (const :tag "All headlines in active region" t)
926 (const :tag "In active region, headlines at the same level than the first one" start-level)
927 (string :tag "Tags/Property/Todo matcher"))
928 :version "24.1"
929 :group 'org-todo
930 :group 'org-archive)
932 (defgroup org-startup nil
933 "Options concerning startup of Org mode."
934 :tag "Org Startup"
935 :group 'org)
937 (defcustom org-startup-folded t
938 "Non-nil means entering Org mode will switch to OVERVIEW.
940 This can also be configured on a per-file basis by adding one of
941 the following lines anywhere in the buffer:
943 #+STARTUP: fold (or `overview', this is equivalent)
944 #+STARTUP: nofold (or `showall', this is equivalent)
945 #+STARTUP: content
946 #+STARTUP: showeverything
948 Set `org-agenda-inhibit-startup' to a non-nil value if you want
949 to ignore this option when Org opens agenda files for the first
950 time."
951 :group 'org-startup
952 :type '(choice
953 (const :tag "nofold: show all" nil)
954 (const :tag "fold: overview" t)
955 (const :tag "content: all headlines" content)
956 (const :tag "show everything, even drawers" showeverything)))
958 (defcustom org-startup-truncated t
959 "Non-nil means entering Org mode will set `truncate-lines'.
960 This is useful since some lines containing links can be very long and
961 uninteresting. Also tables look terrible when wrapped.
963 The variable `org-startup-truncated' allows to configure
964 truncation for Org mode different to the other modes that use the
965 variable `truncate-lines' and as a shortcut instead of putting
966 the variable `truncate-lines' into the `org-mode-hook'. If one
967 wants to configure truncation for Org mode not statically but
968 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
969 the variable `truncate-lines' has to be used because in such a
970 case it is too late to set the variable `org-startup-truncated'."
971 :group 'org-startup
972 :type 'boolean)
974 (defcustom org-startup-indented nil
975 "Non-nil means turn on `org-indent-mode' on startup.
976 This can also be configured on a per-file basis by adding one of
977 the following lines anywhere in the buffer:
979 #+STARTUP: indent
980 #+STARTUP: noindent"
981 :group 'org-structure
982 :type '(choice
983 (const :tag "Not" nil)
984 (const :tag "Globally (slow on startup in large files)" t)))
986 (defcustom org-use-sub-superscripts t
987 "Non-nil means interpret \"_\" and \"^\" for display.
989 If you want to control how Org exports those characters, see
990 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
991 used to be an alias for `org-export-with-sub-superscripts' in
992 Org <8.0, it is not anymore.
994 When this option is turned on, you can use TeX-like syntax for
995 sub- and superscripts within the buffer. Several characters after
996 \"_\" or \"^\" will be considered as a single item - so grouping
997 with {} is normally not needed. For example, the following things
998 will be parsed as single sub- or superscripts:
1000 10^24 or 10^tau several digits will be considered 1 item.
1001 10^-12 or 10^-tau a leading sign with digits or a word
1002 x^2-y^3 will be read as x^2 - y^3, because items are
1003 terminated by almost any nonword/nondigit char.
1004 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1006 Still, ambiguity is possible. So when in doubt, use {} to enclose
1007 the sub/superscript. If you set this variable to the symbol `{}',
1008 the braces are *required* in order to trigger interpretations as
1009 sub/superscript. This can be helpful in documents that need \"_\"
1010 frequently in plain text."
1011 :group 'org-startup
1012 :version "24.4"
1013 :package-version '(Org . "8.0")
1014 :type '(choice
1015 (const :tag "Always interpret" t)
1016 (const :tag "Only with braces" {})
1017 (const :tag "Never interpret" nil)))
1019 (defcustom org-startup-with-beamer-mode nil
1020 "Non-nil means turn on `org-beamer-mode' on startup.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1024 #+STARTUP: beamer"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-align-all-tables nil
1030 "Non-nil means align all tables when visiting a file.
1031 This is useful when the column width in tables is forced with <N> cookies
1032 in table fields. Such tables will look correct only after the first re-align.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: align
1036 #+STARTUP: noalign"
1037 :group 'org-startup
1038 :type 'boolean)
1040 (defcustom org-startup-with-inline-images nil
1041 "Non-nil means show inline images when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: inlineimages
1045 #+STARTUP: noinlineimages"
1046 :group 'org-startup
1047 :version "24.1"
1048 :type 'boolean)
1050 (defcustom org-startup-with-latex-preview nil
1051 "Non-nil means preview LaTeX fragments when loading a new Org file.
1053 This can also be configured on a per-file basis by adding one of
1054 the following lines anywhere in the buffer:
1055 #+STARTUP: latexpreview
1056 #+STARTUP: nolatexpreview"
1057 :group 'org-startup
1058 :version "24.4"
1059 :package-version '(Org . "8.0")
1060 :type 'boolean)
1062 (defcustom org-insert-mode-line-in-empty-file nil
1063 "Non-nil means insert the first line setting Org mode in empty files.
1064 When the function `org-mode' is called interactively in an empty file, this
1065 normally means that the file name does not automatically trigger Org mode.
1066 To ensure that the file will always be in Org mode in the future, a
1067 line enforcing Org mode will be inserted into the buffer, if this option
1068 has been set."
1069 :group 'org-startup
1070 :type 'boolean)
1072 (defcustom org-replace-disputed-keys nil
1073 "Non-nil means use alternative key bindings for some keys.
1074 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1075 These keys are also used by other packages like shift-selection-mode'
1076 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1077 If you want to use Org mode together with one of these other modes,
1078 or more generally if you would like to move some Org mode commands to
1079 other keys, set this variable and configure the keys with the variable
1080 `org-disputed-keys'.
1082 This option is only relevant at load-time of Org mode, and must be set
1083 *before* org.el is loaded. Changing it requires a restart of Emacs to
1084 become effective."
1085 :group 'org-startup
1086 :type 'boolean)
1088 (defcustom org-use-extra-keys nil
1089 "Non-nil means use extra key sequence definitions for certain commands.
1090 This happens automatically if `window-system' is nil. This
1091 variable lets you do the same manually. You must set it before
1092 loading Org."
1093 :group 'org-startup
1094 :type 'boolean)
1096 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1098 (defcustom org-disputed-keys
1099 '(([(shift up)] . [(meta p)])
1100 ([(shift down)] . [(meta n)])
1101 ([(shift left)] . [(meta -)])
1102 ([(shift right)] . [(meta +)])
1103 ([(control shift right)] . [(meta shift +)])
1104 ([(control shift left)] . [(meta shift -)]))
1105 "Keys for which Org mode and other modes compete.
1106 This is an alist, cars are the default keys, second element specifies
1107 the alternative to use when `org-replace-disputed-keys' is t.
1109 Keys can be specified in any syntax supported by `define-key'.
1110 The value of this option takes effect only at Org mode startup,
1111 therefore you'll have to restart Emacs to apply it after changing."
1112 :group 'org-startup
1113 :type 'alist)
1115 (defun org-key (key)
1116 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1117 Or return the original if not disputed."
1118 (when org-replace-disputed-keys
1119 (let* ((nkey (key-description key))
1120 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1121 org-disputed-keys)))
1122 (setq key (if x (cdr x) key))))
1123 key)
1125 (defun org-defkey (keymap key def)
1126 "Define a key, possibly translated, as returned by `org-key'."
1127 (define-key keymap (org-key key) def))
1129 (defcustom org-ellipsis nil
1130 "The ellipsis to use in the Org mode outline.
1132 When nil, just use the standard three dots. When a non-empty string,
1133 use that string instead.
1135 The change affects only Org mode (which will then use its own display table).
1136 Changing this requires executing `\\[org-mode]' in a buffer to become
1137 effective."
1138 :group 'org-startup
1139 :type '(choice (const :tag "Default" nil)
1140 (string :tag "String" :value "...#"))
1141 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1143 (defvar org-display-table nil
1144 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1146 (defgroup org-keywords nil
1147 "Keywords in Org mode."
1148 :tag "Org Keywords"
1149 :group 'org)
1151 (defcustom org-closed-keep-when-no-todo nil
1152 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1153 :group 'org-todo
1154 :group 'org-keywords
1155 :version "24.4"
1156 :package-version '(Org . "8.0")
1157 :type 'boolean)
1159 (defgroup org-structure nil
1160 "Options concerning the general structure of Org files."
1161 :tag "Org Structure"
1162 :group 'org)
1164 (defgroup org-reveal-location nil
1165 "Options about how to make context of a location visible."
1166 :tag "Org Reveal Location"
1167 :group 'org-structure)
1169 (defcustom org-show-context-detail '((agenda . local)
1170 (bookmark-jump . lineage)
1171 (isearch . lineage)
1172 (default . ancestors))
1173 "Alist between context and visibility span when revealing a location.
1175 \\<org-mode-map>Some actions may move point into invisible
1176 locations. As a consequence, Org always expose a neighborhood
1177 around point. How much is shown depends on the initial action,
1178 or context. Valid contexts are
1180 agenda when exposing an entry from the agenda
1181 org-goto when using the command `org-goto' (`\\[org-goto]')
1182 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1183 tags-tree when constructing a sparse tree based on tags matches
1184 link-search when exposing search matches associated with a link
1185 mark-goto when exposing the jump goal of a mark
1186 bookmark-jump when exposing a bookmark location
1187 isearch when exiting from an incremental search
1188 default default for all contexts not set explicitly
1190 Allowed visibility spans are
1192 minimal show current headline; if point is not on headline,
1193 also show entry
1195 local show current headline, entry and next headline
1197 ancestors show current headline and its direct ancestors; if
1198 point is not on headline, also show entry
1200 lineage show current headline, its direct ancestors and all
1201 their children; if point is not on headline, also show
1202 entry and first child
1204 tree show current headline, its direct ancestors and all
1205 their children; if point is not on headline, also show
1206 entry and all children
1208 canonical show current headline, its direct ancestors along with
1209 their entries and children; if point is not located on
1210 the headline, also show current entry and all children
1212 As special cases, a nil or t value means show all contexts in
1213 `minimal' or `canonical' view, respectively.
1215 Some views can make displayed information very compact, but also
1216 make it harder to edit the location of the match. In such
1217 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1218 more context."
1219 :group 'org-reveal-location
1220 :version "26.1"
1221 :package-version '(Org . "9.0")
1222 :type '(choice
1223 (const :tag "Canonical" t)
1224 (const :tag "Minimal" nil)
1225 (repeat :greedy t :tag "Individual contexts"
1226 (cons
1227 (choice :tag "Context"
1228 (const agenda)
1229 (const org-goto)
1230 (const occur-tree)
1231 (const tags-tree)
1232 (const link-search)
1233 (const mark-goto)
1234 (const bookmark-jump)
1235 (const isearch)
1236 (const default))
1237 (choice :tag "Detail level"
1238 (const minimal)
1239 (const local)
1240 (const ancestors)
1241 (const lineage)
1242 (const tree)
1243 (const canonical))))))
1245 (defcustom org-indirect-buffer-display 'other-window
1246 "How should indirect tree buffers be displayed?
1248 This applies to indirect buffers created with the commands
1249 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1251 Valid values are:
1252 current-window Display in the current window
1253 other-window Just display in another window.
1254 dedicated-frame Create one new frame, and re-use it each time.
1255 new-frame Make a new frame each time. Note that in this case
1256 previously-made indirect buffers are kept, and you need to
1257 kill these buffers yourself."
1258 :group 'org-structure
1259 :group 'org-agenda-windows
1260 :type '(choice
1261 (const :tag "In current window" current-window)
1262 (const :tag "In current frame, other window" other-window)
1263 (const :tag "Each time a new frame" new-frame)
1264 (const :tag "One dedicated frame" dedicated-frame)))
1266 (defcustom org-use-speed-commands nil
1267 "Non-nil means activate single letter commands at beginning of a headline.
1268 This may also be a function to test for appropriate locations where speed
1269 commands should be active.
1271 For example, to activate speed commands when the point is on any
1272 star at the beginning of the headline, you can do this:
1274 (setq org-use-speed-commands
1275 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1276 :group 'org-structure
1277 :type '(choice
1278 (const :tag "Never" nil)
1279 (const :tag "At beginning of headline stars" t)
1280 (function)))
1282 (defcustom org-speed-commands-user nil
1283 "Alist of additional speed commands.
1284 This list will be checked before `org-speed-commands-default'
1285 when the variable `org-use-speed-commands' is non-nil
1286 and when the cursor is at the beginning of a headline.
1287 The car if each entry is a string with a single letter, which must
1288 be assigned to `self-insert-command' in the global map.
1289 The cdr is either a command to be called interactively, a function
1290 to be called, or a form to be evaluated.
1291 An entry that is just a list with a single string will be interpreted
1292 as a descriptive headline that will be added when listing the speed
1293 commands in the Help buffer using the `?' speed command."
1294 :group 'org-structure
1295 :type '(repeat :value ("k" . ignore)
1296 (choice :value ("k" . ignore)
1297 (list :tag "Descriptive Headline" (string :tag "Headline"))
1298 (cons :tag "Letter and Command"
1299 (string :tag "Command letter")
1300 (choice
1301 (function)
1302 (sexp))))))
1304 (defcustom org-bookmark-names-plist
1305 '(:last-capture "org-capture-last-stored"
1306 :last-refile "org-refile-last-stored"
1307 :last-capture-marker "org-capture-last-stored-marker")
1308 "Names for bookmarks automatically set by some Org commands.
1309 This can provide strings as names for a number of bookmarks Org sets
1310 automatically. The following keys are currently implemented:
1311 :last-capture
1312 :last-capture-marker
1313 :last-refile
1314 When a key does not show up in the property list, the corresponding bookmark
1315 is not set."
1316 :group 'org-structure
1317 :type 'plist)
1319 (defgroup org-cycle nil
1320 "Options concerning visibility cycling in Org mode."
1321 :tag "Org Cycle"
1322 :group 'org-structure)
1324 (defcustom org-cycle-skip-children-state-if-no-children t
1325 "Non-nil means skip CHILDREN state in entries that don't have any."
1326 :group 'org-cycle
1327 :type 'boolean)
1329 (defcustom org-cycle-max-level nil
1330 "Maximum level which should still be subject to visibility cycling.
1331 Levels higher than this will, for cycling, be treated as text, not a headline.
1332 When `org-odd-levels-only' is set, a value of N in this variable actually
1333 means 2N-1 stars as the limiting headline.
1334 When nil, cycle all levels.
1335 Note that the limiting level of cycling is also influenced by
1336 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1337 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1338 than its value."
1339 :group 'org-cycle
1340 :type '(choice
1341 (const :tag "No limit" nil)
1342 (integer :tag "Maximum level")))
1344 (defcustom org-hide-block-startup nil
1345 "Non-nil means entering Org mode will fold all blocks.
1346 This can also be set in on a per-file basis with
1348 #+STARTUP: hideblocks
1349 #+STARTUP: showblocks"
1350 :group 'org-startup
1351 :group 'org-cycle
1352 :type 'boolean)
1354 (defcustom org-cycle-global-at-bob nil
1355 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1357 This makes it possible to do global cycling without having to use `S-TAB'
1358 or `\\[universal-argument] TAB'. For this special case to work, the first \
1359 line of the buffer
1360 must not be a headline -- it may be empty or some other text.
1362 When used in this way, `org-cycle-hook' is disabled temporarily to make
1363 sure the cursor stays at the beginning of the buffer.
1365 When this option is nil, don't do anything special at the beginning of
1366 the buffer."
1367 :group 'org-cycle
1368 :type 'boolean)
1370 (defcustom org-cycle-level-after-item/entry-creation t
1371 "Non-nil means cycle entry level or item indentation in new empty entries.
1373 When the cursor is at the end of an empty headline, i.e., with only stars
1374 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1375 and then all possible ancestor states, before returning to the original state.
1376 This makes data entry extremely fast: M-RET to create a new headline,
1377 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1379 When the cursor is at the end of an empty plain list item, one TAB will
1380 make it a subitem, two or more tabs will back up to make this an item
1381 higher up in the item hierarchy."
1382 :group 'org-cycle
1383 :type 'boolean)
1385 (defcustom org-cycle-emulate-tab t
1386 "Where should `org-cycle' emulate TAB.
1387 nil Never
1388 white Only in completely white lines
1389 whitestart Only at the beginning of lines, before the first non-white char
1390 t Everywhere except in headlines
1391 exc-hl-bol Everywhere except at the start of a headline
1392 If TAB is used in a place where it does not emulate TAB, the current subtree
1393 visibility is cycled."
1394 :group 'org-cycle
1395 :type '(choice (const :tag "Never" nil)
1396 (const :tag "Only in completely white lines" white)
1397 (const :tag "Before first char in a line" whitestart)
1398 (const :tag "Everywhere except in headlines" t)
1399 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1401 (defcustom org-cycle-separator-lines 2
1402 "Number of empty lines needed to keep an empty line between collapsed trees.
1403 If you leave an empty line between the end of a subtree and the following
1404 headline, this empty line is hidden when the subtree is folded.
1405 Org mode will leave (exactly) one empty line visible if the number of
1406 empty lines is equal or larger to the number given in this variable.
1407 So the default 2 means at least 2 empty lines after the end of a subtree
1408 are needed to produce free space between a collapsed subtree and the
1409 following headline.
1411 If the number is negative, and the number of empty lines is at least -N,
1412 all empty lines are shown.
1414 Special case: when 0, never leave empty lines in collapsed view."
1415 :group 'org-cycle
1416 :type 'integer)
1417 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1419 (defcustom org-pre-cycle-hook nil
1420 "Hook that is run before visibility cycling is happening.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that will be set right after running this hook. The
1423 argument is a symbol. Before a global state change, it can have the values
1424 `overview', `content', or `all'. Before a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook)
1429 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1430 org-cycle-hide-drawers
1431 org-cycle-show-empty-lines
1432 org-optimize-window-after-visibility-change)
1433 "Hook that is run after `org-cycle' has changed the buffer visibility.
1434 The function(s) in this hook must accept a single argument which indicates
1435 the new state that was set by the most recent `org-cycle' command. The
1436 argument is a symbol. After a global state change, it can have the values
1437 `overview', `contents', or `all'. After a local state change, it can have
1438 the values `folded', `children', or `subtree'."
1439 :group 'org-cycle
1440 :type 'hook
1441 :version "26.1"
1442 :package-version '(Org . "8.3"))
1444 (defgroup org-edit-structure nil
1445 "Options concerning structure editing in Org mode."
1446 :tag "Org Edit Structure"
1447 :group 'org-structure)
1449 (defcustom org-odd-levels-only nil
1450 "Non-nil means skip even levels and only use odd levels for the outline.
1451 This has the effect that two stars are being added/taken away in
1452 promotion/demotion commands. It also influences how levels are
1453 handled by the exporters.
1454 Changing it requires restart of `font-lock-mode' to become effective
1455 for fontification also in regions already fontified.
1456 You may also set this on a per-file basis by adding one of the following
1457 lines to the buffer:
1459 #+STARTUP: odd
1460 #+STARTUP: oddeven"
1461 :group 'org-edit-structure
1462 :group 'org-appearance
1463 :type 'boolean)
1465 (defcustom org-adapt-indentation t
1466 "Non-nil means adapt indentation to outline node level.
1468 When this variable is set, Org assumes that you write outlines by
1469 indenting text in each node to align with the headline (after the
1470 stars). The following issues are influenced by this variable:
1472 - The indentation is increased by one space in a demotion
1473 command, and decreased by one in a promotion command. However,
1474 in the latter case, if shifting some line in the entry body
1475 would alter document structure (e.g., insert a new headline),
1476 indentation is not changed at all.
1478 - Property drawers and planning information is inserted indented
1479 when this variable is set. When nil, they will not be indented.
1481 - TAB indents a line relative to current level. The lines below
1482 a headline will be indented when this variable is set.
1484 Note that this is all about true indentation, by adding and
1485 removing space characters. See also `org-indent.el' which does
1486 level-dependent indentation in a virtual way, i.e. at display
1487 time in Emacs."
1488 :group 'org-edit-structure
1489 :type 'boolean)
1491 (defcustom org-special-ctrl-a/e nil
1492 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1494 When t, `C-a' will bring back the cursor to the beginning of the
1495 headline text, i.e. after the stars and after a possible TODO
1496 keyword. In an item, this will be the position after bullet and
1497 check-box, if any. When the cursor is already at that position,
1498 another `C-a' will bring it to the beginning of the line.
1500 `C-e' will jump to the end of the headline, ignoring the presence
1501 of tags in the headline. A second `C-e' will then jump to the
1502 true end of the line, after any tags. This also means that, when
1503 this variable is non-nil, `C-e' also will never jump beyond the
1504 end of the heading of a folded section, i.e. not after the
1505 ellipses.
1507 When set to the symbol `reversed', the first `C-a' or `C-e' works
1508 normally, going to the true line boundary first. Only a directly
1509 following, identical keypress will bring the cursor to the
1510 special positions.
1512 This may also be a cons cell where the behavior for `C-a' and
1513 `C-e' is set separately."
1514 :group 'org-edit-structure
1515 :type '(choice
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet and before tags first" t)
1518 (const :tag "reversed: true line boundary first" reversed)
1519 (cons :tag "Set C-a and C-e separately"
1520 (choice :tag "Special C-a"
1521 (const :tag "off" nil)
1522 (const :tag "on: after stars/bullet first" t)
1523 (const :tag "reversed: before stars/bullet first" reversed))
1524 (choice :tag "Special C-e"
1525 (const :tag "off" nil)
1526 (const :tag "on: before tags first" t)
1527 (const :tag "reversed: after tags first" reversed)))))
1528 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1530 (defcustom org-special-ctrl-k nil
1531 "Non-nil means `C-k' will behave specially in headlines.
1532 When nil, `C-k' will call the default `kill-line' command.
1533 When t, the following will happen while the cursor is in the headline:
1535 - When the cursor is at the beginning of a headline, kill the entire
1536 line and possible the folded subtree below the line.
1537 - When in the middle of the headline text, kill the headline up to the tags.
1538 - When after the headline text, kill the tags."
1539 :group 'org-edit-structure
1540 :type 'boolean)
1542 (defcustom org-ctrl-k-protect-subtree nil
1543 "Non-nil means, do not delete a hidden subtree with C-k.
1544 When set to the symbol `error', simply throw an error when C-k is
1545 used to kill (part-of) a headline that has hidden text behind it.
1546 Any other non-nil value will result in a query to the user, if it is
1547 OK to kill that hidden subtree. When nil, kill without remorse."
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not protect hidden subtrees" nil)
1552 (const :tag "Protect hidden subtrees with a security query" t)
1553 (const :tag "Never kill a hidden subtree with C-k" error)))
1555 (defcustom org-special-ctrl-o t
1556 "Non-nil means, make `C-o' insert a row in tables."
1557 :group 'org-edit-structure
1558 :type 'boolean)
1560 (defcustom org-catch-invisible-edits nil
1561 "Check if in invisible region before inserting or deleting a character.
1562 Valid values are:
1564 nil Do not check, so just do invisible edits.
1565 error Throw an error and do nothing.
1566 show Make point visible, and do the requested edit.
1567 show-and-error Make point visible, then throw an error and abort the edit.
1568 smart Make point visible, and do insertion/deletion if it is
1569 adjacent to visible text and the change feels predictable.
1570 Never delete a previously invisible character or add in the
1571 middle or right after an invisible region. Basically, this
1572 allows insertion and backward-delete right before ellipses.
1573 FIXME: maybe in this case we should not even show?"
1574 :group 'org-edit-structure
1575 :version "24.1"
1576 :type '(choice
1577 (const :tag "Do not check" nil)
1578 (const :tag "Throw error when trying to edit" error)
1579 (const :tag "Unhide, but do not do the edit" show-and-error)
1580 (const :tag "Show invisible part and do the edit" show)
1581 (const :tag "Be smart and do the right thing" smart)))
1583 (defcustom org-yank-folded-subtrees t
1584 "Non-nil means when yanking subtrees, fold them.
1585 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1586 it starts with a heading and all other headings in it are either children
1587 or siblings, then fold all the subtrees. However, do this only if no
1588 text after the yank would be swallowed into a folded tree by this action."
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defcustom org-yank-adjusted-subtrees nil
1593 "Non-nil means when yanking subtrees, adjust the level.
1594 With this setting, `org-paste-subtree' is used to insert the subtree, see
1595 this function for details."
1596 :group 'org-edit-structure
1597 :type 'boolean)
1599 (defcustom org-M-RET-may-split-line '((default . t))
1600 "Non-nil means M-RET will split the line at the cursor position.
1601 When nil, it will go to the end of the line before making a
1602 new line.
1603 You may also set this option in a different way for different
1604 contexts. Valid contexts are:
1606 headline when creating a new headline
1607 item when creating a new item
1608 table in a table field
1609 default the value to be used for all contexts not explicitly
1610 customized"
1611 :group 'org-structure
1612 :group 'org-table
1613 :type '(choice
1614 (const :tag "Always" t)
1615 (const :tag "Never" nil)
1616 (repeat :greedy t :tag "Individual contexts"
1617 (cons
1618 (choice :tag "Context"
1619 (const headline)
1620 (const item)
1621 (const table)
1622 (const default))
1623 (boolean)))))
1626 (defcustom org-insert-heading-respect-content nil
1627 "Non-nil means insert new headings after the current subtree.
1628 \\<org-mode-map>
1629 When nil, the new heading is created directly after the current line.
1630 The commands `\\[org-insert-heading-respect-content]' and \
1631 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1632 for the duration of the command."
1633 :group 'org-structure
1634 :type 'boolean)
1636 (defcustom org-blank-before-new-entry '((heading . auto)
1637 (plain-list-item . auto))
1638 "Should `org-insert-heading' leave a blank line before new heading/item?
1639 The value is an alist, with `heading' and `plain-list-item' as CAR,
1640 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1641 which case Org will look at the surrounding headings/items and try to
1642 make an intelligent decision whether to insert a blank line or not."
1643 :group 'org-edit-structure
1644 :type '(list
1645 (cons (const heading)
1646 (choice (const :tag "Never" nil)
1647 (const :tag "Always" t)
1648 (const :tag "Auto" auto)))
1649 (cons (const plain-list-item)
1650 (choice (const :tag "Never" nil)
1651 (const :tag "Always" t)
1652 (const :tag "Auto" auto)))))
1654 (defcustom org-insert-heading-hook nil
1655 "Hook being run after inserting a new heading."
1656 :group 'org-edit-structure
1657 :type 'hook)
1659 (defcustom org-enable-fixed-width-editor t
1660 "Non-nil means lines starting with \":\" are treated as fixed-width.
1661 This currently only means they are never auto-wrapped.
1662 When nil, such lines will be treated like ordinary lines."
1663 :group 'org-edit-structure
1664 :type 'boolean)
1666 (defcustom org-goto-auto-isearch t
1667 "Non-nil means typing characters in `org-goto' starts incremental search.
1668 When nil, you can use these keybindings to navigate the buffer:
1670 q Quit the org-goto interface
1671 n Go to the next visible heading
1672 p Go to the previous visible heading
1673 f Go one heading forward on same level
1674 b Go one heading backward on same level
1675 u Go one heading up"
1676 :group 'org-edit-structure
1677 :type 'boolean)
1679 (defgroup org-sparse-trees nil
1680 "Options concerning sparse trees in Org mode."
1681 :tag "Org Sparse Trees"
1682 :group 'org-structure)
1684 (defcustom org-highlight-sparse-tree-matches t
1685 "Non-nil means highlight all matches that define a sparse tree.
1686 The highlights will automatically disappear the next time the buffer is
1687 changed by an edit command."
1688 :group 'org-sparse-trees
1689 :type 'boolean)
1691 (defcustom org-remove-highlights-with-change t
1692 "Non-nil means any change to the buffer will remove temporary highlights.
1693 \\<org-mode-map>\
1694 Such highlights are created by `org-occur' and `org-clock-display'.
1695 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1696 to get rid of the highlights.
1697 The highlights created by `org-toggle-latex-fragment' always need
1698 `\\[org-toggle-latex-fragment]' to be removed."
1699 :group 'org-sparse-trees
1700 :group 'org-time
1701 :type 'boolean)
1703 (defcustom org-occur-case-fold-search t
1704 "Non-nil means `org-occur' should be case-insensitive.
1705 If set to `smart' the search will be case-insensitive only if it
1706 doesn't specify any upper case character."
1707 :group 'org-sparse-trees
1708 :version "26.1"
1709 :type '(choice
1710 (const :tag "Case-sensitive" nil)
1711 (const :tag "Case-insensitive" t)
1712 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1714 (defcustom org-occur-hook '(org-first-headline-recenter)
1715 "Hook that is run after `org-occur' has constructed a sparse tree.
1716 This can be used to recenter the window to show as much of the structure
1717 as possible."
1718 :group 'org-sparse-trees
1719 :type 'hook)
1721 (defgroup org-imenu-and-speedbar nil
1722 "Options concerning imenu and speedbar in Org mode."
1723 :tag "Org Imenu and Speedbar"
1724 :group 'org-structure)
1726 (defcustom org-imenu-depth 2
1727 "The maximum level for Imenu access to Org headlines.
1728 This also applied for speedbar access."
1729 :group 'org-imenu-and-speedbar
1730 :type 'integer)
1732 (defgroup org-table nil
1733 "Options concerning tables in Org mode."
1734 :tag "Org Table"
1735 :group 'org)
1737 (defcustom org-self-insert-cluster-for-undo nil
1738 "Non-nil means cluster self-insert commands for undo when possible.
1739 If this is set, then, like in the Emacs command loop, 20 consecutive
1740 characters will be undone together.
1741 This is configurable, because there is some impact on typing performance."
1742 :group 'org-table
1743 :type 'boolean)
1745 (defcustom org-table-tab-recognizes-table.el t
1746 "Non-nil means TAB will automatically notice a table.el table.
1747 When it sees such a table, it moves point into it and - if necessary -
1748 calls `table-recognize-table'."
1749 :group 'org-table-editing
1750 :type 'boolean)
1752 (defgroup org-link nil
1753 "Options concerning links in Org mode."
1754 :tag "Org Link"
1755 :group 'org)
1757 (defvar-local org-link-abbrev-alist-local nil
1758 "Buffer-local version of `org-link-abbrev-alist', which see.
1759 The value of this is taken from the #+LINK lines.")
1761 (defcustom org-link-parameters
1762 '(("doi" :follow org--open-doi-link)
1763 ("elisp" :follow org--open-elisp-link)
1764 ("file" :complete org-file-complete-link)
1765 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1766 ("help" :follow org--open-help-link)
1767 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1768 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1769 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1770 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1771 ("shell" :follow org--open-shell-link))
1772 "An alist of properties that defines all the links in Org mode.
1773 The key in each association is a string of the link type.
1774 Subsequent optional elements make up a p-list of link properties.
1776 :follow - A function that takes the link path as an argument.
1778 :export - A function that takes the link path, description and
1779 export-backend as arguments.
1781 :store - A function responsible for storing the link. See the
1782 function `org-store-link-functions'.
1784 :complete - A function that inserts a link with completion. The
1785 function takes one optional prefix arg.
1787 :face - A face for the link, or a function that returns a face.
1788 The function takes one argument which is the link path. The
1789 default face is `org-link'.
1791 :mouse-face - The mouse-face. The default is `highlight'.
1793 :display - `full' will not fold the link in descriptive
1794 display. Default is `org-link'.
1796 :help-echo - A string or function that takes (window object position)
1797 as arguments and returns a string.
1799 :keymap - A keymap that is active on the link. The default is
1800 `org-mouse-map'.
1802 :htmlize-link - A function for the htmlize-link. Defaults
1803 to (list :uri \"type:path\")
1805 :activate-func - A function to run at the end of font-lock
1806 activation. The function must accept (link-start link-end path bracketp)
1807 as arguments."
1808 :group 'org-link
1809 :type '(alist :tag "Link display parameters"
1810 :value-type plist)
1811 :version "26.1"
1812 :package-version '(Org . "9.1"))
1814 (defun org-link-get-parameter (type key)
1815 "Get TYPE link property for KEY.
1816 TYPE is a string and KEY is a plist keyword."
1817 (plist-get
1818 (cdr (assoc type org-link-parameters))
1819 key))
1821 (defun org-link-set-parameters (type &rest parameters)
1822 "Set link TYPE properties to PARAMETERS.
1823 PARAMETERS should be :key val pairs."
1824 (let ((data (assoc type org-link-parameters)))
1825 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1826 (push (cons type parameters) org-link-parameters)
1827 (org-make-link-regexps)
1828 (org-element-update-syntax))))
1830 (defun org-link-types ()
1831 "Return a list of known link types."
1832 (mapcar #'car org-link-parameters))
1834 (defcustom org-link-abbrev-alist nil
1835 "Alist of link abbreviations.
1836 The car of each element is a string, to be replaced at the start of a link.
1837 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1838 links in Org buffers can have an optional tag after a double colon, e.g.,
1840 [[linkkey:tag][description]]
1842 The `linkkey' must be a single word, starting with a letter, followed
1843 by letters, numbers, `-' or `_'.
1845 If REPLACE is a string, the tag will simply be appended to create the link.
1846 If the string contains \"%s\", the tag will be inserted there. If the string
1847 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1848 at that point (see the function `url-hexify-string'). If the string contains
1849 the specifier \"%(my-function)\", then the custom function `my-function' will
1850 be invoked: this function takes the tag as its only argument and must return
1851 a string.
1853 REPLACE may also be a function that will be called with the tag as the
1854 only argument to create the link, which should be returned as a string.
1856 See the manual for examples."
1857 :group 'org-link
1858 :type '(repeat
1859 (cons
1860 (string :tag "Protocol")
1861 (choice
1862 (string :tag "Format")
1863 (function)))))
1865 (defcustom org-descriptive-links t
1866 "Non-nil means Org will display descriptive links.
1867 E.g. [[http://orgmode.org][Org website]] will be displayed as
1868 \"Org Website\", hiding the link itself and just displaying its
1869 description. When set to nil, Org will display the full links
1870 literally.
1872 You can interactively set the value of this variable by calling
1873 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1874 :group 'org-link
1875 :type 'boolean)
1877 (defcustom org-link-file-path-type 'adaptive
1878 "How the path name in file links should be stored.
1879 Valid values are:
1881 relative Relative to the current directory, i.e. the directory of the file
1882 into which the link is being inserted.
1883 absolute Absolute path, if possible with ~ for home directory.
1884 noabbrev Absolute path, no abbreviation of home directory.
1885 adaptive Use relative path for files in the current directory and sub-
1886 directories of it. For other files, use an absolute path."
1887 :group 'org-link
1888 :type '(choice
1889 (const relative)
1890 (const absolute)
1891 (const noabbrev)
1892 (const adaptive)))
1894 (defvaralias 'org-activate-links 'org-highlight-links)
1895 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1896 "Types of links that should be highlighted in Org files.
1898 This is a list of symbols, each one of them leading to the
1899 highlighting of a certain link type.
1901 You can still open links that are not highlighted.
1903 In principle, it does not hurt to turn on highlighting for all
1904 link types. There may be a small gain when turning off unused
1905 link types. The types are:
1907 bracket The recommended [[link][description]] or [[link]] links with hiding.
1908 angle Links in angular brackets that may contain whitespace like
1909 <bbdb:Carsten Dominik>.
1910 plain Plain links in normal text, no whitespace, like http://google.com.
1911 radio Text that is matched by a radio target, see manual for details.
1912 tag Tag settings in a headline (link to tag search).
1913 date Time stamps (link to calendar).
1914 footnote Footnote labels.
1916 If you set this variable during an Emacs session, use `org-mode-restart'
1917 in the Org buffer so that the change takes effect."
1918 :group 'org-link
1919 :group 'org-appearance
1920 :type '(set :greedy t
1921 (const :tag "Double bracket links" bracket)
1922 (const :tag "Angular bracket links" angle)
1923 (const :tag "Plain text links" plain)
1924 (const :tag "Radio target matches" radio)
1925 (const :tag "Tags" tag)
1926 (const :tag "Timestamps" date)
1927 (const :tag "Footnotes" footnote)))
1929 (defcustom org-make-link-description-function nil
1930 "Function to use for generating link descriptions from links.
1931 This function must take two parameters: the first one is the
1932 link, the second one is the description generated by
1933 `org-insert-link'. The function should return the description to
1934 use."
1935 :group 'org-link
1936 :type '(choice (const nil) (function)))
1938 (defgroup org-link-store nil
1939 "Options concerning storing links in Org mode."
1940 :tag "Org Store Link"
1941 :group 'org-link)
1943 (defcustom org-url-hexify-p t
1944 "When non-nil, hexify URL when creating a link."
1945 :type 'boolean
1946 :version "24.3"
1947 :group 'org-link-store)
1949 (defcustom org-email-link-description-format "Email %c: %.30s"
1950 "Format of the description part of a link to an email or usenet message.
1951 The following %-escapes will be replaced by corresponding information:
1953 %F full \"From\" field
1954 %f name, taken from \"From\" field, address if no name
1955 %T full \"To\" field
1956 %t first name in \"To\" field, address if no name
1957 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1958 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1959 %s subject
1960 %d date
1961 %m message-id.
1963 You may use normal field width specification between the % and the letter.
1964 This is for example useful to limit the length of the subject.
1966 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1967 :group 'org-link-store
1968 :type 'string)
1970 (defcustom org-from-is-user-regexp
1971 (let (r1 r2)
1972 (when (and user-mail-address (not (string= user-mail-address "")))
1973 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1974 (when (and user-full-name (not (string= user-full-name "")))
1975 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1976 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1977 "Regexp matched against the \"From:\" header of an email or usenet message.
1978 It should match if the message is from the user him/herself."
1979 :group 'org-link-store
1980 :type 'regexp)
1982 (defcustom org-context-in-file-links t
1983 "Non-nil means file links from `org-store-link' contain context.
1984 \\<org-mode-map>
1985 A search string will be added to the file name with :: as separator
1986 and used to find the context when the link is activated by the command
1987 `org-open-at-point'. When this option is t, the entire active region
1988 will be placed in the search string of the file link. If set to a
1989 positive integer, only the first n lines of context will be stored.
1991 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1992 \\[org-store-link]')
1993 negates this setting for the duration of the command."
1994 :group 'org-link-store
1995 :type '(choice boolean integer))
1997 (defcustom org-keep-stored-link-after-insertion nil
1998 "Non-nil means keep link in list for entire session.
1999 \\<org-mode-map>
2000 The command `org-store-link' adds a link pointing to the current
2001 location to an internal list. These links accumulate during a session.
2002 The command `org-insert-link' can be used to insert links into any
2003 Org file (offering completion for all stored links).
2005 When this option is nil, every link which has been inserted once using
2006 `\\[org-insert-link]' will be removed from the list, to make completing the \
2007 unused
2008 links more efficient."
2009 :group 'org-link-store
2010 :type 'boolean)
2012 (defgroup org-link-follow nil
2013 "Options concerning following links in Org mode."
2014 :tag "Org Follow Link"
2015 :group 'org-link)
2017 (defcustom org-link-translation-function nil
2018 "Function to translate links with different syntax to Org syntax.
2019 This can be used to translate links created for example by the Planner
2020 or emacs-wiki packages to Org syntax.
2021 The function must accept two parameters, a TYPE containing the link
2022 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2023 which is everything after the link protocol. It should return a cons
2024 with possibly modified values of type and path.
2025 Org contains a function for this, so if you set this variable to
2026 `org-translate-link-from-planner', you should be able follow many
2027 links created by planner."
2028 :group 'org-link-follow
2029 :type '(choice (const nil) (function)))
2031 (defcustom org-follow-link-hook nil
2032 "Hook that is run after a link has been followed."
2033 :group 'org-link-follow
2034 :type 'hook)
2036 (defcustom org-tab-follows-link nil
2037 "Non-nil means on links TAB will follow the link.
2038 Needs to be set before org.el is loaded.
2039 This really should not be used, it does not make sense, and the
2040 implementation is bad."
2041 :group 'org-link-follow
2042 :type 'boolean)
2044 (defcustom org-return-follows-link nil
2045 "Non-nil means on links RET will follow the link.
2046 In tables, the special behavior of RET has precedence."
2047 :group 'org-link-follow
2048 :type 'boolean)
2050 (defcustom org-mouse-1-follows-link
2051 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2052 "Non-nil means mouse-1 on a link will follow the link.
2053 A longer mouse click will still set point. Needs to be set
2054 before org.el is loaded."
2055 :group 'org-link-follow
2056 :version "26.1"
2057 :package-version '(Org . "8.3")
2058 :type '(choice
2059 (const :tag "A double click follows the link" double)
2060 (const :tag "Unconditionally follow the link with mouse-1" t)
2061 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2063 (defcustom org-mark-ring-length 4
2064 "Number of different positions to be recorded in the ring.
2065 Changing this requires a restart of Emacs to work correctly."
2066 :group 'org-link-follow
2067 :type 'integer)
2069 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2070 "Non-nil means internal fuzzy links can only match headlines.
2072 When nil, the a fuzzy link may point to a target or a named
2073 construct in the document. When set to the special value
2074 `query-to-create', offer to create a new headline when none
2075 matched.
2077 Spaces and statistics cookies are ignored during heading searches."
2078 :group 'org-link-follow
2079 :version "24.1"
2080 :type '(choice
2081 (const :tag "Use fuzzy text search" nil)
2082 (const :tag "Match only exact headline" t)
2083 (const :tag "Match exact headline or query to create it"
2084 query-to-create))
2085 :safe #'symbolp)
2087 (defcustom org-link-frame-setup
2088 '((vm . vm-visit-folder-other-frame)
2089 (vm-imap . vm-visit-imap-folder-other-frame)
2090 (gnus . org-gnus-no-new-news)
2091 (file . find-file-other-window)
2092 (wl . wl-other-frame))
2093 "Setup the frame configuration for following links.
2094 When following a link with Emacs, it may often be useful to display
2095 this link in another window or frame. This variable can be used to
2096 set this up for the different types of links.
2097 For VM, use any of
2098 `vm-visit-folder'
2099 `vm-visit-folder-other-window'
2100 `vm-visit-folder-other-frame'
2101 For Gnus, use any of
2102 `gnus'
2103 `gnus-other-frame'
2104 `org-gnus-no-new-news'
2105 For FILE, use any of
2106 `find-file'
2107 `find-file-other-window'
2108 `find-file-other-frame'
2109 For Wanderlust use any of
2110 `wl'
2111 `wl-other-frame'
2112 For the calendar, use the variable `calendar-setup'.
2113 For BBDB, it is currently only possible to display the matches in
2114 another window."
2115 :group 'org-link-follow
2116 :type '(list
2117 (cons (const vm)
2118 (choice
2119 (const vm-visit-folder)
2120 (const vm-visit-folder-other-window)
2121 (const vm-visit-folder-other-frame)))
2122 (cons (const vm-imap)
2123 (choice
2124 (const vm-visit-imap-folder)
2125 (const vm-visit-imap-folder-other-window)
2126 (const vm-visit-imap-folder-other-frame)))
2127 (cons (const gnus)
2128 (choice
2129 (const gnus)
2130 (const gnus-other-frame)
2131 (const org-gnus-no-new-news)))
2132 (cons (const file)
2133 (choice
2134 (const find-file)
2135 (const find-file-other-window)
2136 (const find-file-other-frame)))
2137 (cons (const wl)
2138 (choice
2139 (const wl)
2140 (const wl-other-frame)))))
2142 (defcustom org-display-internal-link-with-indirect-buffer nil
2143 "Non-nil means use indirect buffer to display infile links.
2144 Activating internal links (from one location in a file to another location
2145 in the same file) normally just jumps to the location. When the link is
2146 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2147 is displayed in
2148 another window. When this option is set, the other window actually displays
2149 an indirect buffer clone of the current buffer, to avoid any visibility
2150 changes to the current buffer."
2151 :group 'org-link-follow
2152 :type 'boolean)
2154 (defcustom org-open-non-existing-files nil
2155 "Non-nil means `org-open-file' will open non-existing files.
2156 When nil, an error will be generated.
2157 This variable applies only to external applications because they
2158 might choke on non-existing files. If the link is to a file that
2159 will be opened in Emacs, the variable is ignored."
2160 :group 'org-link-follow
2161 :type 'boolean)
2163 (defcustom org-open-directory-means-index-dot-org nil
2164 "Non-nil means a link to a directory really means to index.org.
2165 When nil, following a directory link will run dired or open a finder/explorer
2166 window on that directory."
2167 :group 'org-link-follow
2168 :type 'boolean)
2170 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2171 "Non-nil means ask for confirmation before executing shell links.
2172 Shell links can be dangerous: just think about a link
2174 [[shell:rm -rf ~/*][Google Search]]
2176 This link would show up in your Org document as \"Google Search\",
2177 but really it would remove your entire home directory.
2178 Therefore we advise against setting this variable to nil.
2179 Just change it to `y-or-n-p' if you want to confirm with a
2180 single keystroke rather than having to type \"yes\"."
2181 :group 'org-link-follow
2182 :type '(choice
2183 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2184 (const :tag "with y-or-n (faster)" y-or-n-p)
2185 (const :tag "no confirmation (dangerous)" nil)))
2186 (put 'org-confirm-shell-link-function
2187 'safe-local-variable
2188 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2190 (defcustom org-confirm-shell-link-not-regexp ""
2191 "A regexp to skip confirmation for shell links."
2192 :group 'org-link-follow
2193 :version "24.1"
2194 :type 'regexp)
2196 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2197 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2198 Elisp links can be dangerous: just think about a link
2200 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2202 This link would show up in your Org document as \"Google Search\",
2203 but really it would remove your entire home directory.
2204 Therefore we advise against setting this variable to nil.
2205 Just change it to `y-or-n-p' if you want to confirm with a
2206 single keystroke rather than having to type \"yes\"."
2207 :group 'org-link-follow
2208 :type '(choice
2209 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2210 (const :tag "with y-or-n (faster)" y-or-n-p)
2211 (const :tag "no confirmation (dangerous)" nil)))
2212 (put 'org-confirm-shell-link-function
2213 'safe-local-variable
2214 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2216 (defcustom org-confirm-elisp-link-not-regexp ""
2217 "A regexp to skip confirmation for Elisp links."
2218 :group 'org-link-follow
2219 :version "24.1"
2220 :type 'regexp)
2222 (defconst org-file-apps-defaults-gnu
2223 '((remote . emacs)
2224 (system . mailcap)
2225 (t . mailcap))
2226 "Default file applications on a UNIX or GNU/Linux system.
2227 See `org-file-apps'.")
2229 (defconst org-file-apps-defaults-macosx
2230 '((remote . emacs)
2231 (system . "open %s")
2232 ("ps.gz" . "gv %s")
2233 ("eps.gz" . "gv %s")
2234 ("dvi" . "xdvi %s")
2235 ("fig" . "xfig %s")
2236 (t . "open %s"))
2237 "Default file applications on a macOS system.
2238 The system \"open\" is known as a default, but we use X11 applications
2239 for some files for which the OS does not have a good default.
2240 See `org-file-apps'.")
2242 (defconst org-file-apps-defaults-windowsnt
2243 (list '(remote . emacs)
2244 (cons 'system (lambda (file _path)
2245 (with-no-warnings (w32-shell-execute "open" file))))
2246 (cons t (lambda (file _path)
2247 (with-no-warnings (w32-shell-execute "open" file)))))
2248 "Default file applications on a Windows NT system.
2249 The system \"open\" is used for most files.
2250 See `org-file-apps'.")
2252 (defcustom org-file-apps
2253 '((auto-mode . emacs)
2254 ("\\.mm\\'" . default)
2255 ("\\.x?html?\\'" . default)
2256 ("\\.pdf\\'" . default))
2257 "External applications for opening `file:path' items in a document.
2258 \\<org-mode-map>\
2260 Org mode uses system defaults for different file types, but
2261 you can use this variable to set the application for a given file
2262 extension. The entries in this list are cons cells where the car identifies
2263 files and the cdr the corresponding command.
2265 Possible values for the file identifier are:
2267 \"string\" A string as a file identifier can be interpreted in different
2268 ways, depending on its contents:
2270 - Alphanumeric characters only:
2271 Match links with this file extension.
2272 Example: (\"pdf\" . \"evince %s\")
2273 to open PDFs with evince.
2275 - Regular expression: Match links where the
2276 filename matches the regexp. If you want to
2277 use groups here, use shy groups.
2279 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2280 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2281 to open *.html and *.xhtml with firefox.
2283 - Regular expression which contains (non-shy) groups:
2284 Match links where the whole link, including \"::\", and
2285 anything after that, matches the regexp.
2286 In a custom command string, %1, %2, etc. are replaced with
2287 the parts of the link that were matched by the groups.
2288 For backwards compatibility, if a command string is given
2289 that does not use any of the group matches, this case is
2290 handled identically to the second one (i.e. match against
2291 file name only).
2292 In a custom function, you can access the group matches with
2293 (match-string n link).
2295 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2296 \"evince -p %1 %s\")
2297 to open [[file:document.pdf::5]] with evince at page 5.
2299 `directory' Matches a directory
2300 `remote' Matches a remote file, accessible through tramp or efs.
2301 Remote files most likely should be visited through Emacs
2302 because external applications cannot handle such paths.
2303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2304 so all files Emacs knows how to handle. Using this with
2305 command `emacs' will open most files in Emacs. Beware that this
2306 will also open html files inside Emacs, unless you add
2307 (\"html\" . default) to the list as well.
2308 `system' The system command to open files, like `open' on Windows
2309 and macOS, and mailcap under GNU/Linux. This is the command
2310 that will be selected if you call `org-open-at-point' with a
2311 double prefix argument (`\\[universal-argument] \
2312 \\[universal-argument] \\[org-open-at-point]').
2313 t Default for files not matched by any of the other options.
2315 Possible values for the command are:
2317 `emacs' The file will be visited by the current Emacs process.
2318 `default' Use the default application for this file type, which is the
2319 association for t in the list, most likely in the system-specific
2320 part. This can be used to overrule an unwanted setting in the
2321 system-specific variable.
2322 `system' Use the system command for opening files, like \"open\".
2323 This command is specified by the entry whose car is `system'.
2324 Most likely, the system-specific version of this variable
2325 does define this command, but you can overrule/replace it
2326 here.
2327 `mailcap' Use command specified in the mailcaps.
2328 string A command to be executed by a shell; %s will be replaced
2329 by the path to the file.
2330 function A Lisp function, which will be called with two arguments:
2331 the file path and the original link string, without the
2332 \"file:\" prefix.
2334 For more examples, see the system specific constants
2335 `org-file-apps-defaults-macosx'
2336 `org-file-apps-defaults-windowsnt'
2337 `org-file-apps-defaults-gnu'."
2338 :group 'org-link-follow
2339 :type '(repeat
2340 (cons (choice :value ""
2341 (string :tag "Extension")
2342 (const :tag "System command to open files" system)
2343 (const :tag "Default for unrecognized files" t)
2344 (const :tag "Remote file" remote)
2345 (const :tag "Links to a directory" directory)
2346 (const :tag "Any files that have Emacs modes"
2347 auto-mode))
2348 (choice :value ""
2349 (const :tag "Visit with Emacs" emacs)
2350 (const :tag "Use default" default)
2351 (const :tag "Use the system command" system)
2352 (string :tag "Command")
2353 (function :tag "Function")))))
2355 (defcustom org-doi-server-url "http://dx.doi.org/"
2356 "The URL of the DOI server."
2357 :type 'string
2358 :version "24.3"
2359 :group 'org-link-follow)
2361 (defgroup org-refile nil
2362 "Options concerning refiling entries in Org mode."
2363 :tag "Org Refile"
2364 :group 'org)
2366 (defcustom org-directory "~/org"
2367 "Directory with Org files.
2368 This is just a default location to look for Org files. There is no need
2369 at all to put your files into this directory. It is used in the
2370 following situations:
2372 1. When a capture template specifies a target file that is not an
2373 absolute path. The path will then be interpreted relative to
2374 `org-directory'
2375 2. When the value of variable `org-agenda-files' is a single file, any
2376 relative paths in this file will be taken as relative to
2377 `org-directory'."
2378 :group 'org-refile
2379 :group 'org-capture
2380 :type 'directory)
2382 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2383 "Default target for storing notes.
2384 Used as a fall back file for org-capture.el, for templates that
2385 do not specify a target file."
2386 :group 'org-refile
2387 :group 'org-capture
2388 :type 'file)
2390 (defcustom org-goto-interface 'outline
2391 "The default interface to be used for `org-goto'.
2392 Allowed values are:
2393 outline The interface shows an outline of the relevant file
2394 and the correct heading is found by moving through
2395 the outline or by searching with incremental search.
2396 outline-path-completion Headlines in the current buffer are offered via
2397 completion. This is the interface also used by
2398 the refile command."
2399 :group 'org-refile
2400 :type '(choice
2401 (const :tag "Outline" outline)
2402 (const :tag "Outline-path-completion" outline-path-completion)))
2404 (defcustom org-goto-max-level 5
2405 "Maximum target level when running `org-goto' with refile interface."
2406 :group 'org-refile
2407 :type 'integer)
2409 (defcustom org-reverse-note-order nil
2410 "Non-nil means store new notes at the beginning of a file or entry.
2411 When nil, new notes will be filed to the end of a file or entry.
2412 This can also be a list with cons cells of regular expressions that
2413 are matched against file names, and values."
2414 :group 'org-capture
2415 :group 'org-refile
2416 :type '(choice
2417 (const :tag "Reverse always" t)
2418 (const :tag "Reverse never" nil)
2419 (repeat :tag "By file name regexp"
2420 (cons regexp boolean))))
2422 (defcustom org-log-refile nil
2423 "Information to record when a task is refiled.
2425 Possible values are:
2427 nil Don't add anything
2428 time Add a time stamp to the task
2429 note Prompt for a note and add it with template `org-log-note-headings'
2431 This option can also be set with on a per-file-basis with
2433 #+STARTUP: nologrefile
2434 #+STARTUP: logrefile
2435 #+STARTUP: lognoterefile
2437 You can have local logging settings for a subtree by setting the LOGGING
2438 property to one or more of these keywords.
2440 When bulk-refiling from the agenda, the value `note' is forbidden and
2441 will temporarily be changed to `time'."
2442 :group 'org-refile
2443 :group 'org-progress
2444 :version "24.1"
2445 :type '(choice
2446 (const :tag "No logging" nil)
2447 (const :tag "Record timestamp" time)
2448 (const :tag "Record timestamp with note." note)))
2450 (defcustom org-refile-targets nil
2451 "Targets for refiling entries with `\\[org-refile]'.
2452 This is a list of cons cells. Each cell contains:
2453 - a specification of the files to be considered, either a list of files,
2454 or a symbol whose function or variable value will be used to retrieve
2455 a file name or a list of file names. If you use `org-agenda-files' for
2456 that, all agenda files will be scanned for targets. Nil means consider
2457 headings in the current buffer.
2458 - A specification of how to find candidate refile targets. This may be
2459 any of:
2460 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2461 This tag has to be present in all target headlines, inheritance will
2462 not be considered.
2463 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2464 todo keyword.
2465 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2466 headlines that are refiling targets.
2467 - a cons cell (:level . N). Any headline of level N is considered a target.
2468 Note that, when `org-odd-levels-only' is set, level corresponds to
2469 order in hierarchy, not to the number of stars.
2470 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2471 Note that, when `org-odd-levels-only' is set, level corresponds to
2472 order in hierarchy, not to the number of stars.
2474 Each element of this list generates a set of possible targets.
2475 The union of these sets is presented (with completion) to
2476 the user by `org-refile'.
2478 You can set the variable `org-refile-target-verify-function' to a function
2479 to verify each headline found by the simple criteria above.
2481 When this variable is nil, all top-level headlines in the current buffer
2482 are used, equivalent to the value `((nil . (:level . 1))'."
2483 :group 'org-refile
2484 :type '(repeat
2485 (cons
2486 (choice :value org-agenda-files
2487 (const :tag "All agenda files" org-agenda-files)
2488 (const :tag "Current buffer" nil)
2489 (function) (variable) (file))
2490 (choice :tag "Identify target headline by"
2491 (cons :tag "Specific tag" (const :value :tag) (string))
2492 (cons :tag "TODO keyword" (const :value :todo) (string))
2493 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2494 (cons :tag "Level number" (const :value :level) (integer))
2495 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2497 (defcustom org-refile-target-verify-function nil
2498 "Function to verify if the headline at point should be a refile target.
2499 The function will be called without arguments, with point at the
2500 beginning of the headline. It should return t and leave point
2501 where it is if the headline is a valid target for refiling.
2503 If the target should not be selected, the function must return nil.
2504 In addition to this, it may move point to a place from where the search
2505 should be continued. For example, the function may decide that the entire
2506 subtree of the current entry should be excluded and move point to the end
2507 of the subtree."
2508 :group 'org-refile
2509 :type '(choice
2510 (const nil)
2511 (function)))
2513 (defcustom org-refile-use-cache nil
2514 "Non-nil means cache refile targets to speed up the process.
2515 \\<org-mode-map>\
2516 The cache for a particular file will be updated automatically when
2517 the buffer has been killed, or when any of the marker used for flagging
2518 refile targets no longer points at a live buffer.
2519 If you have added new entries to a buffer that might themselves be targets,
2520 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2521 if you find that easier, \
2522 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2523 \\[org-refile]'."
2524 :group 'org-refile
2525 :version "24.1"
2526 :type 'boolean)
2528 (defcustom org-refile-use-outline-path nil
2529 "Non-nil means provide refile targets as paths.
2530 So a level 3 headline will be available as level1/level2/level3.
2532 When the value is `file', also include the file name (without directory)
2533 into the path. In this case, you can also stop the completion after
2534 the file name, to get entries inserted as top level in the file.
2536 When `full-file-path', include the full file path.
2538 When `buffer-name', use the buffer name."
2539 :group 'org-refile
2540 :type '(choice
2541 (const :tag "Not" nil)
2542 (const :tag "Yes" t)
2543 (const :tag "Start with file name" file)
2544 (const :tag "Start with full file path" full-file-path)
2545 (const :tag "Start with buffer name" buffer-name)))
2547 (defcustom org-outline-path-complete-in-steps t
2548 "Non-nil means complete the outline path in hierarchical steps.
2549 When Org uses the refile interface to select an outline path (see
2550 `org-refile-use-outline-path'), the completion of the path can be
2551 done in a single go, or it can be done in steps down the headline
2552 hierarchy. Going in steps is probably the best if you do not use
2553 a special completion package like `ido' or `icicles'. However,
2554 when using these packages, going in one step can be very fast,
2555 while still showing the whole path to the entry."
2556 :group 'org-refile
2557 :type 'boolean)
2559 (defcustom org-refile-allow-creating-parent-nodes nil
2560 "Non-nil means allow the creation of new nodes as refile targets.
2561 New nodes are then created by adding \"/new node name\" to the completion
2562 of an existing node. When the value of this variable is `confirm',
2563 new node creation must be confirmed by the user (recommended).
2564 When nil, the completion must match an existing entry.
2566 Note that, if the new heading is not seen by the criteria
2567 listed in `org-refile-targets', multiple instances of the same
2568 heading would be created by trying again to file under the new
2569 heading."
2570 :group 'org-refile
2571 :type '(choice
2572 (const :tag "Never" nil)
2573 (const :tag "Always" t)
2574 (const :tag "Prompt for confirmation" confirm)))
2576 (defcustom org-refile-active-region-within-subtree nil
2577 "Non-nil means also refile active region within a subtree.
2579 By default `org-refile' doesn't allow refiling regions if they
2580 don't contain a set of subtrees, but it might be convenient to
2581 do so sometimes: in that case, the first line of the region is
2582 converted to a headline before refiling."
2583 :group 'org-refile
2584 :version "24.1"
2585 :type 'boolean)
2587 (defgroup org-todo nil
2588 "Options concerning TODO items in Org mode."
2589 :tag "Org TODO"
2590 :group 'org)
2592 (defgroup org-progress nil
2593 "Options concerning Progress logging in Org mode."
2594 :tag "Org Progress"
2595 :group 'org-time)
2597 (defvar org-todo-interpretation-widgets
2598 '((:tag "Sequence (cycling hits every state)" sequence)
2599 (:tag "Type (cycling directly to DONE)" type))
2600 "The available interpretation symbols for customizing `org-todo-keywords'.
2601 Interested libraries should add to this list.")
2603 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2604 "List of TODO entry keyword sequences and their interpretation.
2605 \\<org-mode-map>This is a list of sequences.
2607 Each sequence starts with a symbol, either `sequence' or `type',
2608 indicating if the keywords should be interpreted as a sequence of
2609 action steps, or as different types of TODO items. The first
2610 keywords are states requiring action - these states will select a headline
2611 for inclusion into the global TODO list Org produces. If one of the
2612 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2613 signify that no further action is necessary. If \"|\" is not found,
2614 the last keyword is treated as the only DONE state of the sequence.
2616 The command `\\[org-todo]' cycles an entry through these states, and one
2617 additional state where no keyword is present. For details about this
2618 cycling, see the manual.
2620 TODO keywords and interpretation can also be set on a per-file basis with
2621 the special #+SEQ_TODO and #+TYP_TODO lines.
2623 Each keyword can optionally specify a character for fast state selection
2624 \(in combination with the variable `org-use-fast-todo-selection')
2625 and specifiers for state change logging, using the same syntax that
2626 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2627 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2628 indicates to record a time stamp each time this state is selected.
2630 Each keyword may also specify if a timestamp or a note should be
2631 recorded when entering or leaving the state, by adding additional
2632 characters in the parenthesis after the keyword. This looks like this:
2633 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2634 record only the time of the state change. With X and Y being either
2635 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2636 Y when leaving the state if and only if the *target* state does not
2637 define X. You may omit any of the fast-selection key or X or /Y,
2638 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2640 For backward compatibility, this variable may also be just a list
2641 of keywords. In this case the interpretation (sequence or type) will be
2642 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2643 :group 'org-todo
2644 :group 'org-keywords
2645 :type '(choice
2646 (repeat :tag "Old syntax, just keywords"
2647 (string :tag "Keyword"))
2648 (repeat :tag "New syntax"
2649 (cons
2650 (choice
2651 :tag "Interpretation"
2652 ;;Quick and dirty way to see
2653 ;;`org-todo-interpretations'. This takes the
2654 ;;place of item arguments
2655 :convert-widget
2656 (lambda (widget)
2657 (widget-put widget
2658 :args (mapcar
2659 (lambda (x)
2660 (widget-convert
2661 (cons 'const x)))
2662 org-todo-interpretation-widgets))
2663 widget))
2664 (repeat
2665 (string :tag "Keyword"))))))
2667 (defvar-local org-todo-keywords-1 nil
2668 "All TODO and DONE keywords active in a buffer.")
2669 (defvar org-todo-keywords-for-agenda nil)
2670 (defvar org-done-keywords-for-agenda nil)
2671 (defvar org-todo-keyword-alist-for-agenda nil)
2672 (defvar org-tag-alist-for-agenda nil
2673 "Alist of all tags from all agenda files.")
2674 (defvar org-tag-groups-alist-for-agenda nil
2675 "Alist of all groups tags from all current agenda files.")
2676 (defvar-local org-tag-groups-alist nil)
2677 (defvar org-agenda-contributing-files nil)
2678 (defvar-local org-current-tag-alist nil
2679 "Alist of all tag groups in current buffer.
2680 This variable takes into consideration `org-tag-alist',
2681 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2682 (defvar-local org-not-done-keywords nil)
2683 (defvar-local org-done-keywords nil)
2684 (defvar-local org-todo-heads nil)
2685 (defvar-local org-todo-sets nil)
2686 (defvar-local org-todo-log-states nil)
2687 (defvar-local org-todo-kwd-alist nil)
2688 (defvar-local org-todo-key-alist nil)
2689 (defvar-local org-todo-key-trigger nil)
2691 (defcustom org-todo-interpretation 'sequence
2692 "Controls how TODO keywords are interpreted.
2693 This variable is in principle obsolete and is only used for
2694 backward compatibility, if the interpretation of todo keywords is
2695 not given already in `org-todo-keywords'. See that variable for
2696 more information."
2697 :group 'org-todo
2698 :group 'org-keywords
2699 :type '(choice (const sequence)
2700 (const type)))
2702 (defcustom org-use-fast-todo-selection t
2703 "\\<org-mode-map>\
2704 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2705 This variable describes if and under what circumstances the cycling
2706 mechanism for TODO keywords will be replaced by a single-key, direct
2707 selection scheme.
2709 When nil, fast selection is never used.
2711 When the symbol `prefix', it will be used when `org-todo' is called
2712 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2713 in an Org buffer, and
2714 `\\[universal-argument] t' in an agenda buffer.
2716 When t, fast selection is used by default. In this case, the prefix
2717 argument forces cycling instead.
2719 In all cases, the special interface is only used if access keys have
2720 actually been assigned by the user, i.e. if keywords in the configuration
2721 are followed by a letter in parenthesis, like TODO(t)."
2722 :group 'org-todo
2723 :type '(choice
2724 (const :tag "Never" nil)
2725 (const :tag "By default" t)
2726 (const :tag "Only with C-u C-c C-t" prefix)))
2728 (defcustom org-provide-todo-statistics t
2729 "Non-nil means update todo statistics after insert and toggle.
2730 ALL-HEADLINES means update todo statistics by including headlines
2731 with no TODO keyword as well, counting them as not done.
2732 A list of TODO keywords means the same, but skip keywords that are
2733 not in this list.
2734 When set to a list of two lists, the first list contains keywords
2735 to consider as TODO keywords, the second list contains keywords
2736 to consider as DONE keywords.
2738 When this is set, todo statistics is updated in the parent of the
2739 current entry each time a todo state is changed."
2740 :group 'org-todo
2741 :type '(choice
2742 (const :tag "Yes, only for TODO entries" t)
2743 (const :tag "Yes, including all entries" all-headlines)
2744 (repeat :tag "Yes, for TODOs in this list"
2745 (string :tag "TODO keyword"))
2746 (list :tag "Yes, for TODOs and DONEs in these lists"
2747 (repeat (string :tag "TODO keyword"))
2748 (repeat (string :tag "DONE keyword")))
2749 (other :tag "No TODO statistics" nil)))
2751 (defcustom org-hierarchical-todo-statistics t
2752 "Non-nil means TODO statistics covers just direct children.
2753 When nil, all entries in the subtree are considered.
2754 This has only an effect if `org-provide-todo-statistics' is set.
2755 To set this to nil for only a single subtree, use a COOKIE_DATA
2756 property and include the word \"recursive\" into the value."
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-after-todo-state-change-hook nil
2761 "Hook which is run after the state of a TODO item was changed.
2762 The new state (a string with a TODO keyword, or nil) is available in the
2763 Lisp variable `org-state'."
2764 :group 'org-todo
2765 :type 'hook)
2767 (defvar org-blocker-hook nil
2768 "Hook for functions that are allowed to block a state change.
2770 Functions in this hook should not modify the buffer.
2771 Each function gets as its single argument a property list,
2772 see `org-trigger-hook' for more information about this list.
2774 If any of the functions in this hook returns nil, the state change
2775 is blocked.")
2777 (defvar org-trigger-hook nil
2778 "Hook for functions that are triggered by a state change.
2780 Each function gets as its single argument a property list with at
2781 least the following elements:
2783 (:type type-of-change :position pos-at-entry-start
2784 :from old-state :to new-state)
2786 Depending on the type, more properties may be present.
2788 This mechanism is currently implemented for:
2790 TODO state changes
2791 ------------------
2792 :type todo-state-change
2793 :from previous state (keyword as a string), or nil, or a symbol
2794 `todo' or `done', to indicate the general type of state.
2795 :to new state, like in :from")
2797 (defcustom org-enforce-todo-dependencies nil
2798 "Non-nil means undone TODO entries will block switching the parent to DONE.
2799 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2800 be blocked if any prior sibling is not yet done.
2801 Finally, if the parent is blocked because of ordered siblings of its own,
2802 the child will also be blocked."
2803 :set (lambda (var val)
2804 (set var val)
2805 (if val
2806 (add-hook 'org-blocker-hook
2807 'org-block-todo-from-children-or-siblings-or-parent)
2808 (remove-hook 'org-blocker-hook
2809 'org-block-todo-from-children-or-siblings-or-parent)))
2810 :group 'org-todo
2811 :type 'boolean)
2813 (defcustom org-enforce-todo-checkbox-dependencies nil
2814 "Non-nil means unchecked boxes will block switching the parent to DONE.
2815 When this is nil, checkboxes have no influence on switching TODO states.
2816 When non-nil, you first need to check off all check boxes before the TODO
2817 entry can be switched to DONE.
2818 This variable needs to be set before org.el is loaded, and you need to
2819 restart Emacs after a change to make the change effective. The only way
2820 to change is while Emacs is running is through the customize interface."
2821 :set (lambda (var val)
2822 (set var val)
2823 (if val
2824 (add-hook 'org-blocker-hook
2825 'org-block-todo-from-checkboxes)
2826 (remove-hook 'org-blocker-hook
2827 'org-block-todo-from-checkboxes)))
2828 :group 'org-todo
2829 :type 'boolean)
2831 (defcustom org-treat-insert-todo-heading-as-state-change nil
2832 "Non-nil means inserting a TODO heading is treated as state change.
2833 So when the command `\\[org-insert-todo-heading]' is used, state change
2834 logging will apply if appropriate. When nil, the new TODO item will
2835 be inserted directly, and no logging will take place."
2836 :group 'org-todo
2837 :type 'boolean)
2839 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2840 "Non-nil means switching TODO states with S-cursor counts as state change.
2841 This is the default behavior. However, setting this to nil allows a
2842 convenient way to select a TODO state and bypass any logging associated
2843 with that."
2844 :group 'org-todo
2845 :type 'boolean)
2847 (defcustom org-todo-state-tags-triggers nil
2848 "Tag changes that should be triggered by TODO state changes.
2849 This is a list. Each entry is
2851 (state-change (tag . flag) .......)
2853 State-change can be a string with a state, and empty string to indicate the
2854 state that has no TODO keyword, or it can be one of the symbols `todo'
2855 or `done', meaning any not-done or done state, respectively."
2856 :group 'org-todo
2857 :group 'org-tags
2858 :type '(repeat
2859 (cons (choice :tag "When changing to"
2860 (const :tag "Not-done state" todo)
2861 (const :tag "Done state" done)
2862 (string :tag "State"))
2863 (repeat
2864 (cons :tag "Tag action"
2865 (string :tag "Tag")
2866 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2868 (defcustom org-log-done nil
2869 "Information to record when a task moves to the DONE state.
2871 Possible values are:
2873 nil Don't add anything, just change the keyword
2874 time Add a time stamp to the task
2875 note Prompt for a note and add it with template `org-log-note-headings'
2877 This option can also be set with on a per-file-basis with
2879 #+STARTUP: nologdone
2880 #+STARTUP: logdone
2881 #+STARTUP: lognotedone
2883 You can have local logging settings for a subtree by setting the LOGGING
2884 property to one or more of these keywords."
2885 :group 'org-todo
2886 :group 'org-progress
2887 :type '(choice
2888 (const :tag "No logging" nil)
2889 (const :tag "Record CLOSED timestamp" time)
2890 (const :tag "Record CLOSED timestamp with note." note)))
2892 ;; Normalize old uses of org-log-done.
2893 (cond
2894 ((eq org-log-done t) (setq org-log-done 'time))
2895 ((and (listp org-log-done) (memq 'done org-log-done))
2896 (setq org-log-done 'note)))
2898 (defcustom org-log-reschedule nil
2899 "Information to record when the scheduling date of a tasks is modified.
2901 Possible values are:
2903 nil Don't add anything, just change the date
2904 time Add a time stamp to the task
2905 note Prompt for a note and add it with template `org-log-note-headings'
2907 This option can also be set with on a per-file-basis with
2909 #+STARTUP: nologreschedule
2910 #+STARTUP: logreschedule
2911 #+STARTUP: lognotereschedule"
2912 :group 'org-todo
2913 :group 'org-progress
2914 :type '(choice
2915 (const :tag "No logging" nil)
2916 (const :tag "Record timestamp" time)
2917 (const :tag "Record timestamp with note." note)))
2919 (defcustom org-log-redeadline nil
2920 "Information to record when the deadline date of a tasks is modified.
2922 Possible values are:
2924 nil Don't add anything, just change the date
2925 time Add a time stamp to the task
2926 note Prompt for a note and add it with template `org-log-note-headings'
2928 This option can also be set with on a per-file-basis with
2930 #+STARTUP: nologredeadline
2931 #+STARTUP: logredeadline
2932 #+STARTUP: lognoteredeadline
2934 You can have local logging settings for a subtree by setting the LOGGING
2935 property to one or more of these keywords."
2936 :group 'org-todo
2937 :group 'org-progress
2938 :type '(choice
2939 (const :tag "No logging" nil)
2940 (const :tag "Record timestamp" time)
2941 (const :tag "Record timestamp with note." note)))
2943 (defcustom org-log-note-clock-out nil
2944 "Non-nil means record a note when clocking out of an item.
2945 This can also be configured on a per-file basis by adding one of
2946 the following lines anywhere in the buffer:
2948 #+STARTUP: lognoteclock-out
2949 #+STARTUP: nolognoteclock-out"
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type 'boolean)
2954 (defcustom org-log-done-with-time t
2955 "Non-nil means the CLOSED time stamp will contain date and time.
2956 When nil, only the date will be recorded."
2957 :group 'org-progress
2958 :type 'boolean)
2960 (defcustom org-log-note-headings
2961 '((done . "CLOSING NOTE %t")
2962 (state . "State %-12s from %-12S %t")
2963 (note . "Note taken on %t")
2964 (reschedule . "Rescheduled from %S on %t")
2965 (delschedule . "Not scheduled, was %S on %t")
2966 (redeadline . "New deadline from %S on %t")
2967 (deldeadline . "Removed deadline, was %S on %t")
2968 (refile . "Refiled on %t")
2969 (clock-out . ""))
2970 "Headings for notes added to entries.
2972 The value is an alist, with the car being a symbol indicating the
2973 note context, and the cdr is the heading to be used. The heading
2974 may also be the empty string. The following placeholders can be
2975 used:
2977 %t a time stamp.
2978 %T an active time stamp instead the default inactive one
2979 %d a short-format time stamp.
2980 %D an active short-format time stamp.
2981 %s the new TODO state or time stamp (inactive), in double quotes.
2982 %S the old TODO state or time stamp (inactive), in double quotes.
2983 %u the user name.
2984 %U full user name.
2986 In fact, it is not a good idea to change the `state' entry,
2987 because Agenda Log mode depends on the format of these entries."
2988 :group 'org-todo
2989 :group 'org-progress
2990 :type '(list :greedy t
2991 (cons (const :tag "Heading when closing an item" done) string)
2992 (cons (const :tag
2993 "Heading when changing todo state (todo sequence only)"
2994 state) string)
2995 (cons (const :tag "Heading when just taking a note" note) string)
2996 (cons (const :tag "Heading when rescheduling" reschedule) string)
2997 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2998 (cons (const :tag "Heading when changing deadline" redeadline) string)
2999 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3000 (cons (const :tag "Heading when refiling" refile) string)
3001 (cons (const :tag "Heading when clocking out" clock-out) string)))
3003 (unless (assq 'note org-log-note-headings)
3004 (push '(note . "%t") org-log-note-headings))
3006 (defcustom org-log-into-drawer nil
3007 "Non-nil means insert state change notes and time stamps into a drawer.
3008 When nil, state changes notes will be inserted after the headline and
3009 any scheduling and clock lines, but not inside a drawer.
3011 The value of this variable should be the name of the drawer to use.
3012 LOGBOOK is proposed as the default drawer for this purpose, you can
3013 also set this to a string to define the drawer of your choice.
3015 A value of t is also allowed, representing \"LOGBOOK\".
3017 A value of t or nil can also be set with on a per-file-basis with
3019 #+STARTUP: logdrawer
3020 #+STARTUP: nologdrawer
3022 If this variable is set, `org-log-state-notes-insert-after-drawers'
3023 will be ignored.
3025 You can set the property LOG_INTO_DRAWER to overrule this setting for
3026 a subtree.
3028 Do not check directly this variable in a Lisp program. Call
3029 function `org-log-into-drawer' instead."
3030 :group 'org-todo
3031 :group 'org-progress
3032 :type '(choice
3033 (const :tag "Not into a drawer" nil)
3034 (const :tag "LOGBOOK" t)
3035 (string :tag "Other")))
3037 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3039 (defun org-log-into-drawer ()
3040 "Name of the log drawer, as a string, or nil.
3041 This is the value of `org-log-into-drawer'. However, if the
3042 current entry has or inherits a LOG_INTO_DRAWER property, it will
3043 be used instead of the default value."
3044 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3045 (cond ((equal p "nil") nil)
3046 ((equal p "t") "LOGBOOK")
3047 ((stringp p) p)
3048 (p "LOGBOOK")
3049 ((stringp org-log-into-drawer) org-log-into-drawer)
3050 (org-log-into-drawer "LOGBOOK"))))
3052 (defcustom org-log-state-notes-insert-after-drawers nil
3053 "Non-nil means insert state change notes after any drawers in entry.
3054 Only the drawers that *immediately* follow the headline and the
3055 deadline/scheduled line are skipped.
3056 When nil, insert notes right after the heading and perhaps the line
3057 with deadline/scheduling if present.
3059 This variable will have no effect if `org-log-into-drawer' is
3060 set."
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type 'boolean)
3065 (defcustom org-log-states-order-reversed t
3066 "Non-nil means the latest state note will be directly after heading.
3067 When nil, the state change notes will be ordered according to time.
3069 This option can also be set with on a per-file-basis with
3071 #+STARTUP: logstatesreversed
3072 #+STARTUP: nologstatesreversed"
3073 :group 'org-todo
3074 :group 'org-progress
3075 :type 'boolean)
3077 (defcustom org-todo-repeat-to-state nil
3078 "The TODO state to which a repeater should return the repeating task.
3079 By default this is the first task in a TODO sequence, or the previous state
3080 in a TODO_TYP set. But you can specify another task here.
3081 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3082 :group 'org-todo
3083 :version "24.1"
3084 :type '(choice (const :tag "Head of sequence" nil)
3085 (string :tag "Specific state")))
3087 (defcustom org-log-repeat 'time
3088 "Non-nil means record moving through the DONE state when triggering repeat.
3089 An auto-repeating task is immediately switched back to TODO when
3090 marked DONE. If you are not logging state changes (by adding \"@\"
3091 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3092 record a closing note, there will be no record of the task moving
3093 through DONE. This variable forces taking a note anyway.
3095 nil Don't force a record
3096 time Record a time stamp
3097 note Prompt for a note and add it with template `org-log-note-headings'
3099 This option can also be set with on a per-file-basis with
3101 #+STARTUP: nologrepeat
3102 #+STARTUP: logrepeat
3103 #+STARTUP: lognoterepeat
3105 You can have local logging settings for a subtree by setting the LOGGING
3106 property to one or more of these keywords."
3107 :group 'org-todo
3108 :group 'org-progress
3109 :type '(choice
3110 (const :tag "Don't force a record" nil)
3111 (const :tag "Force recording the DONE state" time)
3112 (const :tag "Force recording a note with the DONE state" note)))
3115 (defgroup org-priorities nil
3116 "Priorities in Org mode."
3117 :tag "Org Priorities"
3118 :group 'org-todo)
3120 (defcustom org-enable-priority-commands t
3121 "Non-nil means priority commands are active.
3122 When nil, these commands will be disabled, so that you never accidentally
3123 set a priority."
3124 :group 'org-priorities
3125 :type 'boolean)
3127 (defcustom org-highest-priority ?A
3128 "The highest priority of TODO items. A character like ?A, ?B etc.
3129 Must have a smaller ASCII number than `org-lowest-priority'."
3130 :group 'org-priorities
3131 :type 'character)
3133 (defcustom org-lowest-priority ?C
3134 "The lowest priority of TODO items. A character like ?A, ?B etc.
3135 Must have a larger ASCII number than `org-highest-priority'."
3136 :group 'org-priorities
3137 :type 'character)
3139 (defcustom org-default-priority ?B
3140 "The default priority of TODO items.
3141 This is the priority an item gets if no explicit priority is given.
3142 When starting to cycle on an empty priority the first step in the cycle
3143 depends on `org-priority-start-cycle-with-default'. The resulting first
3144 step priority must not exceed the range from `org-highest-priority' to
3145 `org-lowest-priority' which means that `org-default-priority' has to be
3146 in this range exclusive or inclusive the range boundaries. Else the
3147 first step refuses to set the default and the second will fall back
3148 to (depending on the command used) the highest or lowest priority."
3149 :group 'org-priorities
3150 :type 'character)
3152 (defcustom org-priority-start-cycle-with-default t
3153 "Non-nil means start with default priority when starting to cycle.
3154 When this is nil, the first step in the cycle will be (depending on the
3155 command used) one higher or lower than the default priority.
3156 See also `org-default-priority'."
3157 :group 'org-priorities
3158 :type 'boolean)
3160 (defcustom org-get-priority-function nil
3161 "Function to extract the priority from a string.
3162 The string is normally the headline. If this is nil Org computes the
3163 priority from the priority cookie like [#A] in the headline. It returns
3164 an integer, increasing by 1000 for each priority level.
3165 The user can set a different function here, which should take a string
3166 as an argument and return the numeric priority."
3167 :group 'org-priorities
3168 :version "24.1"
3169 :type '(choice
3170 (const nil)
3171 (function)))
3173 (defgroup org-time nil
3174 "Options concerning time stamps and deadlines in Org mode."
3175 :tag "Org Time"
3176 :group 'org)
3178 (defcustom org-time-stamp-rounding-minutes '(0 5)
3179 "Number of minutes to round time stamps to.
3180 \\<org-mode-map>\
3181 These are two values, the first applies when first creating a time stamp.
3182 The second applies when changing it with the commands `S-up' and `S-down'.
3183 When changing the time stamp, this means that it will change in steps
3184 of N minutes, as given by the second value.
3186 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3187 numbers should be factors of 60, so for example 5, 10, 15.
3189 When this is larger than 1, you can still force an exact time stamp by using
3190 a double prefix argument to a time stamp command like \
3191 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3192 and by using a prefix arg to `S-up/down' to specify the exact number
3193 of minutes to shift."
3194 :group 'org-time
3195 :get (lambda (var) ; Make sure both elements are there
3196 (if (integerp (default-value var))
3197 (list (default-value var) 5)
3198 (default-value var)))
3199 :type '(list
3200 (integer :tag "when inserting times")
3201 (integer :tag "when modifying times")))
3203 ;; Normalize old customizations of this variable.
3204 (when (integerp org-time-stamp-rounding-minutes)
3205 (setq org-time-stamp-rounding-minutes
3206 (list org-time-stamp-rounding-minutes
3207 org-time-stamp-rounding-minutes)))
3209 (defcustom org-display-custom-times nil
3210 "Non-nil means overlay custom formats over all time stamps.
3211 The formats are defined through the variable `org-time-stamp-custom-formats'.
3212 To turn this on on a per-file basis, insert anywhere in the file:
3213 #+STARTUP: customtime"
3214 :group 'org-time
3215 :set 'set-default
3216 :type 'sexp)
3217 (make-variable-buffer-local 'org-display-custom-times)
3219 (defcustom org-time-stamp-custom-formats
3220 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3221 "Custom formats for time stamps. See `format-time-string' for the syntax.
3222 These are overlaid over the default ISO format if the variable
3223 `org-display-custom-times' is set. Time like %H:%M should be at the
3224 end of the second format. The custom formats are also honored by export
3225 commands, if custom time display is turned on at the time of export."
3226 :group 'org-time
3227 :type 'sexp)
3229 (defun org-time-stamp-format (&optional long inactive)
3230 "Get the right format for a time string."
3231 (let ((f (if long (cdr org-time-stamp-formats)
3232 (car org-time-stamp-formats))))
3233 (if inactive
3234 (concat "[" (substring f 1 -1) "]")
3235 f)))
3237 (defcustom org-deadline-warning-days 14
3238 "Number of days before expiration during which a deadline becomes active.
3239 This variable governs the display in sparse trees and in the agenda.
3240 When 0 or negative, it means use this number (the absolute value of it)
3241 even if a deadline has a different individual lead time specified.
3243 Custom commands can set this variable in the options section."
3244 :group 'org-time
3245 :group 'org-agenda-daily/weekly
3246 :type 'integer)
3248 (defcustom org-scheduled-delay-days 0
3249 "Number of days before a scheduled item becomes active.
3250 This variable governs the display in sparse trees and in the agenda.
3251 The default value (i.e. 0) means: don't delay scheduled item.
3252 When negative, it means use this number (the absolute value of it)
3253 even if a scheduled item has a different individual delay time
3254 specified.
3256 Custom commands can set this variable in the options section."
3257 :group 'org-time
3258 :group 'org-agenda-daily/weekly
3259 :version "24.4"
3260 :package-version '(Org . "8.0")
3261 :type 'integer)
3263 (defcustom org-read-date-prefer-future t
3264 "Non-nil means assume future for incomplete date input from user.
3265 This affects the following situations:
3266 1. The user gives a month but not a year.
3267 For example, if it is April and you enter \"feb 2\", this will be read
3268 as Feb 2, *next* year. \"May 5\", however, will be this year.
3269 2. The user gives a day, but no month.
3270 For example, if today is the 15th, and you enter \"3\", Org will read
3271 this as the third of *next* month. However, if you enter \"17\",
3272 it will be considered as *this* month.
3274 If you set this variable to the symbol `time', then also the following
3275 will work:
3277 3. If the user gives a time.
3278 If the time is before now, it will be interpreted as tomorrow.
3280 Currently none of this works for ISO week specifications.
3282 When this option is nil, the current day, month and year will always be
3283 used as defaults.
3285 See also `org-agenda-jump-prefer-future'."
3286 :group 'org-time
3287 :type '(choice
3288 (const :tag "Never" nil)
3289 (const :tag "Check month and day" t)
3290 (const :tag "Check month, day, and time" time)))
3292 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3293 "Should the agenda jump command prefer the future for incomplete dates?
3294 The default is to do the same as configured in `org-read-date-prefer-future'.
3295 But you can also set a deviating value here.
3296 This may t or nil, or the symbol `org-read-date-prefer-future'."
3297 :group 'org-agenda
3298 :group 'org-time
3299 :version "24.1"
3300 :type '(choice
3301 (const :tag "Use org-read-date-prefer-future"
3302 org-read-date-prefer-future)
3303 (const :tag "Never" nil)
3304 (const :tag "Always" t)))
3306 (defcustom org-read-date-force-compatible-dates t
3307 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3309 Depending on the system Emacs is running on, certain dates cannot
3310 be represented with the type used internally to represent time.
3311 Dates between 1970-1-1 and 2038-1-1 can always be represented
3312 correctly. Some systems allow for earlier dates, some for later,
3313 some for both. One way to find out it to insert any date into an
3314 Org buffer, putting the cursor on the year and hitting S-up and
3315 S-down to test the range.
3317 When this variable is set to t, the date/time prompt will not let
3318 you specify dates outside the 1970-2037 range, so it is certain that
3319 these dates will work in whatever version of Emacs you are
3320 running, and also that you can move a file from one Emacs implementation
3321 to another. WHenever Org is forcing the year for you, it will display
3322 a message and beep.
3324 When this variable is nil, Org will check if the date is
3325 representable in the specific Emacs implementation you are using.
3326 If not, it will force a year, usually the current year, and beep
3327 to remind you. Currently this setting is not recommended because
3328 the likelihood that you will open your Org files in an Emacs that
3329 has limited date range is not negligible.
3331 A workaround for this problem is to use diary sexp dates for time
3332 stamps outside of this range."
3333 :group 'org-time
3334 :version "24.1"
3335 :type 'boolean)
3337 (defcustom org-read-date-display-live t
3338 "Non-nil means display current interpretation of date prompt live.
3339 This display will be in an overlay, in the minibuffer."
3340 :group 'org-time
3341 :type 'boolean)
3343 (defcustom org-read-date-popup-calendar t
3344 "Non-nil means pop up a calendar when prompting for a date.
3345 In the calendar, the date can be selected with mouse-1. However, the
3346 minibuffer will also be active, and you can simply enter the date as well.
3347 When nil, only the minibuffer will be available."
3348 :group 'org-time
3349 :type 'boolean)
3350 (defvaralias 'org-popup-calendar-for-date-prompt
3351 'org-read-date-popup-calendar)
3353 (defcustom org-extend-today-until 0
3354 "The hour when your day really ends. Must be an integer.
3355 This has influence for the following applications:
3356 - When switching the agenda to \"today\". It it is still earlier than
3357 the time given here, the day recognized as TODAY is actually yesterday.
3358 - When a date is read from the user and it is still before the time given
3359 here, the current date and time will be assumed to be yesterday, 23:59.
3360 Also, timestamps inserted in capture templates follow this rule.
3362 IMPORTANT: This is a feature whose implementation is and likely will
3363 remain incomplete. Really, it is only here because past midnight seems to
3364 be the favorite working time of John Wiegley :-)"
3365 :group 'org-time
3366 :type 'integer)
3368 (defcustom org-use-effective-time nil
3369 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3370 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3371 \"effective time\" of any timestamps between midnight and 8am will be
3372 23:59 of the previous day."
3373 :group 'org-time
3374 :version "24.1"
3375 :type 'boolean)
3377 (defcustom org-use-last-clock-out-time-as-effective-time nil
3378 "When non-nil, use the last clock out time for `org-todo'.
3379 Note that this option has precedence over the combined use of
3380 `org-use-effective-time' and `org-extend-today-until'."
3381 :group 'org-time
3382 :version "24.4"
3383 :package-version '(Org . "8.0")
3384 :type 'boolean)
3386 (defcustom org-edit-timestamp-down-means-later nil
3387 "Non-nil means S-down will increase the time in a time stamp.
3388 When nil, S-up will increase."
3389 :group 'org-time
3390 :type 'boolean)
3392 (defcustom org-calendar-follow-timestamp-change t
3393 "Non-nil means make the calendar window follow timestamp changes.
3394 When a timestamp is modified and the calendar window is visible, it will be
3395 moved to the new date."
3396 :group 'org-time
3397 :type 'boolean)
3399 (defgroup org-tags nil
3400 "Options concerning tags in Org mode."
3401 :tag "Org Tags"
3402 :group 'org)
3404 (defcustom org-tag-alist nil
3405 "Default tags available in Org files.
3407 The value of this variable is an alist. Associations either:
3409 (TAG)
3410 (TAG . SELECT)
3411 (SPECIAL)
3413 where TAG is a tag as a string, SELECT is character, used to
3414 select that tag through the fast tag selection interface, and
3415 SPECIAL is one of the following keywords: `:startgroup',
3416 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3417 `:newline'. These keywords are used to define a hierarchy of
3418 tags. See manual for details.
3420 When this variable is nil, Org mode bases tag input on what is
3421 already in the buffer. The value can be overridden locally by
3422 using a TAGS keyword, e.g.,
3424 #+TAGS: tag1 tag2
3426 See also `org-tag-persistent-alist' to sidestep this behavior."
3427 :group 'org-tags
3428 :type '(repeat
3429 (choice
3430 (cons :tag "Tag with key"
3431 (string :tag "Tag name")
3432 (character :tag "Access char"))
3433 (list :tag "Tag" (string :tag "Tag name"))
3434 (const :tag "Start radio group" (:startgroup))
3435 (const :tag "Start tag group, non distinct" (:startgrouptag))
3436 (const :tag "Group tags delimiter" (:grouptags))
3437 (const :tag "End radio group" (:endgroup))
3438 (const :tag "End tag group, non distinct" (:endgrouptag))
3439 (const :tag "New line" (:newline)))))
3441 (defcustom org-tag-persistent-alist nil
3442 "Tags always available in Org files.
3444 The value of this variable is an alist. Associations either:
3446 (TAG)
3447 (TAG . SELECT)
3448 (SPECIAL)
3450 where TAG is a tag as a string, SELECT is a character, used to
3451 select that tag through the fast tag selection interface, and
3452 SPECIAL is one of the following keywords: `:startgroup',
3453 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3454 `:newline'. These keywords are used to define a hierarchy of
3455 tags. See manual for details.
3457 Unlike to `org-tag-alist', tags defined in this variable do not
3458 depend on a local TAGS keyword. Instead, to disable these tags
3459 on a per-file basis, insert anywhere in the file:
3461 #+STARTUP: noptag"
3462 :group 'org-tags
3463 :type '(repeat
3464 (choice
3465 (cons :tag "Tag with key"
3466 (string :tag "Tag name")
3467 (character :tag "Access char"))
3468 (list :tag "Tag" (string :tag "Tag name"))
3469 (const :tag "Start radio group" (:startgroup))
3470 (const :tag "Start tag group, non distinct" (:startgrouptag))
3471 (const :tag "Group tags delimiter" (:grouptags))
3472 (const :tag "End radio group" (:endgroup))
3473 (const :tag "End tag group, non distinct" (:endgrouptag))
3474 (const :tag "New line" (:newline)))))
3476 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3477 "If non-nil, always offer completion for all tags of all agenda files.
3478 Instead of customizing this variable directly, you might want to
3479 set it locally for capture buffers, because there no list of
3480 tags in that file can be created dynamically (there are none).
3482 (add-hook \\='org-capture-mode-hook
3483 (lambda ()
3484 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3485 :group 'org-tags
3486 :version "24.1"
3487 :type 'boolean)
3489 (defvar org-file-tags nil
3490 "List of tags that can be inherited by all entries in the file.
3491 The tags will be inherited if the variable `org-use-tag-inheritance'
3492 says they should be.
3493 This variable is populated from #+FILETAGS lines.")
3495 (defcustom org-use-fast-tag-selection 'auto
3496 "Non-nil means use fast tag selection scheme.
3497 This is a special interface to select and deselect tags with single keys.
3498 When nil, fast selection is never used.
3499 When the symbol `auto', fast selection is used if and only if selection
3500 characters for tags have been configured, either through the variable
3501 `org-tag-alist' or through a #+TAGS line in the buffer.
3502 When t, fast selection is always used and selection keys are assigned
3503 automatically if necessary."
3504 :group 'org-tags
3505 :type '(choice
3506 (const :tag "Always" t)
3507 (const :tag "Never" nil)
3508 (const :tag "When selection characters are configured" auto)))
3510 (defcustom org-fast-tag-selection-single-key nil
3511 "Non-nil means fast tag selection exits after first change.
3512 When nil, you have to press RET to exit it.
3513 During fast tag selection, you can toggle this flag with `C-c'.
3514 This variable can also have the value `expert'. In this case, the window
3515 displaying the tags menu is not even shown, until you press C-c again."
3516 :group 'org-tags
3517 :type '(choice
3518 (const :tag "No" nil)
3519 (const :tag "Yes" t)
3520 (const :tag "Expert" expert)))
3522 (defvar org-fast-tag-selection-include-todo nil
3523 "Non-nil means fast tags selection interface will also offer TODO states.
3524 This is an undocumented feature, you should not rely on it.")
3526 (defcustom org-tags-column -77
3527 "The column to which tags should be indented in a headline.
3528 If this number is positive, it specifies the column. If it is negative,
3529 it means that the tags should be flushright to that column. For example,
3530 -80 works well for a normal 80 character screen.
3531 When 0, place tags directly after headline text, with only one space in
3532 between."
3533 :group 'org-tags
3534 :type 'integer)
3536 (defcustom org-auto-align-tags t
3537 "Non-nil keeps tags aligned when modifying headlines.
3538 Some operations (i.e. demoting) change the length of a headline and
3539 therefore shift the tags around. With this option turned on, after
3540 each such operation the tags are again aligned to `org-tags-column'."
3541 :group 'org-tags
3542 :type 'boolean)
3544 (defcustom org-use-tag-inheritance t
3545 "Non-nil means tags in levels apply also for sublevels.
3546 When nil, only the tags directly given in a specific line apply there.
3547 This may also be a list of tags that should be inherited, or a regexp that
3548 matches tags that should be inherited. Additional control is possible
3549 with the variable `org-tags-exclude-from-inheritance' which gives an
3550 explicit list of tags to be excluded from inheritance, even if the value of
3551 `org-use-tag-inheritance' would select it for inheritance.
3553 If this option is t, a match early-on in a tree can lead to a large
3554 number of matches in the subtree when constructing the agenda or creating
3555 a sparse tree. If you only want to see the first match in a tree during
3556 a search, check out the variable `org-tags-match-list-sublevels'."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "Not" nil)
3560 (const :tag "Always" t)
3561 (repeat :tag "Specific tags" (string :tag "Tag"))
3562 (regexp :tag "Tags matched by regexp")))
3564 (defcustom org-tags-exclude-from-inheritance nil
3565 "List of tags that should never be inherited.
3566 This is a way to exclude a few tags from inheritance. For way to do
3567 the opposite, to actively allow inheritance for selected tags,
3568 see the variable `org-use-tag-inheritance'."
3569 :group 'org-tags
3570 :type '(repeat (string :tag "Tag")))
3572 (defun org-tag-inherit-p (tag)
3573 "Check if TAG is one that should be inherited."
3574 (cond
3575 ((member tag org-tags-exclude-from-inheritance) nil)
3576 ((eq org-use-tag-inheritance t) t)
3577 ((not org-use-tag-inheritance) nil)
3578 ((stringp org-use-tag-inheritance)
3579 (string-match org-use-tag-inheritance tag))
3580 ((listp org-use-tag-inheritance)
3581 (member tag org-use-tag-inheritance))
3582 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3584 (defcustom org-tags-match-list-sublevels t
3585 "Non-nil means list also sublevels of headlines matching a search.
3586 This variable applies to tags/property searches, and also to stuck
3587 projects because this search is based on a tags match as well.
3589 When set to the symbol `indented', sublevels are indented with
3590 leading dots.
3592 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3593 the sublevels of a headline matching a tag search often also match
3594 the same search. Listing all of them can create very long lists.
3595 Setting this variable to nil causes subtrees of a match to be skipped.
3597 This variable is semi-obsolete and probably should always be true. It
3598 is better to limit inheritance to certain tags using the variables
3599 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3600 :group 'org-tags
3601 :type '(choice
3602 (const :tag "No, don't list them" nil)
3603 (const :tag "Yes, do list them" t)
3604 (const :tag "List them, indented with leading dots" indented)))
3606 (defcustom org-tags-sort-function nil
3607 "When set, tags are sorted using this function as a comparator."
3608 :group 'org-tags
3609 :type '(choice
3610 (const :tag "No sorting" nil)
3611 (const :tag "Alphabetical" string<)
3612 (const :tag "Reverse alphabetical" string>)
3613 (function :tag "Custom function" nil)))
3615 (defvar org-tags-history nil
3616 "History of minibuffer reads for tags.")
3617 (defvar org-last-tags-completion-table nil
3618 "The last used completion table for tags.")
3619 (defvar org-after-tags-change-hook nil
3620 "Hook that is run after the tags in a line have changed.")
3622 (defgroup org-properties nil
3623 "Options concerning properties in Org mode."
3624 :tag "Org Properties"
3625 :group 'org)
3627 (defcustom org-property-format "%-10s %s"
3628 "How property key/value pairs should be formatted by `indent-line'.
3629 When `indent-line' hits a property definition, it will format the line
3630 according to this format, mainly to make sure that the values are
3631 lined-up with respect to each other."
3632 :group 'org-properties
3633 :type 'string)
3635 (defcustom org-properties-postprocess-alist nil
3636 "Alist of properties and functions to adjust inserted values.
3637 Elements of this alist must be of the form
3639 ([string] [function])
3641 where [string] must be a property name and [function] must be a
3642 lambda expression: this lambda expression must take one argument,
3643 the value to adjust, and return the new value as a string.
3645 For example, this element will allow the property \"Remaining\"
3646 to be updated wrt the relation between the \"Effort\" property
3647 and the clock summary:
3649 ((\"Remaining\" (lambda(value)
3650 (let ((clocksum (org-clock-sum-current-item))
3651 (effort (org-duration-to-minutes
3652 (org-entry-get (point) \"Effort\"))))
3653 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3654 :group 'org-properties
3655 :version "24.1"
3656 :type '(alist :key-type (string :tag "Property")
3657 :value-type (function :tag "Function")))
3659 (defcustom org-use-property-inheritance nil
3660 "Non-nil means properties apply also for sublevels.
3662 This setting is chiefly used during property searches. Turning it on can
3663 cause significant overhead when doing a search, which is why it is not
3664 on by default.
3666 When nil, only the properties directly given in the current entry count.
3667 When t, every property is inherited. The value may also be a list of
3668 properties that should have inheritance, or a regular expression matching
3669 properties that should be inherited.
3671 However, note that some special properties use inheritance under special
3672 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3673 and the properties ending in \"_ALL\" when they are used as descriptor
3674 for valid values of a property.
3676 Note for programmers:
3677 When querying an entry with `org-entry-get', you can control if inheritance
3678 should be used. By default, `org-entry-get' looks only at the local
3679 properties. You can request inheritance by setting the inherit argument
3680 to t (to force inheritance) or to `selective' (to respect the setting
3681 in this variable)."
3682 :group 'org-properties
3683 :type '(choice
3684 (const :tag "Not" nil)
3685 (const :tag "Always" t)
3686 (repeat :tag "Specific properties" (string :tag "Property"))
3687 (regexp :tag "Properties matched by regexp")))
3689 (defun org-property-inherit-p (property)
3690 "Return a non-nil value if PROPERTY should be inherited."
3691 (cond
3692 ((eq org-use-property-inheritance t) t)
3693 ((not org-use-property-inheritance) nil)
3694 ((stringp org-use-property-inheritance)
3695 (string-match org-use-property-inheritance property))
3696 ((listp org-use-property-inheritance)
3697 (member-ignore-case property org-use-property-inheritance))
3698 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3700 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3701 "The default column format, if no other format has been defined.
3702 This variable can be set on the per-file basis by inserting a line
3704 #+COLUMNS: %25ITEM ....."
3705 :group 'org-properties
3706 :type 'string)
3708 (defcustom org-columns-ellipses ".."
3709 "The ellipses to be used when a field in column view is truncated.
3710 When this is the empty string, as many characters as possible are shown,
3711 but then there will be no visual indication that the field has been truncated.
3712 When this is a string of length N, the last N characters of a truncated
3713 field are replaced by this string. If the column is narrower than the
3714 ellipses string, only part of the ellipses string will be shown."
3715 :group 'org-properties
3716 :type 'string)
3718 (defconst org-global-properties-fixed
3719 '(("VISIBILITY_ALL" . "folded children content all")
3720 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3721 "List of property/value pairs that can be inherited by any entry.
3723 These are fixed values, for the preset properties. The user variable
3724 that can be used to add to this list is `org-global-properties'.
3726 The entries in this list are cons cells where the car is a property
3727 name and cdr is a string with the value. If the value represents
3728 multiple items like an \"_ALL\" property, separate the items by
3729 spaces.")
3731 (defcustom org-global-properties nil
3732 "List of property/value pairs that can be inherited by any entry.
3734 This list will be combined with the constant `org-global-properties-fixed'.
3736 The entries in this list are cons cells where the car is a property
3737 name and cdr is a string with the value.
3739 You can set buffer-local values for the same purpose in the variable
3740 `org-file-properties' this by adding lines like
3742 #+PROPERTY: NAME VALUE"
3743 :group 'org-properties
3744 :type '(repeat
3745 (cons (string :tag "Property")
3746 (string :tag "Value"))))
3748 (defvar-local org-file-properties nil
3749 "List of property/value pairs that can be inherited by any entry.
3750 Valid for the current buffer.
3751 This variable is populated from #+PROPERTY lines.")
3753 (defgroup org-agenda nil
3754 "Options concerning agenda views in Org mode."
3755 :tag "Org Agenda"
3756 :group 'org)
3758 (defvar-local org-category nil
3759 "Variable used by org files to set a category for agenda display.
3760 Such files should use a file variable to set it, for example
3762 # -*- mode: org; org-category: \"ELisp\"
3764 or contain a special line
3766 #+CATEGORY: ELisp
3768 If the file does not specify a category, then file's base name
3769 is used instead.")
3770 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3772 (defcustom org-agenda-files nil
3773 "The files to be used for agenda display.
3775 If an entry is a directory, all files in that directory that are matched
3776 by `org-agenda-file-regexp' will be part of the file list.
3778 If the value of the variable is not a list but a single file name, then
3779 the list of agenda files is actually stored and maintained in that file,
3780 one agenda file per line. In this file paths can be given relative to
3781 `org-directory'. Tilde expansion and environment variable substitution
3782 are also made.
3784 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3785 and removed with `\\[org-remove-file]'."
3786 :group 'org-agenda
3787 :type '(choice
3788 (repeat :tag "List of files and directories" file)
3789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3792 "Regular expression to match files for `org-agenda-files'.
3793 If any element in the list in that variable contains a directory instead
3794 of a normal file, all files in that directory that are matched by this
3795 regular expression will be included."
3796 :group 'org-agenda
3797 :type 'regexp)
3799 (defcustom org-agenda-text-search-extra-files nil
3800 "List of extra files to be searched by text search commands.
3801 These files will be searched in addition to the agenda files by the
3802 commands `org-search-view' (`\\[org-agenda] s') \
3803 and `org-occur-in-agenda-files'.
3804 Note that these files will only be searched for text search commands,
3805 not for the other agenda views like todo lists, tag searches or the weekly
3806 agenda. This variable is intended to list notes and possibly archive files
3807 that should also be searched by these two commands.
3808 In fact, if the first element in the list is the symbol `agenda-archives',
3809 then all archive files of all agenda files will be added to the search
3810 scope."
3811 :group 'org-agenda
3812 :type '(set :greedy t
3813 (const :tag "Agenda Archives" agenda-archives)
3814 (repeat :inline t (file))))
3816 (defvaralias 'org-agenda-multi-occur-extra-files
3817 'org-agenda-text-search-extra-files)
3819 (defcustom org-agenda-skip-unavailable-files nil
3820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3821 A nil value means to remove them, after a query, from the list."
3822 :group 'org-agenda
3823 :type 'boolean)
3825 (defcustom org-calendar-to-agenda-key [?c]
3826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3827 The command `org-calendar-goto-agenda' will be bound to this key. The
3828 default is the character `c' because then `c' can be used to switch back and
3829 forth between agenda and calendar."
3830 :group 'org-agenda
3831 :type 'sexp)
3833 (defcustom org-calendar-insert-diary-entry-key [?i]
3834 "The key to be installed in `calendar-mode-map' for adding diary entries.
3835 This option is irrelevant until `org-agenda-diary-file' has been configured
3836 to point to an Org file. When that is the case, the command
3837 `org-agenda-diary-entry' will be bound to the key given here, by default
3838 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3839 if you want to continue doing this, you need to change this to a different
3840 key."
3841 :group 'org-agenda
3842 :type 'sexp)
3844 (defcustom org-agenda-diary-file 'diary-file
3845 "File to which to add new entries with the `i' key in agenda and calendar.
3846 When this is the symbol `diary-file', the functionality in the Emacs
3847 calendar will be used to add entries to the `diary-file'. But when this
3848 points to a file, `org-agenda-diary-entry' will be used instead."
3849 :group 'org-agenda
3850 :type '(choice
3851 (const :tag "The standard Emacs diary file" diary-file)
3852 (file :tag "Special Org file diary entries")))
3854 (eval-after-load "calendar"
3855 '(progn
3856 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3857 'org-calendar-goto-agenda)
3858 (add-hook 'calendar-mode-hook
3859 (lambda ()
3860 (unless (eq org-agenda-diary-file 'diary-file)
3861 (define-key calendar-mode-map
3862 org-calendar-insert-diary-entry-key
3863 'org-agenda-diary-entry))))))
3865 (defgroup org-latex nil
3866 "Options for embedding LaTeX code into Org mode."
3867 :tag "Org LaTeX"
3868 :group 'org)
3870 (defcustom org-format-latex-options
3871 '(:foreground default :background default :scale 1.0
3872 :html-foreground "Black" :html-background "Transparent"
3873 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3874 "Options for creating images from LaTeX fragments.
3875 This is a property list with the following properties:
3876 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3877 `default' means use the foreground of the default face.
3878 `auto' means use the foreground from the text face.
3879 :background the background color, or \"Transparent\".
3880 `default' means use the background of the default face.
3881 `auto' means use the background from the text face.
3882 :scale a scaling factor for the size of the images, to get more pixels
3883 :html-foreground, :html-background, :html-scale
3884 the same numbers for HTML export.
3885 :matchers a list indicating which matchers should be used to
3886 find LaTeX fragments. Valid members of this list are:
3887 \"begin\" find environments
3888 \"$1\" find single characters surrounded by $.$
3889 \"$\" find math expressions surrounded by $...$
3890 \"$$\" find math expressions surrounded by $$....$$
3891 \"\\(\" find math expressions surrounded by \\(...\\)
3892 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3893 :group 'org-latex
3894 :type 'plist)
3896 (defcustom org-format-latex-signal-error t
3897 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3898 When nil, just push out a message."
3899 :group 'org-latex
3900 :version "24.1"
3901 :type 'boolean)
3903 (defcustom org-latex-to-mathml-jar-file nil
3904 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3905 Use this to specify additional executable file say a jar file.
3907 When using MathToWeb as the converter, specify the full-path to
3908 your mathtoweb.jar file."
3909 :group 'org-latex
3910 :version "24.1"
3911 :type '(choice
3912 (const :tag "None" nil)
3913 (file :tag "JAR file" :must-match t)))
3915 (defcustom org-latex-to-mathml-convert-command nil
3916 "Command to convert LaTeX fragments to MathML.
3917 Replace format-specifiers in the command as noted below and use
3918 `shell-command' to convert LaTeX to MathML.
3919 %j: Executable file in fully expanded form as specified by
3920 `org-latex-to-mathml-jar-file'.
3921 %I: Input LaTeX file in fully expanded form.
3922 %i: The latex fragment to be converted.
3923 %o: Output MathML file.
3925 This command is used by `org-create-math-formula'.
3927 When using MathToWeb as the converter, set this option to
3928 \"java -jar %j -unicode -force -df %o %I\".
3930 When using LaTeXML set this option to
3931 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3932 :group 'org-latex
3933 :version "24.1"
3934 :type '(choice
3935 (const :tag "None" nil)
3936 (string :tag "\nShell command")))
3938 (defcustom org-preview-latex-default-process 'dvipng
3939 "The default process to convert LaTeX fragments to image files.
3940 All available processes and theirs documents can be found in
3941 `org-preview-latex-process-alist', which see."
3942 :group 'org-latex
3943 :version "26.1"
3944 :package-version '(Org . "9.0")
3945 :type 'symbol)
3947 (defcustom org-preview-latex-process-alist
3948 '((dvipng
3949 :programs ("latex" "dvipng")
3950 :description "dvi > png"
3951 :message "you need to install the programs: latex and dvipng."
3952 :image-input-type "dvi"
3953 :image-output-type "png"
3954 :image-size-adjust (1.0 . 1.0)
3955 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3956 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3957 (dvisvgm
3958 :programs ("latex" "dvisvgm")
3959 :description "dvi > svg"
3960 :message "you need to install the programs: latex and dvisvgm."
3961 :use-xcolor t
3962 :image-input-type "dvi"
3963 :image-output-type "svg"
3964 :image-size-adjust (1.7 . 1.5)
3965 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3966 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3967 (imagemagick
3968 :programs ("latex" "convert")
3969 :description "pdf > png"
3970 :message "you need to install the programs: latex and imagemagick."
3971 :use-xcolor t
3972 :image-input-type "pdf"
3973 :image-output-type "png"
3974 :image-size-adjust (1.0 . 1.0)
3975 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3976 :image-converter
3977 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3978 "Definitions of external processes for LaTeX previewing.
3979 Org mode can use some external commands to generate TeX snippet's images for
3980 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3981 `org-create-formula-image' how to call them.
3983 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3984 PROPERTIES accepts the following attributes:
3986 :programs list of strings, required programs.
3987 :description string, describe the process.
3988 :message string, message it when required programs cannot be found.
3989 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3990 :image-output-type string, output file type of image converter (e.g., \"png\").
3991 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3992 deal with background and foreground color of image.
3993 Otherwise, dvipng style background and foreground color
3994 format are generated. You may then refer to them in
3995 command options with \"%F\" and \"%B\".
3996 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3997 image size showed in buffer and the cdr element is for
3998 HTML file. This option is only useful for process
3999 developers, users should use variable
4000 `org-format-latex-options' instead.
4001 :post-clean list of strings, files matched are to be cleaned up once
4002 the image is generated. When nil, the files with \".dvi\",
4003 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4004 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4005 be cleaned up.
4006 :latex-header list of strings, the LaTeX header of the snippet file.
4007 When nil, the fallback value is used instead, which is
4008 controlled by `org-format-latex-header',
4009 `org-latex-default-packages-alist' and
4010 `org-latex-packages-alist', which see.
4011 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4012 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4013 replaced with values defined below.
4014 :image-converter list of image converter commands strings. Each of them is
4015 given to the shell and supports any of the following
4016 place-holders defined below.
4018 Place-holders used by `:image-converter' and `:latex-compiler':
4020 %f input file name
4021 %b base name of input file
4022 %o base directory of input file
4023 %O absolute output file name
4025 Place-holders only used by `:image-converter':
4027 %F foreground of image
4028 %B background of image
4029 %D dpi, which is used to adjust image size by some processing commands.
4030 %S the image size scale ratio, which is used to adjust image size by some
4031 processing commands."
4032 :group 'org-latex
4033 :version "26.1"
4034 :package-version '(Org . "9.0")
4035 :type '(alist :tag "LaTeX to image backends"
4036 :value-type (plist)))
4038 (defcustom org-preview-latex-image-directory "ltximg/"
4039 "Path to store latex preview images.
4040 A relative path here creates many directories relative to the
4041 processed org files paths. An absolute path puts all preview
4042 images at the same place."
4043 :group 'org-latex
4044 :version "26.1"
4045 :package-version '(Org . "9.0")
4046 :type 'string)
4048 (defun org-format-latex-mathml-available-p ()
4049 "Return t if `org-latex-to-mathml-convert-command' is usable."
4050 (save-match-data
4051 (when (and (boundp 'org-latex-to-mathml-convert-command)
4052 org-latex-to-mathml-convert-command)
4053 (let ((executable (car (split-string
4054 org-latex-to-mathml-convert-command))))
4055 (when (executable-find executable)
4056 (if (string-match
4057 "%j" org-latex-to-mathml-convert-command)
4058 (file-readable-p org-latex-to-mathml-jar-file)
4059 t))))))
4061 (defcustom org-format-latex-header "\\documentclass{article}
4062 \\usepackage[usenames]{color}
4063 \[PACKAGES]
4064 \[DEFAULT-PACKAGES]
4065 \\pagestyle{empty} % do not remove
4066 % The settings below are copied from fullpage.sty
4067 \\setlength{\\textwidth}{\\paperwidth}
4068 \\addtolength{\\textwidth}{-3cm}
4069 \\setlength{\\oddsidemargin}{1.5cm}
4070 \\addtolength{\\oddsidemargin}{-2.54cm}
4071 \\setlength{\\evensidemargin}{\\oddsidemargin}
4072 \\setlength{\\textheight}{\\paperheight}
4073 \\addtolength{\\textheight}{-\\headheight}
4074 \\addtolength{\\textheight}{-\\headsep}
4075 \\addtolength{\\textheight}{-\\footskip}
4076 \\addtolength{\\textheight}{-3cm}
4077 \\setlength{\\topmargin}{1.5cm}
4078 \\addtolength{\\topmargin}{-2.54cm}"
4079 "The document header used for processing LaTeX fragments.
4080 It is imperative that this header make sure that no page number
4081 appears on the page. The package defined in the variables
4082 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4083 will either replace the placeholder \"[PACKAGES]\" in this
4084 header, or they will be appended."
4085 :group 'org-latex
4086 :type 'string)
4088 (defun org-set-packages-alist (var val)
4089 "Set the packages alist and make sure it has 3 elements per entry."
4090 (set var (mapcar (lambda (x)
4091 (if (and (consp x) (= (length x) 2))
4092 (list (car x) (nth 1 x) t)
4094 val)))
4096 (defun org-get-packages-alist (var)
4097 "Get the packages alist and make sure it has 3 elements per entry."
4098 (mapcar (lambda (x)
4099 (if (and (consp x) (= (length x) 2))
4100 (list (car x) (nth 1 x) t)
4102 (default-value var)))
4104 (defcustom org-latex-default-packages-alist
4105 '(("AUTO" "inputenc" t ("pdflatex"))
4106 ("T1" "fontenc" t ("pdflatex"))
4107 ("" "graphicx" t)
4108 ("" "grffile" t)
4109 ("" "longtable" nil)
4110 ("" "wrapfig" nil)
4111 ("" "rotating" nil)
4112 ("normalem" "ulem" t)
4113 ("" "amsmath" t)
4114 ("" "textcomp" t)
4115 ("" "amssymb" t)
4116 ("" "capt-of" nil)
4117 ("" "hyperref" nil))
4118 "Alist of default packages to be inserted in the header.
4120 Change this only if one of the packages here causes an
4121 incompatibility with another package you are using.
4123 The packages in this list are needed by one part or another of
4124 Org mode to function properly:
4126 - inputenc, fontenc: for basic font and character selection
4127 - graphicx: for including images
4128 - grffile: allow periods and spaces in graphics file names
4129 - longtable: For multipage tables
4130 - wrapfig: for figure placement
4131 - rotating: for sideways figures and tables
4132 - ulem: for underline and strike-through
4133 - amsmath: for subscript and superscript and math environments
4134 - textcomp, amssymb: for various symbols used
4135 for interpreting the entities in `org-entities'. You can skip
4136 some of these packages if you don't use any of their symbols.
4137 - capt-of: for captions outside of floats
4138 - hyperref: for cross references
4140 Therefore you should not modify this variable unless you know
4141 what you are doing. The one reason to change it anyway is that
4142 you might be loading some other package that conflicts with one
4143 of the default packages. Each element is either a cell or
4144 a string.
4146 A cell is of the format
4148 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4150 If SNIPPET-FLAG is non-nil, the package also needs to be included
4151 when compiling LaTeX snippets into images for inclusion into
4152 non-LaTeX output. COMPILERS is a list of compilers that should
4153 include the package, see `org-latex-compiler'. If the document
4154 compiler is not in the list, and the list is non-nil, the package
4155 will not be inserted in the final document.
4157 A string will be inserted as-is in the header of the document."
4158 :group 'org-latex
4159 :group 'org-export-latex
4160 :set 'org-set-packages-alist
4161 :get 'org-get-packages-alist
4162 :version "26.1"
4163 :package-version '(Org . "8.3")
4164 :type '(repeat
4165 (choice
4166 (list :tag "options/package pair"
4167 (string :tag "options")
4168 (string :tag "package")
4169 (boolean :tag "Snippet"))
4170 (string :tag "A line of LaTeX"))))
4172 (defcustom org-latex-packages-alist nil
4173 "Alist of packages to be inserted in every LaTeX header.
4175 These will be inserted after `org-latex-default-packages-alist'.
4176 Each element is either a cell or a string.
4178 A cell is of the format:
4180 (\"options\" \"package\" SNIPPET-FLAG)
4182 SNIPPET-FLAG, when non-nil, indicates that this package is also
4183 needed when turning LaTeX snippets into images for inclusion into
4184 non-LaTeX output.
4186 A string will be inserted as-is in the header of the document.
4188 Make sure that you only list packages here which:
4190 - you want in every file;
4191 - do not conflict with the setup in `org-format-latex-header';
4192 - do not conflict with the default packages in
4193 `org-latex-default-packages-alist'."
4194 :group 'org-latex
4195 :group 'org-export-latex
4196 :set 'org-set-packages-alist
4197 :get 'org-get-packages-alist
4198 :type '(repeat
4199 (choice
4200 (list :tag "options/package pair"
4201 (string :tag "options")
4202 (string :tag "package")
4203 (boolean :tag "Snippet"))
4204 (string :tag "A line of LaTeX"))))
4206 (defgroup org-appearance nil
4207 "Settings for Org mode appearance."
4208 :tag "Org Appearance"
4209 :group 'org)
4211 (defcustom org-level-color-stars-only nil
4212 "Non-nil means fontify only the stars in each headline.
4213 When nil, the entire headline is fontified.
4214 Changing it requires restart of `font-lock-mode' to become effective
4215 also in regions already fontified."
4216 :group 'org-appearance
4217 :type 'boolean)
4219 (defcustom org-hide-leading-stars nil
4220 "Non-nil means hide the first N-1 stars in a headline.
4221 This works by using the face `org-hide' for these stars. This
4222 face is white for a light background, and black for a dark
4223 background. You may have to customize the face `org-hide' to
4224 make this work.
4225 Changing it requires restart of `font-lock-mode' to become effective
4226 also in regions already fontified.
4227 You may also set this on a per-file basis by adding one of the following
4228 lines to the buffer:
4230 #+STARTUP: hidestars
4231 #+STARTUP: showstars"
4232 :group 'org-appearance
4233 :type 'boolean)
4235 (defcustom org-hidden-keywords nil
4236 "List of symbols corresponding to keywords to be hidden the org buffer.
4237 For example, a value \\='(title) for this list will make the document's title
4238 appear in the buffer without the initial #+TITLE: keyword."
4239 :group 'org-appearance
4240 :version "24.1"
4241 :type '(set (const :tag "#+AUTHOR" author)
4242 (const :tag "#+DATE" date)
4243 (const :tag "#+EMAIL" email)
4244 (const :tag "#+TITLE" title)))
4246 (defcustom org-custom-properties nil
4247 "List of properties (as strings) with a special meaning.
4248 The default use of these custom properties is to let the user
4249 hide them with `org-toggle-custom-properties-visibility'."
4250 :group 'org-properties
4251 :group 'org-appearance
4252 :version "24.3"
4253 :type '(repeat (string :tag "Property Name")))
4255 (defcustom org-fontify-done-headline nil
4256 "Non-nil means change the face of a headline if it is marked DONE.
4257 Normally, only the TODO/DONE keyword indicates the state of a headline.
4258 When this is non-nil, the headline after the keyword is set to the
4259 `org-headline-done' as an additional indication."
4260 :group 'org-appearance
4261 :type 'boolean)
4263 (defcustom org-fontify-emphasized-text t
4264 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4265 Changing this variable requires a restart of Emacs to take effect."
4266 :group 'org-appearance
4267 :type 'boolean)
4269 (defcustom org-fontify-whole-heading-line nil
4270 "Non-nil means fontify the whole line for headings.
4271 This is useful when setting a background color for the
4272 org-level-* faces."
4273 :group 'org-appearance
4274 :type 'boolean)
4276 (defcustom org-highlight-latex-and-related nil
4277 "Non-nil means highlight LaTeX related syntax in the buffer.
4278 When non nil, the value should be a list containing any of the
4279 following symbols:
4280 `latex' Highlight LaTeX snippets and environments.
4281 `script' Highlight subscript and superscript.
4282 `entities' Highlight entities."
4283 :group 'org-appearance
4284 :version "24.4"
4285 :package-version '(Org . "8.0")
4286 :type '(choice
4287 (const :tag "No highlighting" nil)
4288 (set :greedy t :tag "Highlight"
4289 (const :tag "LaTeX snippets and environments" latex)
4290 (const :tag "Subscript and superscript" script)
4291 (const :tag "Entities" entities))))
4293 (defcustom org-hide-emphasis-markers nil
4294 "Non-nil mean font-lock should hide the emphasis marker characters."
4295 :group 'org-appearance
4296 :type 'boolean)
4298 (defcustom org-hide-macro-markers nil
4299 "Non-nil mean font-lock should hide the brackets marking macro calls."
4300 :group 'org-appearance
4301 :type 'boolean)
4303 (defcustom org-pretty-entities nil
4304 "Non-nil means show entities as UTF8 characters.
4305 When nil, the \\name form remains in the buffer."
4306 :group 'org-appearance
4307 :version "24.1"
4308 :type 'boolean)
4310 (defcustom org-pretty-entities-include-sub-superscripts t
4311 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4312 :group 'org-appearance
4313 :version "24.1"
4314 :type 'boolean)
4316 (defvar org-emph-re nil
4317 "Regular expression for matching emphasis.
4318 After a match, the match groups contain these elements:
4319 0 The match of the full regular expression, including the characters
4320 before and after the proper match
4321 1 The character before the proper match, or empty at beginning of line
4322 2 The proper match, including the leading and trailing markers
4323 3 The leading marker like * or /, indicating the type of highlighting
4324 4 The text between the emphasis markers, not including the markers
4325 5 The character after the match, empty at the end of a line")
4327 (defvar org-verbatim-re nil
4328 "Regular expression for matching verbatim text.")
4330 (defvar org-emphasis-regexp-components) ; defined just below
4331 (defvar org-emphasis-alist) ; defined just below
4332 (defun org-set-emph-re (var val)
4333 "Set variable and compute the emphasis regular expression."
4334 (set var val)
4335 (when (and (boundp 'org-emphasis-alist)
4336 (boundp 'org-emphasis-regexp-components)
4337 org-emphasis-alist org-emphasis-regexp-components)
4338 (pcase-let*
4339 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4340 (body (if (<= nl 0) body
4341 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4342 (template
4343 (format (concat "\\([%s]\\|^\\)" ;before markers
4344 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4345 "\\([%s]\\|$\\)") ;after markers
4346 pre border border body border post)))
4347 (setq org-emph-re (format template "*/_+"))
4348 (setq org-verbatim-re (format template "=~")))))
4350 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4351 ;; set this option proved cumbersome. See this message/thread:
4352 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4353 (defvar org-emphasis-regexp-components
4354 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4355 "Components used to build the regular expression for emphasis.
4356 This is a list with five entries. Terminology: In an emphasis string
4357 like \" *strong word* \", we call the initial space PREMATCH, the final
4358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4359 and \"trong wor\" is the body. The different components in this variable
4360 specify what is allowed/forbidden in each part:
4362 pre Chars allowed as prematch. Beginning of line will be allowed too.
4363 post Chars allowed as postmatch. End of line will be allowed too.
4364 border The chars *forbidden* as border characters.
4365 body-regexp A regexp like \".\" to match a body character. Don't use
4366 non-shy groups here, and don't allow newline here.
4367 newline The maximum number of newlines allowed in an emphasis exp.
4369 You need to reload Org or to restart Emacs after customizing this.")
4371 (defcustom org-emphasis-alist
4372 '(("*" bold)
4373 ("/" italic)
4374 ("_" underline)
4375 ("=" org-verbatim verbatim)
4376 ("~" org-code verbatim)
4377 ("+" (:strike-through t)))
4378 "Alist of characters and faces to emphasize text.
4379 Text starting and ending with a special character will be emphasized,
4380 for example *bold*, _underlined_ and /italic/. This variable sets the
4381 marker characters and the face to be used by font-lock for highlighting
4382 in Org buffers.
4384 You need to reload Org or to restart Emacs after customizing this."
4385 :group 'org-appearance
4386 :set 'org-set-emph-re
4387 :version "24.4"
4388 :package-version '(Org . "8.0")
4389 :type '(repeat
4390 (list
4391 (string :tag "Marker character")
4392 (choice
4393 (face :tag "Font-lock-face")
4394 (plist :tag "Face property list"))
4395 (option (const verbatim)))))
4397 (defvar org-protecting-blocks '("src" "example" "export")
4398 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4399 This is needed for font-lock setup.")
4401 ;;; Functions and variables from their packages
4402 ;; Declared here to avoid compiler warnings
4403 (defvar mark-active)
4405 ;; Various packages
4406 (declare-function calc-eval "calc" (str &optional separator &rest args))
4407 (declare-function calendar-forward-day "cal-move" (arg))
4408 (declare-function calendar-goto-date "cal-move" (date))
4409 (declare-function calendar-goto-today "cal-move" ())
4410 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4411 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4412 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4413 (declare-function cdlatex-tab "ext:cdlatex" ())
4414 (declare-function dired-get-filename
4415 "dired"
4416 (&optional localp no-error-if-not-filep))
4417 (declare-function iswitchb-read-buffer
4418 "iswitchb"
4419 (prompt &optional
4420 default require-match _predicate start matches-set))
4421 (declare-function org-agenda-change-all-lines
4422 "org-agenda"
4423 (newhead hdmarker &optional fixface just-this))
4424 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4425 "org-agenda"
4426 (&optional end))
4427 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4428 (declare-function org-agenda-format-item
4429 "org-agenda"
4430 (extra txt &optional level category tags dotime
4431 remove-re habitp))
4432 (declare-function org-agenda-maybe-redo "org-agenda" ())
4433 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4434 (declare-function org-agenda-save-markers-for-cut-and-paste
4435 "org-agenda"
4436 (beg end))
4437 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4438 (declare-function org-agenda-skip "org-agenda" ())
4439 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4440 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4441 (declare-function org-indent-mode "org-indent" (&optional arg))
4442 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4443 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4444 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4445 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4446 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4447 (declare-function parse-time-string "parse-time" (string))
4448 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4450 (defvar align-mode-rules-list)
4451 (defvar calc-embedded-close-formula)
4452 (defvar calc-embedded-open-formula)
4453 (defvar calc-embedded-open-mode)
4454 (defvar font-lock-unfontify-region-function)
4455 (defvar iswitchb-temp-buflist)
4456 (defvar org-agenda-tags-todo-honor-ignore-options)
4457 (defvar remember-data-file)
4458 (defvar texmathp-why)
4460 ;;;###autoload
4461 (defun turn-on-orgtbl ()
4462 "Unconditionally turn on `orgtbl-mode'."
4463 (require 'org-table)
4464 (orgtbl-mode 1))
4466 (defun org-at-table-p (&optional table-type)
4467 "Non-nil if the cursor is inside an Org table.
4468 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4469 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4470 (or (not (derived-mode-p 'org-mode))
4471 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4472 (and e (or table-type
4473 (eq 'org (org-element-property :type e))))))))
4475 (defun org-at-table.el-p ()
4476 "Non-nil when point is at a table.el table."
4477 (and (org-match-line "[ \t]*[|+]")
4478 (let ((element (org-element-at-point)))
4479 (and (eq (org-element-type element) 'table)
4480 (eq (org-element-property :type element) 'table.el)))))
4482 (defun org-at-table-hline-p ()
4483 "Non-nil when point is inside a hline in a table.
4484 Assume point is already in a table."
4485 (org-match-line org-table-hline-regexp))
4487 (defun org-table-map-tables (function &optional quietly)
4488 "Apply FUNCTION to the start of all tables in the buffer."
4489 (org-with-wide-buffer
4490 (goto-char (point-min))
4491 (while (re-search-forward org-table-any-line-regexp nil t)
4492 (unless quietly
4493 (message "Mapping tables: %d%%"
4494 (floor (* 100.0 (point)) (buffer-size))))
4495 (beginning-of-line 1)
4496 (when (and (looking-at org-table-line-regexp)
4497 ;; Exclude tables in src/example/verbatim/clocktable blocks
4498 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4499 (save-excursion (funcall function))
4500 (or (looking-at org-table-line-regexp)
4501 (forward-char 1)))
4502 (re-search-forward org-table-any-border-regexp nil 1)))
4503 (unless quietly (message "Mapping tables: done")))
4505 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4506 (declare-function org-clock-update-mode-line "org-clock" ())
4507 (declare-function org-resolve-clocks "org-clock"
4508 (&optional also-non-dangling-p prompt last-valid))
4510 (defun org-at-TBLFM-p (&optional pos)
4511 "Non-nil when point (or POS) is in #+TBLFM line."
4512 (save-excursion
4513 (goto-char (or pos (point)))
4514 (beginning-of-line)
4515 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4516 (eq (org-element-type (org-element-at-point)) 'table))))
4518 (defvar org-clock-start-time)
4519 (defvar org-clock-marker (make-marker)
4520 "Marker recording the last clock-in.")
4521 (defvar org-clock-hd-marker (make-marker)
4522 "Marker recording the last clock-in, but the headline position.")
4523 (defvar org-clock-heading ""
4524 "The heading of the current clock entry.")
4525 (defun org-clock-is-active ()
4526 "Return the buffer where the clock is currently running.
4527 Return nil if no clock is running."
4528 (marker-buffer org-clock-marker))
4530 (defun org-check-running-clock ()
4531 "Check if the current buffer contains the running clock.
4532 If yes, offer to stop it and to save the buffer with the changes."
4533 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4534 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4535 (buffer-name))))
4536 (org-clock-out)
4537 (when (y-or-n-p "Save changed buffer?")
4538 (save-buffer))))
4540 (defun org-clocktable-try-shift (dir n)
4541 "Check if this line starts a clock table, if yes, shift the time block."
4542 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4543 (org-clocktable-shift dir n)))
4545 ;;;###autoload
4546 (defun org-clock-persistence-insinuate ()
4547 "Set up hooks for clock persistence."
4548 (require 'org-clock)
4549 (add-hook 'org-mode-hook 'org-clock-load)
4550 (add-hook 'kill-emacs-hook 'org-clock-save))
4552 (defgroup org-archive nil
4553 "Options concerning archiving in Org mode."
4554 :tag "Org Archive"
4555 :group 'org-structure)
4557 (defcustom org-archive-location "%s_archive::"
4558 "The location where subtrees should be archived.
4560 The value of this variable is a string, consisting of two parts,
4561 separated by a double-colon. The first part is a filename and
4562 the second part is a headline.
4564 When the filename is omitted, archiving happens in the same file.
4565 %s in the filename will be replaced by the current file
4566 name (without the directory part). Archiving to a different file
4567 is useful to keep archived entries from contributing to the
4568 Org Agenda.
4570 The archived entries will be filed as subtrees of the specified
4571 headline. When the headline is omitted, the subtrees are simply
4572 filed away at the end of the file, as top-level entries. Also in
4573 the heading you can use %s to represent the file name, this can be
4574 useful when using the same archive for a number of different files.
4576 Here are a few examples:
4577 \"%s_archive::\"
4578 If the current file is Projects.org, archive in file
4579 Projects.org_archive, as top-level trees. This is the default.
4581 \"::* Archived Tasks\"
4582 Archive in the current file, under the top-level headline
4583 \"* Archived Tasks\".
4585 \"~/org/archive.org::\"
4586 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4588 \"~/org/archive.org::* From %s\"
4589 Archive in file ~/org/archive.org (absolute path), under headlines
4590 \"From FILENAME\" where file name is the current file name.
4592 \"~/org/datetree.org::datetree/* Finished Tasks\"
4593 The \"datetree/\" string is special, signifying to archive
4594 items to the datetree. Items are placed in either the CLOSED
4595 date of the item, or the current date if there is no CLOSED date.
4596 The heading will be a subentry to the current date. There doesn't
4597 need to be a heading, but there always needs to be a slash after
4598 datetree. For example, to store archived items directly in the
4599 datetree, use \"~/org/datetree.org::datetree/\".
4601 \"basement::** Finished Tasks\"
4602 Archive in file ./basement (relative path), as level 3 trees
4603 below the level 2 heading \"** Finished Tasks\".
4605 You may set this option on a per-file basis by adding to the buffer a
4606 line like
4608 #+ARCHIVE: basement::** Finished Tasks
4610 You may also define it locally for a subtree by setting an ARCHIVE property
4611 in the entry. If such a property is found in an entry, or anywhere up
4612 the hierarchy, it will be used."
4613 :group 'org-archive
4614 :type 'string)
4616 (defcustom org-agenda-skip-archived-trees t
4617 "Non-nil means the agenda will skip any items located in archived trees.
4618 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4619 variable is no longer recommended, you should leave it at the value t.
4620 Instead, use the key `v' to cycle the archives-mode in the agenda."
4621 :group 'org-archive
4622 :group 'org-agenda-skip
4623 :type 'boolean)
4625 (defcustom org-columns-skip-archived-trees t
4626 "Non-nil means ignore archived trees when creating column view."
4627 :group 'org-archive
4628 :group 'org-properties
4629 :type 'boolean)
4631 (defcustom org-cycle-open-archived-trees nil
4632 "Non-nil means `org-cycle' will open archived trees.
4633 An archived tree is a tree marked with the tag ARCHIVE.
4634 When nil, archived trees will stay folded. You can still open them with
4635 normal outline commands like `show-all', but not with the cycling commands."
4636 :group 'org-archive
4637 :group 'org-cycle
4638 :type 'boolean)
4640 (defcustom org-sparse-tree-open-archived-trees nil
4641 "Non-nil means sparse tree construction shows matches in archived trees.
4642 When nil, matches in these trees are highlighted, but the trees are kept in
4643 collapsed state."
4644 :group 'org-archive
4645 :group 'org-sparse-trees
4646 :type 'boolean)
4648 (defcustom org-sparse-tree-default-date-type nil
4649 "The default date type when building a sparse tree.
4650 When this is nil, a date is a scheduled or a deadline timestamp.
4651 Otherwise, these types are allowed:
4653 all: all timestamps
4654 active: only active timestamps (<...>)
4655 inactive: only inactive timestamps ([...])
4656 scheduled: only scheduled timestamps
4657 deadline: only deadline timestamps"
4658 :type '(choice (const :tag "Scheduled or deadline" nil)
4659 (const :tag "All timestamps" all)
4660 (const :tag "Only active timestamps" active)
4661 (const :tag "Only inactive timestamps" inactive)
4662 (const :tag "Only scheduled timestamps" scheduled)
4663 (const :tag "Only deadline timestamps" deadline)
4664 (const :tag "Only closed timestamps" closed))
4665 :version "26.1"
4666 :package-version '(Org . "8.3")
4667 :group 'org-sparse-trees)
4669 (defun org-cycle-hide-archived-subtrees (state)
4670 "Re-hide all archived subtrees after a visibility state change.
4671 STATE should be one of the symbols listed in the docstring of
4672 `org-cycle-hook'."
4673 (when (and (not org-cycle-open-archived-trees)
4674 (not (memq state '(overview folded))))
4675 (save-excursion
4676 (let* ((globalp (memq state '(contents all)))
4677 (beg (if globalp (point-min) (point)))
4678 (end (if globalp (point-max) (org-end-of-subtree t))))
4679 (org-hide-archived-subtrees beg end)
4680 (goto-char beg)
4681 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4682 (message "%s" (substitute-command-keys
4683 "Subtree is archived and stays closed. Use \
4684 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4686 (defun org-force-cycle-archived ()
4687 "Cycle subtree even if it is archived."
4688 (interactive)
4689 (setq this-command 'org-cycle)
4690 (let ((org-cycle-open-archived-trees t))
4691 (call-interactively 'org-cycle)))
4693 (defun org-hide-archived-subtrees (beg end)
4694 "Re-hide all archived subtrees after a visibility state change."
4695 (org-with-wide-buffer
4696 (let ((case-fold-search nil)
4697 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4698 (goto-char beg)
4699 ;; Include headline point is currently on.
4700 (beginning-of-line)
4701 (while (and (< (point) end) (re-search-forward re end t))
4702 (when (member org-archive-tag (org-get-tags))
4703 (org-flag-subtree t)
4704 (org-end-of-subtree t))))))
4706 (declare-function outline-end-of-heading "outline" ())
4707 (declare-function outline-flag-region "outline" (from to flag))
4708 (defun org-flag-subtree (flag)
4709 (save-excursion
4710 (org-back-to-heading t)
4711 (outline-end-of-heading)
4712 (outline-flag-region (point)
4713 (progn (org-end-of-subtree t) (point))
4714 flag)))
4716 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4718 ;; Declare Column View Code
4720 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4721 (declare-function org-columns-compute "org-colview" (property))
4723 ;; Declare ID code
4725 (declare-function org-id-store-link "org-id")
4726 (declare-function org-id-locations-load "org-id")
4727 (declare-function org-id-locations-save "org-id")
4728 (defvar org-id-track-globally)
4730 ;;; Variables for pre-computed regular expressions, all buffer local
4732 (defvar-local org-todo-regexp nil
4733 "Matches any of the TODO state keywords.
4734 Since TODO keywords are case-sensitive, `case-fold-search' is
4735 expected to be bound to nil when matching against this regexp.")
4737 (defvar-local org-not-done-regexp nil
4738 "Matches any of the TODO state keywords except the last one.
4739 Since TODO keywords are case-sensitive, `case-fold-search' is
4740 expected to be bound to nil when matching against this regexp.")
4742 (defvar-local org-not-done-heading-regexp nil
4743 "Matches a TODO headline that is not done.
4744 Since TODO keywords are case-sensitive, `case-fold-search' is
4745 expected to be bound to nil when matching against this regexp.")
4747 (defvar-local org-todo-line-regexp nil
4748 "Matches a headline and puts TODO state into group 2 if present.
4749 Since TODO keywords are case-sensitive, `case-fold-search' is
4750 expected to be bound to nil when matching against this regexp.")
4752 (defvar-local org-complex-heading-regexp nil
4753 "Matches a headline and puts everything into groups:
4755 group 1: Stars
4756 group 2: The TODO keyword, maybe
4757 group 3: Priority cookie
4758 group 4: True headline
4759 group 5: Tags
4761 Since TODO keywords are case-sensitive, `case-fold-search' is
4762 expected to be bound to nil when matching against this regexp.")
4764 (defvar-local org-complex-heading-regexp-format nil
4765 "Printf format to make regexp to match an exact headline.
4766 This regexp will match the headline of any node which has the
4767 exact headline text that is put into the format, but may have any
4768 TODO state, priority and tags.")
4770 (defvar-local org-todo-line-tags-regexp nil
4771 "Matches a headline and puts TODO state into group 2 if present.
4772 Also put tags into group 4 if tags are present.")
4774 (defconst org-plain-time-of-day-regexp
4775 (concat
4776 "\\(\\<[012]?[0-9]"
4777 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4778 "\\(--?"
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\)?")
4782 "Regular expression to match a plain time or time range.
4783 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4784 groups carry important information:
4785 0 the full match
4786 1 the first time, range or not
4787 8 the second time, if it is a range.")
4789 (defconst org-plain-time-extension-regexp
4790 (concat
4791 "\\(\\<[012]?[0-9]"
4792 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4793 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4794 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4795 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4796 groups carry important information:
4797 0 the full match
4798 7 hours of duration
4799 9 minutes of duration")
4801 (defconst org-stamp-time-of-day-regexp
4802 (concat
4803 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4804 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4805 "\\(--?"
4806 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4807 "Regular expression to match a timestamp time or time range.
4808 After a match, the following groups carry important information:
4809 0 the full match
4810 1 date plus weekday, for back referencing to make sure both times are on the same day
4811 2 the first time, range or not
4812 4 the second time, if it is a range.")
4814 (defconst org-startup-options
4815 '(("fold" org-startup-folded t)
4816 ("overview" org-startup-folded t)
4817 ("nofold" org-startup-folded nil)
4818 ("showall" org-startup-folded nil)
4819 ("showeverything" org-startup-folded showeverything)
4820 ("content" org-startup-folded content)
4821 ("indent" org-startup-indented t)
4822 ("noindent" org-startup-indented nil)
4823 ("hidestars" org-hide-leading-stars t)
4824 ("showstars" org-hide-leading-stars nil)
4825 ("odd" org-odd-levels-only t)
4826 ("oddeven" org-odd-levels-only nil)
4827 ("align" org-startup-align-all-tables t)
4828 ("noalign" org-startup-align-all-tables nil)
4829 ("inlineimages" org-startup-with-inline-images t)
4830 ("noinlineimages" org-startup-with-inline-images nil)
4831 ("latexpreview" org-startup-with-latex-preview t)
4832 ("nolatexpreview" org-startup-with-latex-preview nil)
4833 ("customtime" org-display-custom-times t)
4834 ("logdone" org-log-done time)
4835 ("lognotedone" org-log-done note)
4836 ("nologdone" org-log-done nil)
4837 ("lognoteclock-out" org-log-note-clock-out t)
4838 ("nolognoteclock-out" org-log-note-clock-out nil)
4839 ("logrepeat" org-log-repeat state)
4840 ("lognoterepeat" org-log-repeat note)
4841 ("logdrawer" org-log-into-drawer t)
4842 ("nologdrawer" org-log-into-drawer nil)
4843 ("logstatesreversed" org-log-states-order-reversed t)
4844 ("nologstatesreversed" org-log-states-order-reversed nil)
4845 ("nologrepeat" org-log-repeat nil)
4846 ("logreschedule" org-log-reschedule time)
4847 ("lognotereschedule" org-log-reschedule note)
4848 ("nologreschedule" org-log-reschedule nil)
4849 ("logredeadline" org-log-redeadline time)
4850 ("lognoteredeadline" org-log-redeadline note)
4851 ("nologredeadline" org-log-redeadline nil)
4852 ("logrefile" org-log-refile time)
4853 ("lognoterefile" org-log-refile note)
4854 ("nologrefile" org-log-refile nil)
4855 ("fninline" org-footnote-define-inline t)
4856 ("nofninline" org-footnote-define-inline nil)
4857 ("fnlocal" org-footnote-section nil)
4858 ("fnauto" org-footnote-auto-label t)
4859 ("fnprompt" org-footnote-auto-label nil)
4860 ("fnconfirm" org-footnote-auto-label confirm)
4861 ("fnplain" org-footnote-auto-label plain)
4862 ("fnadjust" org-footnote-auto-adjust t)
4863 ("nofnadjust" org-footnote-auto-adjust nil)
4864 ("constcgs" constants-unit-system cgs)
4865 ("constSI" constants-unit-system SI)
4866 ("noptag" org-tag-persistent-alist nil)
4867 ("hideblocks" org-hide-block-startup t)
4868 ("nohideblocks" org-hide-block-startup nil)
4869 ("beamer" org-startup-with-beamer-mode t)
4870 ("entitiespretty" org-pretty-entities t)
4871 ("entitiesplain" org-pretty-entities nil))
4872 "Variable associated with STARTUP options for org-mode.
4873 Each element is a list of three items: the startup options (as written
4874 in the #+STARTUP line), the corresponding variable, and the value to set
4875 this variable to if the option is found. An optional forth element PUSH
4876 means to push this value onto the list in the variable.")
4878 (defcustom org-group-tags t
4879 "When non-nil (the default), use group tags.
4880 This can be turned on/off through `org-toggle-tags-groups'."
4881 :group 'org-tags
4882 :group 'org-startup
4883 :type 'boolean)
4885 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4887 (defun org-toggle-tags-groups ()
4888 "Toggle support for group tags.
4889 Support for group tags is controlled by the option
4890 `org-group-tags', which is non-nil by default."
4891 (interactive)
4892 (setq org-group-tags (not org-group-tags))
4893 (cond ((and (derived-mode-p 'org-agenda-mode)
4894 org-group-tags)
4895 (org-agenda-redo))
4896 ((derived-mode-p 'org-mode)
4897 (let ((org-inhibit-startup t)) (org-mode))))
4898 (message "Groups tags support has been turned %s"
4899 (if org-group-tags "on" "off")))
4901 (defun org-set-regexps-and-options (&optional tags-only)
4902 "Precompute regular expressions used in the current buffer.
4903 When optional argument TAGS-ONLY is non-nil, only compute tags
4904 related expressions."
4905 (when (derived-mode-p 'org-mode)
4906 (let ((alist (org--setup-collect-keywords
4907 (org-make-options-regexp
4908 (append '("FILETAGS" "TAGS" "SETUPFILE")
4909 (and (not tags-only)
4910 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4911 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4912 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4913 ;; Startup options. Get this early since it does change
4914 ;; behavior for other options (e.g., tags).
4915 (let ((startup (cdr (assq 'startup alist))))
4916 (dolist (option startup)
4917 (let ((entry (assoc-string option org-startup-options t)))
4918 (when entry
4919 (let ((var (nth 1 entry))
4920 (val (nth 2 entry)))
4921 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4922 (unless (listp (symbol-value var))
4923 (set (make-local-variable var) nil))
4924 (add-to-list var val)))))))
4925 (setq-local org-file-tags
4926 (mapcar #'org-add-prop-inherited
4927 (cdr (assq 'filetags alist))))
4928 (setq org-current-tag-alist
4929 (append org-tag-persistent-alist
4930 (let ((tags (cdr (assq 'tags alist))))
4931 (if tags (org-tag-string-to-alist tags)
4932 org-tag-alist))))
4933 (setq org-tag-groups-alist
4934 (org-tag-alist-to-groups org-current-tag-alist))
4935 (unless tags-only
4936 ;; File properties.
4937 (setq-local org-file-properties (cdr (assq 'property alist)))
4938 ;; Archive location.
4939 (let ((archive (cdr (assq 'archive alist))))
4940 (when archive (setq-local org-archive-location archive)))
4941 ;; Category.
4942 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4943 (when cat
4944 (setq-local org-category (intern cat))
4945 (setq-local org-file-properties
4946 (org--update-property-plist
4947 "CATEGORY" cat org-file-properties))))
4948 ;; Columns.
4949 (let ((column (cdr (assq 'columns alist))))
4950 (when column (setq-local org-columns-default-format column)))
4951 ;; Constants.
4952 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4953 ;; Link abbreviations.
4954 (let ((links (cdr (assq 'link alist))))
4955 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4956 ;; Priorities.
4957 (let ((priorities (cdr (assq 'priorities alist))))
4958 (when priorities
4959 (setq-local org-highest-priority (nth 0 priorities))
4960 (setq-local org-lowest-priority (nth 1 priorities))
4961 (setq-local org-default-priority (nth 2 priorities))))
4962 ;; Scripts.
4963 (let ((scripts (assq 'scripts alist)))
4964 (when scripts
4965 (setq-local org-use-sub-superscripts (cdr scripts))))
4966 ;; TODO keywords.
4967 (setq-local org-todo-kwd-alist nil)
4968 (setq-local org-todo-key-alist nil)
4969 (setq-local org-todo-key-trigger nil)
4970 (setq-local org-todo-keywords-1 nil)
4971 (setq-local org-done-keywords nil)
4972 (setq-local org-todo-heads nil)
4973 (setq-local org-todo-sets nil)
4974 (setq-local org-todo-log-states nil)
4975 (let ((todo-sequences
4976 (or (nreverse (cdr (assq 'todo alist)))
4977 (let ((d (default-value 'org-todo-keywords)))
4978 (if (not (stringp (car d))) d
4979 ;; XXX: Backward compatibility code.
4980 (list (cons org-todo-interpretation d)))))))
4981 (dolist (sequence todo-sequences)
4982 (let* ((sequence (or (run-hook-with-args-until-success
4983 'org-todo-setup-filter-hook sequence)
4984 sequence))
4985 (sequence-type (car sequence))
4986 (keywords (cdr sequence))
4987 (sep (member "|" keywords))
4988 names alist)
4989 (dolist (k (remove "|" keywords))
4990 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4992 (error "Invalid TODO keyword %s" k))
4993 (let ((name (match-string 1 k))
4994 (key (match-string 2 k))
4995 (log (org-extract-log-state-settings k)))
4996 (push name names)
4997 (push (cons name (and key (string-to-char key))) alist)
4998 (when log (push log org-todo-log-states))))
4999 (let* ((names (nreverse names))
5000 (done (if sep (org-remove-keyword-keys (cdr sep))
5001 (last names)))
5002 (head (car names))
5003 (tail (list sequence-type head (car done) (org-last done))))
5004 (add-to-list 'org-todo-heads head 'append)
5005 (push names org-todo-sets)
5006 (setq org-done-keywords (append org-done-keywords done nil))
5007 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5008 (setq org-todo-key-alist
5009 (append org-todo-key-alist
5010 (and alist
5011 (append '((:startgroup))
5012 (nreverse alist)
5013 '((:endgroup))))))
5014 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5015 (setq org-todo-sets (nreverse org-todo-sets)
5016 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5017 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5018 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5019 ;; Compute the regular expressions and other local variables.
5020 ;; Using `org-outline-regexp-bol' would complicate them much,
5021 ;; because of the fixed white space at the end of that string.
5022 (unless org-done-keywords
5023 (setq org-done-keywords
5024 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5025 (setq org-not-done-keywords
5026 (org-delete-all org-done-keywords
5027 (copy-sequence org-todo-keywords-1))
5028 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5029 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5030 org-not-done-heading-regexp
5031 (format org-heading-keyword-regexp-format org-not-done-regexp)
5032 org-todo-line-regexp
5033 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5034 org-complex-heading-regexp
5035 (concat "^\\(\\*+\\)"
5036 "\\(?: +" org-todo-regexp "\\)?"
5037 "\\(?: +\\(\\[#.\\]\\)\\)?"
5038 "\\(?: +\\(.*?\\)\\)??"
5039 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5040 "[ \t]*$")
5041 org-complex-heading-regexp-format
5042 (concat "^\\(\\*+\\)"
5043 "\\(?: +" org-todo-regexp "\\)?"
5044 "\\(?: +\\(\\[#.\\]\\)\\)?"
5045 "\\(?: +"
5046 ;; Stats cookies can be stuck to body.
5047 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5048 "\\(%s\\)"
5049 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5050 "\\)"
5051 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5052 "[ \t]*$")
5053 org-todo-line-tags-regexp
5054 (concat "^\\(\\*+\\)"
5055 "\\(?: +" org-todo-regexp "\\)?"
5056 "\\(?: +\\(.*?\\)\\)??"
5057 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5058 "[ \t]*$"))
5059 (org-compute-latex-and-related-regexp)))))
5061 (defun org--setup-collect-keywords (regexp &optional files alist)
5062 "Return setup keywords values as an alist.
5064 REGEXP matches a subset of setup keywords. FILES is a list of
5065 file names already visited. It is used to avoid circular setup
5066 files. ALIST, when non-nil, is the alist computed so far.
5068 Return value contains the following keys: `archive', `category',
5069 `columns', `constants', `filetags', `link', `priorities',
5070 `property', `scripts', `startup', `tags' and `todo'."
5071 (org-with-wide-buffer
5072 (goto-char (point-min))
5073 (let ((case-fold-search t))
5074 (while (re-search-forward regexp nil t)
5075 (let ((element (org-element-at-point)))
5076 (when (eq (org-element-type element) 'keyword)
5077 (let ((key (org-element-property :key element))
5078 (value (org-element-property :value element)))
5079 (cond
5080 ((equal key "ARCHIVE")
5081 (when (org-string-nw-p value)
5082 (push (cons 'archive value) alist)))
5083 ((equal key "CATEGORY") (push (cons 'category value) alist))
5084 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5085 ((equal key "CONSTANTS")
5086 (let* ((constants (assq 'constants alist))
5087 (store (cdr constants)))
5088 (dolist (pair (split-string value))
5089 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5090 pair)
5091 (let* ((name (match-string 1 pair))
5092 (value (match-string 2 pair))
5093 (old (assoc name store)))
5094 (if old (setcdr old value)
5095 (push (cons name value) store)))))
5096 (if constants (setcdr constants store)
5097 (push (cons 'constants store) alist))))
5098 ((equal key "FILETAGS")
5099 (when (org-string-nw-p value)
5100 (let ((old (assq 'filetags alist))
5101 (new (apply #'nconc
5102 (mapcar (lambda (x) (org-split-string x ":"))
5103 (split-string value)))))
5104 (if old (setcdr old (append new (cdr old)))
5105 (push (cons 'filetags new) alist)))))
5106 ((equal key "LINK")
5107 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5108 (let ((links (assq 'link alist))
5109 (pair (cons (match-string-no-properties 1 value)
5110 (match-string-no-properties 2 value))))
5111 (if links (push pair (cdr links))
5112 (push (list 'link pair) alist)))))
5113 ((equal key "OPTIONS")
5114 (when (and (org-string-nw-p value)
5115 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5116 (push (cons 'scripts (read (match-string 1 value))) alist)))
5117 ((equal key "PRIORITIES")
5118 (push (cons 'priorities
5119 (let ((prio (split-string value)))
5120 (if (< (length prio) 3) '(?A ?C ?B)
5121 (mapcar #'string-to-char prio))))
5122 alist))
5123 ((equal key "PROPERTY")
5124 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5125 (let* ((property (assq 'property alist))
5126 (value (org--update-property-plist
5127 (match-string-no-properties 1 value)
5128 (match-string-no-properties 2 value)
5129 (cdr property))))
5130 (if property (setcdr property value)
5131 (push (cons 'property value) alist)))))
5132 ((equal key "STARTUP")
5133 (let ((startup (assq 'startup alist)))
5134 (if startup
5135 (setcdr startup
5136 (append (cdr startup) (split-string value)))
5137 (push (cons 'startup (split-string value)) alist))))
5138 ((equal key "TAGS")
5139 (let ((tag-cell (assq 'tags alist)))
5140 (if tag-cell
5141 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5142 (push (cons 'tags value) alist))))
5143 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5144 (let ((todo (assq 'todo alist))
5145 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5146 (split-string value))))
5147 (if todo (push value (cdr todo))
5148 (push (list 'todo value) alist))))
5149 ((equal key "SETUPFILE")
5150 (unless buffer-read-only ; Do not check in Gnus messages.
5151 (let ((f (and (org-string-nw-p value)
5152 (expand-file-name
5153 (org-unbracket-string "\"" "\"" value)))))
5154 (when (and f (file-readable-p f) (not (member f files)))
5155 (with-temp-buffer
5156 (setq default-directory (file-name-directory f))
5157 (insert-file-contents f)
5158 (setq alist
5159 ;; Fake Org mode to benefit from cache
5160 ;; without recurring needlessly.
5161 (let ((major-mode 'org-mode))
5162 (org--setup-collect-keywords
5163 regexp (cons f files) alist)))))))))))))))
5164 alist)
5166 (defun org-tag-string-to-alist (s)
5167 "Return tag alist associated to string S.
5168 S is a value for TAGS keyword or produced with
5169 `org-tag-alist-to-string'. Return value is an alist suitable for
5170 `org-tag-alist' or `org-tag-persistent-alist'."
5171 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5172 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5173 "\\|{.+?}\\)" ; regular expression
5174 "\\(?:(\\(.\\))\\)?\\'"))
5175 alist group-flag)
5176 (dolist (tokens lines (cdr (nreverse alist)))
5177 (push '(:newline) alist)
5178 (while tokens
5179 (let ((token (pop tokens)))
5180 (pcase token
5181 ("{"
5182 (push '(:startgroup) alist)
5183 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5184 ("}"
5185 (push '(:endgroup) alist)
5186 (setq group-flag nil))
5187 ("["
5188 (push '(:startgrouptag) alist)
5189 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5190 ("]"
5191 (push '(:endgrouptag) alist)
5192 (setq group-flag nil))
5193 (":"
5194 (push '(:grouptags) alist))
5195 ((guard (string-match tag-re token))
5196 (let ((tag (match-string 1 token))
5197 (key (and (match-beginning 2)
5198 (string-to-char (match-string 2 token)))))
5199 ;; Push all tags in groups, no matter if they already
5200 ;; appear somewhere else in the list.
5201 (when (or group-flag (not (assoc tag alist)))
5202 (push (cons tag key) alist))))))))))
5204 (defun org-tag-alist-to-string (alist &optional skip-key)
5205 "Return tag string associated to ALIST.
5207 ALIST is an alist, as defined in `org-tag-alist' or
5208 `org-tag-persistent-alist', or produced with
5209 `org-tag-string-to-alist'.
5211 Return value is a string suitable as a value for \"TAGS\"
5212 keyword.
5214 When optional argument SKIP-KEY is non-nil, skip selection keys
5215 next to tags."
5216 (mapconcat (lambda (token)
5217 (pcase token
5218 (`(:startgroup) "{")
5219 (`(:endgroup) "}")
5220 (`(:startgrouptag) "[")
5221 (`(:endgrouptag) "]")
5222 (`(:grouptags) ":")
5223 (`(:newline) "\\n")
5224 ((and
5225 (guard (not skip-key))
5226 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5227 (format "%s(%c)" tag key))
5228 (`(,(and tag (pred stringp)) . ,_) tag)
5229 (_ (user-error "Invalid tag token: %S" token))))
5230 alist
5231 " "))
5233 (defun org-tag-alist-to-groups (alist)
5234 "Return group alist from tag ALIST.
5235 ALIST is an alist, as defined in `org-tag-alist' or
5236 `org-tag-persistent-alist', or produced with
5237 `org-tag-string-to-alist'. Return value is an alist following
5238 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5239 a string, summarizing TAGS, as a list of strings."
5240 (let (groups group-status current-group)
5241 (dolist (token alist (nreverse groups))
5242 (pcase token
5243 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5244 (`(,(or :endgroup :endgrouptag))
5245 (when (eq group-status 'append)
5246 (push (nreverse current-group) groups))
5247 (setq group-status nil))
5248 (`(:grouptags) (setq group-status 'append))
5249 ((and `(,tag . ,_) (guard group-status))
5250 (if (eq group-status 'append) (push tag current-group)
5251 (setq current-group (list tag))))
5252 (_ nil)))))
5254 (defvar org--file-cache (make-hash-table :test #'equal)
5255 "Hash table to store contents of files referenced via a URL.
5256 This is the cache of file URLs read using `org-file-contents'.")
5258 (defun org-reset-file-cache ()
5259 "Reset the cache of files downloaded by `org-file-contents'."
5260 (clrhash org--file-cache))
5262 (defun org-file-url-p (file)
5263 "Non-nil if FILE is a URL."
5264 (require 'ffap)
5265 (string-match-p ffap-url-regexp file))
5267 (defun org-file-contents (file &optional noerror nocache)
5268 "Return the contents of FILE, as a string.
5270 FILE can be a file name or URL.
5272 If FILE is a URL, download the contents. If the URL contents are
5273 already cached in the `org--file-cache' hash table, the download step
5274 is skipped.
5276 If NOERROR is non-nil, ignore the error when unable to read the FILE
5277 from file or URL.
5279 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5280 is available. This option applies only if FILE is a URL."
5281 (let* ((is-url (org-file-url-p file))
5282 (cache (and is-url
5283 (not nocache)
5284 (gethash file org--file-cache))))
5285 (cond
5286 (cache)
5287 (is-url
5288 (with-current-buffer (url-retrieve-synchronously file)
5289 (goto-char (point-min))
5290 ;; Move point to after the url-retrieve header.
5291 (search-forward "\n\n" nil :move)
5292 ;; Search for the success code only in the url-retrieve header.
5293 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5294 ;; Update the cache `org--file-cache' and return contents.
5295 (puthash file
5296 (buffer-substring-no-properties (point) (point-max))
5297 org--file-cache)
5298 (funcall (if noerror #'message #'user-error)
5299 "Unable to fetch file from %S"
5300 file))))
5302 (with-temp-buffer
5303 (condition-case err
5304 (progn
5305 (insert-file-contents file)
5306 (buffer-string))
5307 (file-error
5308 (funcall (if noerror #'message #'user-error)
5309 (error-message-string err)))))))))
5311 (defun org-extract-log-state-settings (x)
5312 "Extract the log state setting from a TODO keyword string.
5313 This will extract info from a string like \"WAIT(w@/!)\"."
5314 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5315 (let ((kw (match-string 1 x))
5316 (log1 (and (match-end 3) (match-string 3 x)))
5317 (log2 (and (match-end 4) (match-string 4 x))))
5318 (and (or log1 log2)
5319 (list kw
5320 (and log1 (if (equal log1 "!") 'time 'note))
5321 (and log2 (if (equal log2 "!") 'time 'note)))))))
5323 (defun org-remove-keyword-keys (list)
5324 "Remove a pair of parenthesis at the end of each string in LIST."
5325 (mapcar (lambda (x)
5326 (if (string-match "(.*)$" x)
5327 (substring x 0 (match-beginning 0))
5329 list))
5331 (defun org-assign-fast-keys (alist)
5332 "Assign fast keys to a keyword-key alist.
5333 Respect keys that are already there."
5334 (let (new e (alt ?0))
5335 (while (setq e (pop alist))
5336 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5337 (cdr e)) ;; Key already assigned.
5338 (push e new)
5339 (let ((clist (string-to-list (downcase (car e))))
5340 (used (append new alist)))
5341 (when (= (car clist) ?@)
5342 (pop clist))
5343 (while (and clist (rassoc (car clist) used))
5344 (pop clist))
5345 (unless clist
5346 (while (rassoc alt used)
5347 (cl-incf alt)))
5348 (push (cons (car e) (or (car clist) alt)) new))))
5349 (nreverse new)))
5351 ;;; Some variables used in various places
5353 (defvar org-window-configuration nil
5354 "Used in various places to store a window configuration.")
5355 (defvar org-selected-window nil
5356 "Used in various places to store a window configuration.")
5357 (defvar org-finish-function nil
5358 "Function to be called when `C-c C-c' is used.
5359 This is for getting out of special buffers like capture.")
5360 (defvar org-last-state)
5362 ;; Defined somewhere in this file, but used before definition.
5363 (defvar org-entities) ;; defined in org-entities.el
5364 (defvar org-struct-menu)
5365 (defvar org-org-menu)
5366 (defvar org-tbl-menu)
5368 ;;;; Define the Org mode
5370 ;; We use a before-change function to check if a table might need
5371 ;; an update.
5372 (defvar org-table-may-need-update t
5373 "Indicates that a table might need an update.
5374 This variable is set by `org-before-change-function'.
5375 `org-table-align' sets it back to nil.")
5376 (defun org-before-change-function (_beg _end)
5377 "Every change indicates that a table might need an update."
5378 (setq org-table-may-need-update t))
5379 (defvar org-mode-map)
5380 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5381 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5382 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5383 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5384 (defvar org-table-buffer-is-an nil)
5386 (defvar bidi-paragraph-direction)
5387 (defvar buffer-face-mode-face)
5389 (require 'outline)
5391 ;; Other stuff we need.
5392 (require 'time-date)
5393 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5394 (require 'easymenu)
5395 (autoload 'easy-menu-add "easymenu")
5396 (require 'overlay)
5398 ;; (require 'org-macs) moved higher up in the file before it is first used
5399 (require 'org-entities)
5400 ;; (require 'org-compat) moved higher up in the file before it is first used
5401 (require 'org-faces)
5402 (require 'org-list)
5403 (require 'org-pcomplete)
5404 (require 'org-src)
5405 (require 'org-footnote)
5406 (require 'org-macro)
5408 ;; babel
5409 (require 'ob)
5411 ;;;###autoload
5412 (define-derived-mode org-mode outline-mode "Org"
5413 "Outline-based notes management and organizer, alias
5414 \"Carsten's outline-mode for keeping track of everything.\"
5416 Org mode develops organizational tasks around a NOTES file which
5417 contains information about projects as plain text. Org mode is
5418 implemented on top of Outline mode, which is ideal to keep the content
5419 of large files well structured. It supports ToDo items, deadlines and
5420 time stamps, which magically appear in the diary listing of the Emacs
5421 calendar. Tables are easily created with a built-in table editor.
5422 Plain text URL-like links connect to websites, emails (VM), Usenet
5423 messages (Gnus), BBDB entries, and any files related to the project.
5424 For printing and sharing of notes, an Org file (or a part of it)
5425 can be exported as a structured ASCII or HTML file.
5427 The following commands are available:
5429 \\{org-mode-map}"
5431 ;; Get rid of Outline menus, they are not needed
5432 ;; Need to do this here because define-derived-mode sets up
5433 ;; the keymap so late. Still, it is a waste to call this each time
5434 ;; we switch another buffer into Org mode.
5435 (define-key org-mode-map [menu-bar headings] 'undefined)
5436 (define-key org-mode-map [menu-bar hide] 'undefined)
5437 (define-key org-mode-map [menu-bar show] 'undefined)
5439 (org-load-modules-maybe)
5440 (org-install-agenda-files-menu)
5441 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5442 (add-to-invisibility-spec '(org-cwidth))
5443 (add-to-invisibility-spec '(org-hide-block . t))
5444 (setq-local outline-regexp org-outline-regexp)
5445 (setq-local outline-level 'org-outline-level)
5446 (setq bidi-paragraph-direction 'left-to-right)
5447 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5448 (unless org-display-table
5449 (setq org-display-table (make-display-table)))
5450 (set-display-table-slot
5451 org-display-table 4
5452 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5453 org-ellipsis)))
5454 (setq buffer-display-table org-display-table))
5455 (org-set-regexps-and-options)
5456 (org-set-font-lock-defaults)
5457 (when (and org-tag-faces (not org-tags-special-faces-re))
5458 ;; tag faces set outside customize.... force initialization.
5459 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5460 ;; Calc embedded
5461 (setq-local calc-embedded-open-mode "# ")
5462 ;; Modify a few syntax entries
5463 (modify-syntax-entry ?@ "w")
5464 (modify-syntax-entry ?\" "\"")
5465 (modify-syntax-entry ?\\ "_")
5466 (modify-syntax-entry ?~ "_")
5467 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5468 ;; Activate before-change-function
5469 (setq-local org-table-may-need-update t)
5470 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5471 ;; Check for running clock before killing a buffer
5472 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5473 ;; Initialize macros templates.
5474 (org-macro-initialize-templates)
5475 ;; Initialize radio targets.
5476 (org-update-radio-target-regexp)
5477 ;; Indentation.
5478 (setq-local indent-line-function 'org-indent-line)
5479 (setq-local indent-region-function 'org-indent-region)
5480 ;; Filling and auto-filling.
5481 (org-setup-filling)
5482 ;; Comments.
5483 (org-setup-comments-handling)
5484 ;; Initialize cache.
5485 (org-element-cache-reset)
5486 ;; Beginning/end of defun
5487 (setq-local beginning-of-defun-function 'org-backward-element)
5488 (setq-local end-of-defun-function
5489 (lambda ()
5490 (if (not (org-at-heading-p))
5491 (org-forward-element)
5492 (org-forward-element)
5493 (forward-char -1))))
5494 ;; Next error for sparse trees
5495 (setq-local next-error-function 'org-occur-next-match)
5496 ;; Make sure dependence stuff works reliably, even for users who set it
5497 ;; too late :-(
5498 (if org-enforce-todo-dependencies
5499 (add-hook 'org-blocker-hook
5500 'org-block-todo-from-children-or-siblings-or-parent)
5501 (remove-hook 'org-blocker-hook
5502 'org-block-todo-from-children-or-siblings-or-parent))
5503 (if org-enforce-todo-checkbox-dependencies
5504 (add-hook 'org-blocker-hook
5505 'org-block-todo-from-checkboxes)
5506 (remove-hook 'org-blocker-hook
5507 'org-block-todo-from-checkboxes))
5509 ;; Align options lines
5510 (setq-local
5511 align-mode-rules-list
5512 '((org-in-buffer-settings
5513 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5514 (modes . '(org-mode)))))
5516 ;; Imenu
5517 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5519 ;; Make isearch reveal context
5520 (setq-local outline-isearch-open-invisible-function
5521 (lambda (&rest _) (org-show-context 'isearch)))
5523 ;; Setup the pcomplete hooks
5524 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5525 (setq-local pcomplete-command-name-function 'org-command-at-point)
5526 (setq-local pcomplete-default-completion-function 'ignore)
5527 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5528 (setq-local pcomplete-termination-string "")
5529 (setq-local buffer-face-mode-face 'org-default)
5531 ;; If empty file that did not turn on Org mode automatically, make
5532 ;; it to.
5533 (when (and org-insert-mode-line-in-empty-file
5534 (called-interactively-p 'any)
5535 (= (point-min) (point-max)))
5536 (insert "# -*- mode: org -*-\n\n"))
5537 (unless org-inhibit-startup
5538 (org-unmodified
5539 (when org-startup-with-beamer-mode (org-beamer-mode))
5540 (when org-startup-align-all-tables
5541 (org-table-map-tables #'org-table-align t))
5542 (when org-startup-with-inline-images (org-display-inline-images))
5543 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5544 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5545 (when org-startup-truncated (setq truncate-lines t))
5546 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5547 (org-refresh-effort-properties)))
5548 ;; Try to set `org-hide' face correctly.
5549 (let ((foreground (org-find-invisible-foreground)))
5550 (when foreground
5551 (set-face-foreground 'org-hide foreground))))
5553 ;; Update `customize-package-emacs-version-alist'
5554 (add-to-list 'customize-package-emacs-version-alist
5555 '(Org ("8.0" . "24.4")
5556 ("8.1" . "24.4")
5557 ("8.2" . "24.4")
5558 ("8.2.7" . "24.4")
5559 ("8.3" . "26.1")
5560 ("9.0" . "26.1")
5561 ("9.1" . "26.1")))
5563 (defvar org-mode-transpose-word-syntax-table
5564 (let ((st (make-syntax-table text-mode-syntax-table)))
5565 (dolist (c org-emphasis-alist st)
5566 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5568 (when (fboundp 'abbrev-table-put)
5569 (abbrev-table-put org-mode-abbrev-table
5570 :parents (list text-mode-abbrev-table)))
5572 (defun org-find-invisible-foreground ()
5573 (let ((candidates (remove
5574 "unspecified-bg"
5575 (nconc
5576 (list (face-background 'default)
5577 (face-background 'org-default))
5578 (mapcar
5579 (lambda (alist)
5580 (when (boundp alist)
5581 (cdr (assq 'background-color (symbol-value alist)))))
5582 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5583 (list (face-foreground 'org-hide))))))
5584 (car (remove nil candidates))))
5586 (defun org-current-time (&optional rounding-minutes past)
5587 "Current time, possibly rounded to ROUNDING-MINUTES.
5588 When ROUNDING-MINUTES is not an integer, fall back on the car of
5589 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5590 the rounding returns a past time."
5591 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5592 (car org-time-stamp-rounding-minutes)))
5593 (time (decode-time)) res)
5594 (if (< r 1)
5595 (current-time)
5596 (setq res
5597 (apply 'encode-time
5598 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5599 (nthcdr 2 time))))
5600 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5601 (seconds-to-time (- (float-time res) (* r 60)))
5602 res))))
5604 (defun org-today ()
5605 "Return today date, considering `org-extend-today-until'."
5606 (time-to-days
5607 (time-subtract (current-time)
5608 (list 0 (* 3600 org-extend-today-until) 0))))
5610 ;;;; Font-Lock stuff, including the activators
5612 (defvar org-mouse-map (make-sparse-keymap))
5613 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5614 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5615 (when org-mouse-1-follows-link
5616 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5617 (when org-tab-follows-link
5618 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5619 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5621 (require 'font-lock)
5623 (defconst org-non-link-chars "]\t\n\r<>")
5624 (defvar org-link-types-re nil
5625 "Matches a link that has a url-like prefix like \"http:\"")
5626 (defvar org-link-re-with-space nil
5627 "Matches a link with spaces, optional angular brackets around it.")
5628 (defvar org-link-re-with-space2 nil
5629 "Matches a link with spaces, optional angular brackets around it.")
5630 (defvar org-link-re-with-space3 nil
5631 "Matches a link with spaces, only for internal part in bracket links.")
5632 (defvar org-angle-link-re nil
5633 "Matches link with angular brackets, spaces are allowed.")
5634 (defvar org-plain-link-re nil
5635 "Matches plain link, without spaces.")
5636 (defvar org-bracket-link-regexp nil
5637 "Matches a link in double brackets.")
5638 (defvar org-bracket-link-analytic-regexp nil
5639 "Regular expression used to analyze links.
5640 Here is what the match groups contain after a match:
5641 1: http:
5642 2: http
5643 3: path
5644 4: [desc]
5645 5: desc")
5646 (defvar org-bracket-link-analytic-regexp++ nil
5647 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5648 (defvar org-any-link-re nil
5649 "Regular expression matching any link.")
5651 (defconst org-match-sexp-depth 3
5652 "Number of stacked braces for sub/superscript matching.")
5654 (defun org-create-multibrace-regexp (left right n)
5655 "Create a regular expression which will match a balanced sexp.
5656 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5657 as single character strings.
5658 The regexp returned will match the entire expression including the
5659 delimiters. It will also define a single group which contains the
5660 match except for the outermost delimiters. The maximum depth of
5661 stacked delimiters is N. Escaping delimiters is not possible."
5662 (let* ((nothing (concat "[^" left right "]*?"))
5663 (or "\\|")
5664 (re nothing)
5665 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5666 (while (> n 1)
5667 (setq n (1- n)
5668 re (concat re or next)
5669 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5670 (concat left "\\(" re "\\)" right)))
5672 (defconst org-match-substring-regexp
5673 (concat
5674 "\\(\\S-\\)\\([_^]\\)\\("
5675 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5676 "\\|"
5677 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5678 "\\|"
5679 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5680 "The regular expression matching a sub- or superscript.")
5682 (defconst org-match-substring-with-braces-regexp
5683 (concat
5684 "\\(\\S-\\)\\([_^]\\)"
5685 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5686 "The regular expression matching a sub- or superscript, forcing braces.")
5688 (defun org-make-link-regexps ()
5689 "Update the link regular expressions.
5690 This should be called after the variable `org-link-parameters' has changed."
5691 (let ((types-re (regexp-opt (org-link-types) t)))
5692 (setq org-link-types-re
5693 (concat "\\`" types-re ":")
5694 org-link-re-with-space
5695 (concat "<?" types-re ":"
5696 "\\([^" org-non-link-chars " ]"
5697 "[^" org-non-link-chars "]*"
5698 "[^" org-non-link-chars " ]\\)>?")
5699 org-link-re-with-space2
5700 (concat "<?" types-re ":"
5701 "\\([^" org-non-link-chars " ]"
5702 "[^\t\n\r]*"
5703 "[^" org-non-link-chars " ]\\)>?")
5704 org-link-re-with-space3
5705 (concat "<?" types-re ":"
5706 "\\([^" org-non-link-chars " ]"
5707 "[^\t\n\r]*\\)")
5708 org-angle-link-re
5709 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5710 types-re)
5711 org-plain-link-re
5712 (concat
5713 "\\<" types-re ":"
5714 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5715 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5716 org-bracket-link-regexp
5717 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5718 org-bracket-link-analytic-regexp
5719 (concat
5720 "\\[\\["
5721 "\\(" types-re ":\\)?"
5722 "\\([^]]+\\)"
5723 "\\]"
5724 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5725 "\\]")
5726 org-bracket-link-analytic-regexp++
5727 (concat
5728 "\\[\\["
5729 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5730 "\\([^]]+\\)"
5731 "\\]"
5732 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5733 "\\]")
5734 org-any-link-re
5735 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5736 org-angle-link-re "\\)\\|\\("
5737 org-plain-link-re "\\)"))))
5739 (org-make-link-regexps)
5741 (defvar org-emph-face nil)
5743 (defun org-do-emphasis-faces (limit)
5744 "Run through the buffer and emphasize strings."
5745 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5746 (car org-emphasis-regexp-components))))
5747 (catch :exit
5748 (while (re-search-forward quick-re limit t)
5749 (let* ((marker (match-string 2))
5750 (verbatim? (member marker '("~" "="))))
5751 (when (save-excursion
5752 (goto-char (match-beginning 0))
5753 ;; Do not match headline stars. Do not consider
5754 ;; stars of a headline as closing marker for bold
5755 ;; markup either. Do not match table hlines.
5756 (and
5757 (not (looking-at-p org-outline-regexp-bol))
5758 (not (and (equal marker "+")
5759 (org-match-line
5760 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5761 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5762 (not (string-match-p
5763 (concat org-outline-regexp-bol "\\'")
5764 (match-string 0)))))
5765 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5766 (font-lock-prepend-text-property
5767 (match-beginning 2) (match-end 2) 'face face)
5768 (when verbatim?
5769 (org-remove-flyspell-overlays-in
5770 (match-beginning 0) (match-end 0)))
5771 (add-text-properties (match-beginning 2) (match-end 2)
5772 '(font-lock-multiline t org-emphasis t))
5773 (when org-hide-emphasis-markers
5774 (add-text-properties (match-end 4) (match-beginning 5)
5775 '(invisible org-link))
5776 (add-text-properties (match-beginning 3) (match-end 3)
5777 '(invisible org-link)))
5778 (throw :exit t))))))))
5780 (defun org-emphasize (&optional char)
5781 "Insert or change an emphasis, i.e. a font like bold or italic.
5782 If there is an active region, change that region to a new emphasis.
5783 If there is no region, just insert the marker characters and position
5784 the cursor between them.
5785 CHAR should be the marker character. If it is a space, it means to
5786 remove the emphasis of the selected region.
5787 If CHAR is not given (for example in an interactive call) it will be
5788 prompted for."
5789 (interactive)
5790 (let ((erc org-emphasis-regexp-components)
5791 (string "") beg end move s)
5792 (if (org-region-active-p)
5793 (setq beg (region-beginning)
5794 end (region-end)
5795 string (buffer-substring beg end))
5796 (setq move t))
5798 (unless char
5799 (message "Emphasis marker or tag: [%s]"
5800 (mapconcat #'car org-emphasis-alist ""))
5801 (setq char (read-char-exclusive)))
5802 (if (equal char ?\s)
5803 (setq s ""
5804 move nil)
5805 (unless (assoc (char-to-string char) org-emphasis-alist)
5806 (user-error "No such emphasis marker: \"%c\"" char))
5807 (setq s (char-to-string char)))
5808 (while (and (> (length string) 1)
5809 (equal (substring string 0 1) (substring string -1))
5810 (assoc (substring string 0 1) org-emphasis-alist))
5811 (setq string (substring string 1 -1)))
5812 (setq string (concat s string s))
5813 (when beg (delete-region beg end))
5814 (unless (or (bolp)
5815 (string-match (concat "[" (nth 0 erc) "\n]")
5816 (char-to-string (char-before (point)))))
5817 (insert " "))
5818 (unless (or (eobp)
5819 (string-match (concat "[" (nth 1 erc) "\n]")
5820 (char-to-string (char-after (point)))))
5821 (insert " ") (backward-char 1))
5822 (insert string)
5823 (and move (backward-char 1))))
5825 (defconst org-nonsticky-props
5826 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5828 (defsubst org-rear-nonsticky-at (pos)
5829 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5831 (defun org-activate-links (limit)
5832 "Add link properties to links.
5833 This includes angle, plain, and bracket links."
5834 (catch :exit
5835 (while (re-search-forward org-any-link-re limit t)
5836 (let* ((start (match-beginning 0))
5837 (end (match-end 0))
5838 (style (cond ((eq ?< (char-after start)) 'angle)
5839 ((eq ?\[ (char-after (1+ start))) 'bracket)
5840 (t 'plain))))
5841 (when (and (memq style org-highlight-links)
5842 ;; Do not confuse plain links with tags.
5843 (not (and (eq style 'plain)
5844 (let ((face (get-text-property
5845 (max (1- start) (point-min)) 'face)))
5846 (if (consp face) (memq 'org-tag face)
5847 (eq 'org-tag face))))))
5848 (let* ((link-object (save-excursion
5849 (goto-char start)
5850 (save-match-data (org-element-link-parser))))
5851 (link (org-element-property :raw-link link-object))
5852 (type (org-element-property :type link-object))
5853 (path (org-element-property :path link-object))
5854 (properties ;for link's visible part
5855 (list
5856 'face (pcase (org-link-get-parameter type :face)
5857 ((and (pred functionp) face) (funcall face path))
5858 ((and (pred facep) face) face)
5859 ((and (pred consp) face) face) ;anonymous
5860 (_ 'org-link))
5861 'mouse-face (or (org-link-get-parameter type :mouse-face)
5862 'highlight)
5863 'keymap (or (org-link-get-parameter type :keymap)
5864 org-mouse-map)
5865 'help-echo (pcase (org-link-get-parameter type :help-echo)
5866 ((and (pred stringp) echo) echo)
5867 ((and (pred functionp) echo) echo)
5868 (_ (concat "LINK: " link)))
5869 'htmlize-link (pcase (org-link-get-parameter type
5870 :htmlize-link)
5871 ((and (pred functionp) f) (funcall f))
5872 (_ `(:uri ,link)))
5873 'font-lock-multiline t)))
5874 (org-remove-flyspell-overlays-in start end)
5875 (org-rear-nonsticky-at end)
5876 (if (not (eq 'bracket style))
5877 (add-text-properties start end properties)
5878 ;; Handle invisible parts in bracket links.
5879 (remove-text-properties start end '(invisible nil))
5880 (let ((hidden
5881 (append `(invisible
5882 ,(or (org-link-get-parameter type :display)
5883 'org-link))
5884 properties))
5885 (visible-start (or (match-beginning 4) (match-beginning 2)))
5886 (visible-end (or (match-end 4) (match-end 2))))
5887 (add-text-properties start visible-start hidden)
5888 (add-text-properties visible-start visible-end properties)
5889 (add-text-properties visible-end end hidden)
5890 (org-rear-nonsticky-at visible-start)
5891 (org-rear-nonsticky-at visible-end)))
5892 (let ((f (org-link-get-parameter type :activate-func)))
5893 (when (functionp f)
5894 (funcall f start end path (eq style 'bracket))))
5895 (throw :exit t))))) ;signal success
5896 nil))
5898 (defun org-activate-code (limit)
5899 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5900 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5901 (remove-text-properties (match-beginning 0) (match-end 0)
5902 '(display t invisible t intangible t))
5905 (defcustom org-src-fontify-natively t
5906 "When non-nil, fontify code in code blocks.
5907 See also the `org-block' face."
5908 :type 'boolean
5909 :version "26.1"
5910 :package-version '(Org . "8.3")
5911 :group 'org-appearance
5912 :group 'org-babel)
5914 (defcustom org-allow-promoting-top-level-subtree nil
5915 "When non-nil, allow promoting a top level subtree.
5916 The leading star of the top level headline will be replaced
5917 by a #."
5918 :type 'boolean
5919 :version "24.1"
5920 :group 'org-appearance)
5922 (defun org-fontify-meta-lines-and-blocks (limit)
5923 (condition-case nil
5924 (org-fontify-meta-lines-and-blocks-1 limit)
5925 (error (message "org-mode fontification error in %S at %d"
5926 (current-buffer)
5927 (line-number-at-pos)))))
5929 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5930 "Fontify #+ lines and blocks."
5931 (let ((case-fold-search t))
5932 (when (re-search-forward
5933 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5934 limit t)
5935 (let ((beg (match-beginning 0))
5936 (block-start (match-end 0))
5937 (block-end nil)
5938 (lang (match-string 7))
5939 (beg1 (line-beginning-position 2))
5940 (dc1 (downcase (match-string 2)))
5941 (dc3 (downcase (match-string 3)))
5942 end end1 quoting block-type)
5943 (cond
5944 ((and (match-end 4) (equal dc3 "+begin"))
5945 ;; Truly a block
5946 (setq block-type (downcase (match-string 5))
5947 quoting (member block-type org-protecting-blocks))
5948 (when (re-search-forward
5949 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5950 nil t) ;; on purpose, we look further than LIMIT
5951 (setq end (min (point-max) (match-end 0))
5952 end1 (min (point-max) (1- (match-beginning 0))))
5953 (setq block-end (match-beginning 0))
5954 (when quoting
5955 (org-remove-flyspell-overlays-in beg1 end1)
5956 (remove-text-properties beg end
5957 '(display t invisible t intangible t)))
5958 (add-text-properties
5959 beg end '(font-lock-fontified t font-lock-multiline t))
5960 (add-text-properties beg beg1 '(face org-meta-line))
5961 (org-remove-flyspell-overlays-in beg beg1)
5962 (add-text-properties ; For end_src
5963 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5964 (org-remove-flyspell-overlays-in end1 end)
5965 (cond
5966 ((and lang (not (string= lang "")) org-src-fontify-natively)
5967 (org-src-font-lock-fontify-block lang block-start block-end)
5968 (add-text-properties beg1 block-end '(src-block t)))
5969 (quoting
5970 (add-text-properties beg1 (min (point-max) (1+ end1))
5971 (list 'face
5972 (list :inherit
5973 (let ((face-name
5974 (intern (format "org-block-%s" lang))))
5975 (append (and (facep face-name) (list face-name))
5976 '(org-block))))))) ; end of source block
5977 ((not org-fontify-quote-and-verse-blocks))
5978 ((string= block-type "quote")
5979 (add-face-text-property
5980 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5981 ((string= block-type "verse")
5982 (add-face-text-property
5983 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5984 (add-text-properties beg beg1 '(face org-block-begin-line))
5985 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5986 '(face org-block-end-line))
5988 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5989 (org-remove-flyspell-overlays-in
5990 (match-beginning 0)
5991 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5992 (add-text-properties
5993 beg (match-end 3)
5994 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5995 '(font-lock-fontified t invisible t)
5996 '(font-lock-fontified t face org-document-info-keyword)))
5997 (add-text-properties
5998 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5999 (if (string-equal dc1 "+title:")
6000 '(font-lock-fontified t face org-document-title)
6001 '(font-lock-fontified t face org-document-info))))
6002 ((string-prefix-p "+caption" dc1)
6003 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6004 (remove-text-properties (match-beginning 0) (match-end 0)
6005 '(display t invisible t intangible t))
6006 ;; Handle short captions.
6007 (save-excursion
6008 (beginning-of-line)
6009 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6010 (add-text-properties (line-beginning-position) (match-end 1)
6011 '(font-lock-fontified t face org-meta-line))
6012 (add-text-properties (match-end 0) (line-end-position)
6013 '(font-lock-fontified t face org-block))
6015 ((member dc3 '(" " ""))
6016 (org-remove-flyspell-overlays-in beg (match-end 0))
6017 (add-text-properties
6018 beg (match-end 0)
6019 '(font-lock-fontified t face font-lock-comment-face)))
6020 (t ;; just any other in-buffer setting, but not indented
6021 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6022 (remove-text-properties (match-beginning 0) (match-end 0)
6023 '(display t invisible t intangible t))
6024 (add-text-properties beg (match-end 0)
6025 '(font-lock-fontified t face org-meta-line))
6026 t))))))
6028 (defun org-fontify-drawers (limit)
6029 "Fontify drawers."
6030 (when (re-search-forward org-drawer-regexp limit t)
6031 (add-text-properties
6032 (match-beginning 0) (match-end 0)
6033 '(font-lock-fontified t face org-special-keyword))
6034 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6037 (defun org-fontify-macros (limit)
6038 "Fontify macros."
6039 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6040 (add-text-properties
6041 (match-beginning 0) (match-end 0)
6042 '(font-lock-fontified t face org-macro))
6043 (when org-hide-macro-markers
6044 (add-text-properties (match-end 2) (match-beginning 2)
6045 '(invisible t))
6046 (add-text-properties (match-beginning 1) (match-end 1)
6047 '(invisible t)))
6048 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6051 (defun org-activate-footnote-links (limit)
6052 "Add text properties for footnotes."
6053 (let ((fn (org-footnote-next-reference-or-definition limit)))
6054 (when fn
6055 (let* ((beg (nth 1 fn))
6056 (end (nth 2 fn))
6057 (label (car fn))
6058 (referencep (/= (line-beginning-position) beg)))
6059 (when (and referencep (nth 3 fn))
6060 (save-excursion
6061 (goto-char beg)
6062 (search-forward (or label "fn:"))
6063 (org-remove-flyspell-overlays-in beg (match-end 0))))
6064 (add-text-properties beg end
6065 (list 'mouse-face 'highlight
6066 'keymap org-mouse-map
6067 'help-echo
6068 (if referencep "Footnote reference"
6069 "Footnote definition")
6070 'font-lock-fontified t
6071 'font-lock-multiline t
6072 'face 'org-footnote))))))
6074 (defun org-activate-dates (limit)
6075 "Add text properties for dates."
6076 (when (and (re-search-forward org-tsr-regexp-both limit t)
6077 (not (equal (char-before (match-beginning 0)) 91)))
6078 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6079 (add-text-properties (match-beginning 0) (match-end 0)
6080 (list 'mouse-face 'highlight
6081 'keymap org-mouse-map))
6082 (org-rear-nonsticky-at (match-end 0))
6083 (when org-display-custom-times
6084 ;; If it's a date range, activate custom time for second date.
6085 (when (match-end 3)
6086 (org-display-custom-time (match-beginning 3) (match-end 3)))
6087 (org-display-custom-time (match-beginning 1) (match-end 1)))
6090 (defvar-local org-target-link-regexp nil
6091 "Regular expression matching radio targets in plain text.")
6093 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6094 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6095 border border border))
6096 "Regular expression matching a link target.")
6098 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6099 "Regular expression matching a radio target.")
6101 (defconst org-any-target-regexp
6102 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6103 "Regular expression matching any target.")
6105 (defun org-activate-target-links (limit)
6106 "Add text properties for target matches."
6107 (when org-target-link-regexp
6108 (let ((case-fold-search t))
6109 (when (re-search-forward org-target-link-regexp limit t)
6110 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6111 (add-text-properties (match-beginning 1) (match-end 1)
6112 (list 'mouse-face 'highlight
6113 'keymap org-mouse-map
6114 'help-echo "Radio target link"
6115 'org-linked-text t))
6116 (org-rear-nonsticky-at (match-end 1))
6117 t))))
6119 (defun org-update-radio-target-regexp ()
6120 "Find all radio targets in this file and update the regular expression.
6121 Also refresh fontification if needed."
6122 (interactive)
6123 (let ((old-regexp org-target-link-regexp)
6124 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6125 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6126 (targets
6127 (org-with-wide-buffer
6128 (goto-char (point-min))
6129 (let (rtn)
6130 (while (re-search-forward org-radio-target-regexp nil t)
6131 ;; Make sure point is really within the object.
6132 (backward-char)
6133 (let ((obj (org-element-context)))
6134 (when (eq (org-element-type obj) 'radio-target)
6135 (cl-pushnew (org-element-property :value obj) rtn
6136 :test #'equal))))
6137 rtn))))
6138 (setq org-target-link-regexp
6139 (and targets
6140 (concat before-re
6141 (mapconcat
6142 (lambda (x)
6143 (replace-regexp-in-string
6144 " +" "\\s-+" (regexp-quote x) t t))
6145 targets
6146 "\\|")
6147 after-re)))
6148 (unless (equal old-regexp org-target-link-regexp)
6149 ;; Clean-up cache.
6150 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6151 ((not org-target-link-regexp) old-regexp)
6153 (concat before-re
6154 (mapconcat
6155 (lambda (re)
6156 (substring re (length before-re)
6157 (- (length after-re))))
6158 (list old-regexp org-target-link-regexp)
6159 "\\|")
6160 after-re)))))
6161 (org-with-wide-buffer
6162 (goto-char (point-min))
6163 (while (re-search-forward regexp nil t)
6164 (org-element-cache-refresh (match-beginning 1)))))
6165 ;; Re fontify buffer.
6166 (when (memq 'radio org-highlight-links)
6167 (org-restart-font-lock)))))
6169 (defun org-hide-wide-columns (limit)
6170 (let (s e)
6171 (setq s (text-property-any (point) (or limit (point-max))
6172 'org-cwidth t))
6173 (when s
6174 (setq e (next-single-property-change s 'org-cwidth))
6175 (add-text-properties s e '(invisible org-cwidth))
6176 (goto-char e)
6177 t)))
6179 (defvar org-latex-and-related-regexp nil
6180 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6182 (defun org-compute-latex-and-related-regexp ()
6183 "Compute regular expression for LaTeX, entities and sub/superscript.
6184 Result depends on variable `org-highlight-latex-and-related'."
6185 (setq-local
6186 org-latex-and-related-regexp
6187 (let* ((re-sub
6188 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6189 ((eq org-use-sub-superscripts '{})
6190 (list org-match-substring-with-braces-regexp))
6191 (org-use-sub-superscripts (list org-match-substring-regexp))))
6192 (re-latex
6193 (when (memq 'latex org-highlight-latex-and-related)
6194 (let ((matchers (plist-get org-format-latex-options :matchers)))
6195 (delq nil
6196 (mapcar (lambda (x)
6197 (and (member (car x) matchers) (nth 1 x)))
6198 org-latex-regexps)))))
6199 (re-entities
6200 (when (memq 'entities org-highlight-latex-and-related)
6201 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6202 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6204 (defun org-do-latex-and-related (limit)
6205 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6206 LIMIT bounds the search for syntax to highlight. Stop at first
6207 highlighted object, if any. Return t if some highlighting was
6208 done, nil otherwise."
6209 (when (org-string-nw-p org-latex-and-related-regexp)
6210 (catch 'found
6211 (while (re-search-forward org-latex-and-related-regexp limit t)
6212 (unless
6213 (cl-some
6214 (lambda (f)
6215 (memq f '(org-code org-verbatim underline org-special-keyword)))
6216 (save-excursion
6217 (goto-char (1+ (match-beginning 0)))
6218 (face-at-point nil t)))
6219 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6220 '(?_ ?^))
6222 0)))
6223 (font-lock-prepend-text-property
6224 (+ offset (match-beginning 0)) (match-end 0)
6225 'face 'org-latex-and-related)
6226 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6227 '(font-lock-multiline t)))
6228 (throw 'found t)))
6229 nil)))
6231 (defun org-restart-font-lock ()
6232 "Restart `font-lock-mode', to force refontification."
6233 (when (and (boundp 'font-lock-mode) font-lock-mode)
6234 (font-lock-mode -1)
6235 (font-lock-mode 1)))
6237 (defun org-activate-tags (limit)
6238 (when (re-search-forward
6239 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6240 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6241 (add-text-properties (match-beginning 1) (match-end 1)
6242 (list 'mouse-face 'highlight
6243 'keymap org-mouse-map))
6244 (org-rear-nonsticky-at (match-end 1))
6247 (defun org-outline-level ()
6248 "Compute the outline level of the heading at point.
6250 If this is called at a normal headline, the level is the number
6251 of stars. Use `org-reduced-level' to remove the effect of
6252 `org-odd-levels'. Unlike to `org-current-level', this function
6253 takes into consideration inlinetasks."
6254 (org-with-wide-buffer
6255 (end-of-line)
6256 (if (re-search-backward org-outline-regexp-bol nil t)
6257 (1- (- (match-end 0) (match-beginning 0)))
6258 0)))
6260 (defvar org-font-lock-keywords nil)
6262 (defsubst org-re-property (property &optional literal allow-null value)
6263 "Return a regexp matching a PROPERTY line.
6265 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6266 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6267 non-nil, match properties even without a value.
6269 Match group 3 is set to the value when it exists. If there is no
6270 value and ALLOW-NULL is non-nil, it is set to the empty string.
6272 With optional argument VALUE, match only property lines with
6273 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6274 unless LITERAL is non-nil."
6275 (concat
6276 "^\\(?4:[ \t]*\\)"
6277 (format "\\(?1::\\(?2:%s\\):\\)"
6278 (if literal property (regexp-quote property)))
6279 (cond (value
6280 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6281 (if literal value (regexp-quote value))))
6282 (allow-null
6283 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6285 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6287 (defconst org-property-re
6288 (org-re-property "\\S-+" 'literal t)
6289 "Regular expression matching a property line.
6290 There are four matching groups:
6291 1: :PROPKEY: including the leading and trailing colon,
6292 2: PROPKEY without the leading and trailing colon,
6293 3: PROPVAL without leading or trailing spaces,
6294 4: the indentation of the current line,
6295 5: trailing whitespace.")
6297 (defvar org-font-lock-hook nil
6298 "Functions to be called for special font lock stuff.")
6300 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6302 (defvar org-font-lock-set-keywords-hook nil
6303 "Functions that can manipulate `org-font-lock-extra-keywords'.
6304 This is called after `org-font-lock-extra-keywords' is defined, but before
6305 it is installed to be used by font lock. This can be useful if something
6306 needs to be inserted at a specific position in the font-lock sequence.")
6308 (defun org-font-lock-hook (limit)
6309 "Run `org-font-lock-hook' within LIMIT."
6310 (run-hook-with-args 'org-font-lock-hook limit))
6312 (defun org-set-font-lock-defaults ()
6313 "Set font lock defaults for the current buffer."
6314 (let* ((em org-fontify-emphasized-text)
6315 (lk org-highlight-links)
6316 (org-font-lock-extra-keywords
6317 (list
6318 ;; Call the hook
6319 '(org-font-lock-hook)
6320 ;; Headlines
6321 `(,(if org-fontify-whole-heading-line
6322 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6323 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6324 (1 (org-get-level-face 1))
6325 (2 (org-get-level-face 2))
6326 (3 (org-get-level-face 3)))
6327 ;; Table lines
6328 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6329 (1 'org-table t))
6330 ;; Table internals
6331 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6332 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6333 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6334 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6335 ;; Drawers
6336 '(org-fontify-drawers)
6337 ;; Properties
6338 (list org-property-re
6339 '(1 'org-special-keyword t)
6340 '(3 'org-property-value t))
6341 ;; Link related fontification.
6342 '(org-activate-links)
6343 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6344 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6345 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6346 (when (memq 'footnote lk) '(org-activate-footnote-links))
6347 ;; Targets.
6348 (list org-any-target-regexp '(0 'org-target t))
6349 ;; Diary sexps.
6350 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6351 ;; Macro
6352 '(org-fontify-macros)
6353 '(org-hide-wide-columns (0 nil append))
6354 ;; TODO keyword
6355 (list (format org-heading-keyword-regexp-format
6356 org-todo-regexp)
6357 '(2 (org-get-todo-face 2) t))
6358 ;; DONE
6359 (if org-fontify-done-headline
6360 (list (format org-heading-keyword-regexp-format
6361 (concat
6362 "\\(?:"
6363 (mapconcat 'regexp-quote org-done-keywords "\\|")
6364 "\\)"))
6365 '(2 'org-headline-done t))
6366 nil)
6367 ;; Priorities
6368 '(org-font-lock-add-priority-faces)
6369 ;; Tags
6370 '(org-font-lock-add-tag-faces)
6371 ;; Tags groups
6372 (when (and org-group-tags org-tag-groups-alist)
6373 (list (concat org-outline-regexp-bol ".+\\(:"
6374 (regexp-opt (mapcar 'car org-tag-groups-alist))
6375 ":\\).*$")
6376 '(1 'org-tag-group prepend)))
6377 ;; Special keywords
6378 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6379 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6380 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6381 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6382 ;; Emphasis
6383 (when em '(org-do-emphasis-faces))
6384 ;; Checkboxes
6385 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6386 1 'org-checkbox prepend)
6387 (when (cdr (assq 'checkbox org-list-automatic-rules))
6388 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6389 (0 (org-get-checkbox-statistics-face) t)))
6390 ;; Description list items
6391 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6392 1 'org-list-dt prepend)
6393 ;; ARCHIVEd headings
6394 (list (concat
6395 org-outline-regexp-bol
6396 "\\(.*:" org-archive-tag ":.*\\)")
6397 '(1 'org-archived prepend))
6398 ;; Specials
6399 '(org-do-latex-and-related)
6400 '(org-fontify-entities)
6401 '(org-raise-scripts)
6402 ;; Code
6403 '(org-activate-code (1 'org-code t))
6404 ;; COMMENT
6405 (list (format
6406 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6407 org-todo-regexp
6408 org-comment-string)
6409 '(9 'org-special-keyword t))
6410 ;; Blocks and meta lines
6411 '(org-fontify-meta-lines-and-blocks))))
6412 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6413 (run-hooks 'org-font-lock-set-keywords-hook)
6414 ;; Now set the full font-lock-keywords
6415 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6416 (setq-local font-lock-defaults
6417 '(org-font-lock-keywords t nil nil backward-paragraph))
6418 (kill-local-variable 'font-lock-keywords)
6419 nil))
6421 (defun org-toggle-pretty-entities ()
6422 "Toggle the composition display of entities as UTF8 characters."
6423 (interactive)
6424 (setq-local org-pretty-entities (not org-pretty-entities))
6425 (org-restart-font-lock)
6426 (if org-pretty-entities
6427 (message "Entities are now displayed as UTF8 characters")
6428 (save-restriction
6429 (widen)
6430 (decompose-region (point-min) (point-max))
6431 (message "Entities are now displayed as plain text"))))
6433 (defvar-local org-custom-properties-overlays nil
6434 "List of overlays used for custom properties.")
6436 (defun org-toggle-custom-properties-visibility ()
6437 "Display or hide properties in `org-custom-properties'."
6438 (interactive)
6439 (if org-custom-properties-overlays
6440 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6441 (setq org-custom-properties-overlays nil))
6442 (when org-custom-properties
6443 (org-with-wide-buffer
6444 (goto-char (point-min))
6445 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6446 (while (re-search-forward regexp nil t)
6447 (let ((end (cdr (save-match-data (org-get-property-block)))))
6448 (when (and end (< (point) end))
6449 ;; Hide first custom property in current drawer.
6450 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6451 (overlay-put o 'invisible t)
6452 (overlay-put o 'org-custom-property t)
6453 (push o org-custom-properties-overlays))
6454 ;; Hide additional custom properties in the same drawer.
6455 (while (re-search-forward regexp end t)
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 ;; Each entry is limited to a single property drawer.
6461 (outline-next-heading)))))))
6463 (defun org-fontify-entities (limit)
6464 "Find an entity to fontify."
6465 (let (ee)
6466 (when org-pretty-entities
6467 (catch 'match
6468 ;; "\_ "-family is left out on purpose. Only the first one,
6469 ;; i.e., "\_ ", could be fontified anyway, and it would be
6470 ;; confusing when adding a second white space character.
6471 (while (re-search-forward
6472 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6473 limit t)
6474 (when (and (not (org-at-comment-p))
6475 (setq ee (org-entity-get (match-string 1)))
6476 (= (length (nth 6 ee)) 1))
6477 (let* ((end (if (equal (match-string 2) "{}")
6478 (match-end 2)
6479 (match-end 1))))
6480 (add-text-properties
6481 (match-beginning 0) end
6482 (list 'font-lock-fontified t))
6483 (compose-region (match-beginning 0) end
6484 (nth 6 ee) nil)
6485 (backward-char 1)
6486 (throw 'match t))))
6487 nil))))
6489 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6490 "Fontify string S like in Org mode."
6491 (with-temp-buffer
6492 (insert s)
6493 (let ((org-odd-levels-only odd-levels))
6494 (org-mode)
6495 (org-font-lock-ensure)
6496 (buffer-string))))
6498 (defvar org-m nil)
6499 (defvar org-l nil)
6500 (defvar org-f nil)
6501 (defun org-get-level-face (n)
6502 "Get the right face for match N in font-lock matching of headlines."
6503 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6504 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6505 (if org-cycle-level-faces
6506 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6507 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6508 (cond
6509 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6510 ((eq n 2) org-f)
6511 (t (unless org-level-color-stars-only org-f))))
6513 (defun org-face-from-face-or-color (context inherit face-or-color)
6514 "Create a face list that inherits INHERIT, but sets the foreground color.
6515 When FACE-OR-COLOR is not a string, just return it."
6516 (if (stringp face-or-color)
6517 (list :inherit inherit
6518 (cdr (assoc context org-faces-easy-properties))
6519 face-or-color)
6520 face-or-color))
6522 (defun org-get-todo-face (kwd)
6523 "Get the right face for a TODO keyword KWD.
6524 If KWD is a number, get the corresponding match group."
6525 (when (numberp kwd) (setq kwd (match-string kwd)))
6526 (or (org-face-from-face-or-color
6527 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6528 (and (member kwd org-done-keywords) 'org-done)
6529 'org-todo))
6531 (defun org-get-priority-face (priority)
6532 "Get the right face for PRIORITY.
6533 PRIORITY is a character."
6534 (or (org-face-from-face-or-color
6535 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6536 'org-priority))
6538 (defun org-get-tag-face (tag)
6539 "Get the right face for TAG.
6540 If TAG is a number, get the corresponding match group."
6541 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6542 (or (org-face-from-face-or-color
6543 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6544 'org-tag)))
6546 (defun org-font-lock-add-priority-faces (limit)
6547 "Add the special priority faces."
6548 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6549 (add-text-properties
6550 (match-beginning 1) (match-end 1)
6551 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6552 'font-lock-fontified t))))
6554 (defun org-font-lock-add-tag-faces (limit)
6555 "Add the special tag faces."
6556 (when (and org-tag-faces org-tags-special-faces-re)
6557 (while (re-search-forward org-tags-special-faces-re limit t)
6558 (add-text-properties (match-beginning 1) (match-end 1)
6559 (list 'face (org-get-tag-face 1)
6560 'font-lock-fontified t))
6561 (backward-char 1))))
6563 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6564 "Remove fontification and activation overlays from links."
6565 (font-lock-default-unfontify-region beg end)
6566 (let* ((buffer-undo-list t)
6567 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6568 (inhibit-modification-hooks t)
6569 deactivate-mark buffer-file-name buffer-file-truename)
6570 (decompose-region beg end)
6571 (remove-text-properties beg end
6572 '(mouse-face t keymap t org-linked-text t
6573 invisible t intangible t
6574 org-emphasis t))
6575 (org-remove-font-lock-display-properties beg end)))
6577 (defconst org-script-display '(((raise -0.3) (height 0.7))
6578 ((raise 0.3) (height 0.7))
6579 ((raise -0.5))
6580 ((raise 0.5)))
6581 "Display properties for showing superscripts and subscripts.")
6583 (defun org-remove-font-lock-display-properties (beg end)
6584 "Remove specific display properties that have been added by font lock.
6585 The will remove the raise properties that are used to show superscripts
6586 and subscripts."
6587 (let (next prop)
6588 (while (< beg end)
6589 (setq next (next-single-property-change beg 'display nil end)
6590 prop (get-text-property beg 'display))
6591 (when (member prop org-script-display)
6592 (put-text-property beg next 'display nil))
6593 (setq beg next))))
6595 (defun org-raise-scripts (limit)
6596 "Add raise properties to sub/superscripts."
6597 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6598 (re-search-forward
6599 (if (eq org-use-sub-superscripts t)
6600 org-match-substring-regexp
6601 org-match-substring-with-braces-regexp)
6602 limit t))
6603 (let* ((pos (point)) table-p comment-p
6604 (mpos (match-beginning 3))
6605 (emph-p (get-text-property mpos 'org-emphasis))
6606 (link-p (get-text-property mpos 'mouse-face))
6607 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6608 (goto-char (point-at-bol))
6609 (setq table-p (looking-at-p org-table-dataline-regexp)
6610 comment-p (looking-at-p "^[ \t]*#[ +]"))
6611 (goto-char pos)
6612 ;; Handle a_b^c
6613 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6614 (unless (or comment-p emph-p link-p keyw-p)
6615 (put-text-property (match-beginning 3) (match-end 0)
6616 'display
6617 (if (equal (char-after (match-beginning 2)) ?^)
6618 (nth (if table-p 3 1) org-script-display)
6619 (nth (if table-p 2 0) org-script-display)))
6620 (add-text-properties (match-beginning 2) (match-end 2)
6621 (list 'invisible t))
6622 (when (and (eq (char-after (match-beginning 3)) ?{)
6623 (eq (char-before (match-end 3)) ?}))
6624 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6625 (list 'invisible t))
6626 (add-text-properties (1- (match-end 3)) (match-end 3)
6627 (list 'invisible t))))
6628 t)))
6630 ;;;; Visibility cycling, including org-goto and indirect buffer
6632 ;;; Cycling
6634 (defvar-local org-cycle-global-status nil)
6635 (put 'org-cycle-global-status 'org-state t)
6636 (defvar-local org-cycle-subtree-status nil)
6637 (put 'org-cycle-subtree-status 'org-state t)
6639 (defvar org-inlinetask-min-level)
6641 (defun org-unlogged-message (&rest args)
6642 "Display a message, but avoid logging it in the *Messages* buffer."
6643 (let ((message-log-max nil))
6644 (apply 'message args)))
6646 ;;;###autoload
6647 (defun org-cycle (&optional arg)
6648 "TAB-action and visibility cycling for Org mode.
6650 This is the command invoked in Org mode by the `TAB' key. Its main
6651 purpose is outline visibility cycling, but it also invokes other actions
6652 in special contexts.
6654 When this function is called with a `\\[universal-argument]' prefix, rotate \
6655 the entire
6656 buffer through 3 states (global cycling)
6657 1. OVERVIEW: Show only top-level headlines.
6658 2. CONTENTS: Show all headlines of all levels, but no body text.
6659 3. SHOW ALL: Show everything.
6661 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6662 switch to the startup visibility,
6663 determined by the variable `org-startup-folded', and by any VISIBILITY
6664 properties in the buffer.
6666 With a `\\[universal-argument] \\[universal-argument] \
6667 \\[universal-argument]' prefix argument, show the entire buffer, including
6668 any drawers.
6670 When inside a table, re-align the table and move to the next field.
6672 When point is at the beginning of a headline, rotate the subtree started
6673 by this line through 3 different states (local cycling)
6674 1. FOLDED: Only the main headline is shown.
6675 2. CHILDREN: The main headline and the direct children are shown.
6676 From this state, you can move to one of the children
6677 and zoom in further.
6678 3. SUBTREE: Show the entire subtree, including body text.
6679 If there is no subtree, switch directly from CHILDREN to FOLDED.
6681 When point is at the beginning of an empty headline and the variable
6682 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6683 of the headline by demoting and promoting it to likely levels. This
6684 speeds up creation document structure by pressing `TAB' once or several
6685 times right after creating a new headline.
6687 When there is a numeric prefix, go up to a heading with level ARG, do
6688 a `show-subtree' and return to the previous cursor position. If ARG
6689 is negative, go up that many levels.
6691 When point is not at the beginning of a headline, execute the global
6692 binding for `TAB', which is re-indenting the line. See the option
6693 `org-cycle-emulate-tab' for details.
6695 As a special case, if point is at the beginning of the buffer and there is
6696 no headline in line 1, this function will act as if called with prefix arg
6697 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6698 prefix arg, but only
6699 if the variable `org-cycle-global-at-bob' is t."
6700 (interactive "P")
6701 (org-load-modules-maybe)
6702 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6703 (and org-cycle-level-after-item/entry-creation
6704 (or (org-cycle-level)
6705 (org-cycle-item-indentation))))
6706 (let* ((limit-level
6707 (or org-cycle-max-level
6708 (and (boundp 'org-inlinetask-min-level)
6709 org-inlinetask-min-level
6710 (1- org-inlinetask-min-level))))
6711 (nstars (and limit-level
6712 (if org-odd-levels-only
6713 (and limit-level (1- (* limit-level 2)))
6714 limit-level)))
6715 (org-outline-regexp
6716 (if (not (derived-mode-p 'org-mode))
6717 outline-regexp
6718 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6719 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6720 (not (looking-at org-outline-regexp))))
6721 (org-cycle-hook
6722 (if bob-special
6723 (delq 'org-optimize-window-after-visibility-change
6724 (copy-sequence org-cycle-hook))
6725 org-cycle-hook))
6726 (pos (point)))
6728 (cond
6730 ((equal arg '(16))
6731 (setq last-command 'dummy)
6732 (org-set-startup-visibility)
6733 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6735 ((equal arg '(64))
6736 (outline-show-all)
6737 (org-unlogged-message "Entire buffer visible, including drawers"))
6739 ((equal arg '(4)) (org-cycle-internal-global))
6741 ;; Try hiding block at point.
6742 ((org-hide-block-toggle-maybe))
6744 ;; Try cdlatex TAB completion
6745 ((org-try-cdlatex-tab))
6747 ;; Table: enter it or move to the next field.
6748 ((org-at-table-p 'any)
6749 (if (org-at-table.el-p)
6750 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6751 Use `\\[org-edit-special]' to edit table.el tables"))
6752 (if arg (org-table-edit-field t)
6753 (org-table-justify-field-maybe)
6754 (call-interactively 'org-table-next-field))))
6756 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6758 ;; Global cycling: delegate to `org-cycle-internal-global'.
6759 (bob-special (org-cycle-internal-global))
6761 ;; Drawers: delegate to `org-flag-drawer'.
6762 ((save-excursion
6763 (beginning-of-line 1)
6764 (looking-at org-drawer-regexp))
6765 (org-flag-drawer ; toggle block visibility
6766 (not (get-char-property (match-end 0) 'invisible))))
6768 ;; Show-subtree, ARG levels up from here.
6769 ((integerp arg)
6770 (save-excursion
6771 (org-back-to-heading)
6772 (outline-up-heading (if (< arg 0) (- arg)
6773 (- (funcall outline-level) arg)))
6774 (org-show-subtree)))
6776 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6777 ((and (featurep 'org-inlinetask)
6778 (org-inlinetask-at-task-p)
6779 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6780 (org-inlinetask-toggle-visibility))
6782 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6783 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6784 (save-excursion (move-beginning-of-line 1)
6785 (looking-at org-outline-regexp)))
6786 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6787 (org-cycle-internal-local))
6789 ;; From there: TAB emulation and template completion.
6790 (buffer-read-only (org-back-to-heading))
6792 ((run-hook-with-args-until-success
6793 'org-tab-after-check-for-cycling-hook))
6795 ((org-try-structure-completion))
6797 ((run-hook-with-args-until-success
6798 'org-tab-before-tab-emulation-hook))
6800 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6801 (or (not (bolp))
6802 (not (looking-at org-outline-regexp))))
6803 (call-interactively (global-key-binding "\t")))
6805 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6806 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6807 (or (and (eq org-cycle-emulate-tab 'white)
6808 (= (match-end 0) (point-at-eol)))
6809 (and (eq org-cycle-emulate-tab 'whitestart)
6810 (>= (match-end 0) pos))))
6812 (eq org-cycle-emulate-tab t))
6813 (call-interactively (global-key-binding "\t")))
6815 (t (save-excursion
6816 (org-back-to-heading)
6817 (org-cycle)))))))
6819 (defun org-cycle-internal-global ()
6820 "Do the global cycling action."
6821 ;; Hack to avoid display of messages for .org attachments in Gnus
6822 (let ((ga (string-match "\\*fontification" (buffer-name))))
6823 (cond
6824 ((and (eq last-command this-command)
6825 (eq org-cycle-global-status 'overview))
6826 ;; We just created the overview - now do table of contents
6827 ;; This can be slow in very large buffers, so indicate action
6828 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6829 (unless ga (org-unlogged-message "CONTENTS..."))
6830 (org-content)
6831 (unless ga (org-unlogged-message "CONTENTS...done"))
6832 (setq org-cycle-global-status 'contents)
6833 (run-hook-with-args 'org-cycle-hook 'contents))
6835 ((and (eq last-command this-command)
6836 (eq org-cycle-global-status 'contents))
6837 ;; We just showed the table of contents - now show everything
6838 (run-hook-with-args 'org-pre-cycle-hook 'all)
6839 (outline-show-all)
6840 (unless ga (org-unlogged-message "SHOW ALL"))
6841 (setq org-cycle-global-status 'all)
6842 (run-hook-with-args 'org-cycle-hook 'all))
6845 ;; Default action: go to overview
6846 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6847 (org-overview)
6848 (unless ga (org-unlogged-message "OVERVIEW"))
6849 (setq org-cycle-global-status 'overview)
6850 (run-hook-with-args 'org-cycle-hook 'overview)))))
6852 (defvar org-called-with-limited-levels nil
6853 "Non-nil when `org-with-limited-levels' is currently active.")
6855 (defun org-invisible-p (&optional pos)
6856 "Non-nil if the character after POS is invisible.
6857 If POS is nil, use `point' instead."
6858 (get-char-property (or pos (point)) 'invisible))
6860 (defun org-cycle-internal-local ()
6861 "Do the local cycling action."
6862 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6863 ;; First, determine end of headline (EOH), end of subtree or item
6864 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6865 (save-excursion
6866 (if (org-at-item-p)
6867 (progn
6868 (beginning-of-line)
6869 (setq struct (org-list-struct))
6870 (setq eoh (point-at-eol))
6871 (setq eos (org-list-get-item-end-before-blank (point) struct))
6872 (setq has-children (org-list-has-child-p (point) struct)))
6873 (org-back-to-heading)
6874 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6875 (setq eos (save-excursion (org-end-of-subtree t t)
6876 (when (bolp) (backward-char)) (point)))
6877 (setq has-children
6878 (or (save-excursion
6879 (let ((level (funcall outline-level)))
6880 (outline-next-heading)
6881 (and (org-at-heading-p t)
6882 (> (funcall outline-level) level))))
6883 (save-excursion
6884 (org-list-search-forward (org-item-beginning-re) eos t)))))
6885 ;; Determine end invisible part of buffer (EOL)
6886 (beginning-of-line 2)
6887 (while (and (not (eobp)) ;This is like `next-line'.
6888 (get-char-property (1- (point)) 'invisible))
6889 (goto-char (next-single-char-property-change (point) 'invisible))
6890 (and (eolp) (beginning-of-line 2)))
6891 (setq eol (point)))
6892 ;; Find out what to do next and set `this-command'
6893 (cond
6894 ((= eos eoh)
6895 ;; Nothing is hidden behind this heading
6896 (unless (org-before-first-heading-p)
6897 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6898 (org-unlogged-message "EMPTY ENTRY")
6899 (setq org-cycle-subtree-status nil)
6900 (save-excursion
6901 (goto-char eos)
6902 (outline-next-heading)
6903 (when (org-invisible-p) (org-flag-heading nil))))
6904 ((and (or (>= eol eos)
6905 (not (string-match "\\S-" (buffer-substring eol eos))))
6906 (or has-children
6907 (not (setq children-skipped
6908 org-cycle-skip-children-state-if-no-children))))
6909 ;; Entire subtree is hidden in one line: children view
6910 (unless (org-before-first-heading-p)
6911 (run-hook-with-args 'org-pre-cycle-hook 'children))
6912 (if (org-at-item-p)
6913 (org-list-set-item-visibility (point-at-bol) struct 'children)
6914 (org-show-entry)
6915 (org-with-limited-levels (org-show-children))
6916 ;; FIXME: This slows down the func way too much.
6917 ;; How keep drawers hidden in subtree anyway?
6918 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6919 ;; (org-cycle-hide-drawers 'subtree))
6921 ;; Fold every list in subtree to top-level items.
6922 (when (eq org-cycle-include-plain-lists 'integrate)
6923 (save-excursion
6924 (org-back-to-heading)
6925 (while (org-list-search-forward (org-item-beginning-re) eos t)
6926 (beginning-of-line 1)
6927 (let* ((struct (org-list-struct))
6928 (prevs (org-list-prevs-alist struct))
6929 (end (org-list-get-bottom-point struct)))
6930 (dolist (e (org-list-get-all-items (point) struct prevs))
6931 (org-list-set-item-visibility e struct 'folded))
6932 (goto-char (if (< end eos) end eos)))))))
6933 (org-unlogged-message "CHILDREN")
6934 (save-excursion
6935 (goto-char eos)
6936 (outline-next-heading)
6937 (when (org-invisible-p) (org-flag-heading nil)))
6938 (setq org-cycle-subtree-status 'children)
6939 (unless (org-before-first-heading-p)
6940 (run-hook-with-args 'org-cycle-hook 'children)))
6941 ((or children-skipped
6942 (and (eq last-command this-command)
6943 (eq org-cycle-subtree-status 'children)))
6944 ;; We just showed the children, or no children are there,
6945 ;; now show everything.
6946 (unless (org-before-first-heading-p)
6947 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6948 (outline-flag-region eoh eos nil)
6949 (org-unlogged-message
6950 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6951 (setq org-cycle-subtree-status 'subtree)
6952 (unless (org-before-first-heading-p)
6953 (run-hook-with-args 'org-cycle-hook 'subtree)))
6955 ;; Default action: hide the subtree.
6956 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6957 (outline-flag-region eoh eos t)
6958 (org-unlogged-message "FOLDED")
6959 (setq org-cycle-subtree-status 'folded)
6960 (unless (org-before-first-heading-p)
6961 (run-hook-with-args 'org-cycle-hook 'folded))))))
6963 ;;;###autoload
6964 (defun org-global-cycle (&optional arg)
6965 "Cycle the global visibility. For details see `org-cycle'.
6966 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6967 With a numeric prefix, show all headlines up to that level."
6968 (interactive "P")
6969 (let ((org-cycle-include-plain-lists
6970 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6971 (cond
6972 ((integerp arg)
6973 (outline-show-all)
6974 (outline-hide-sublevels arg)
6975 (setq org-cycle-global-status 'contents))
6976 ((equal arg '(4))
6977 (org-set-startup-visibility)
6978 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6980 (org-cycle '(4))))))
6982 (defun org-set-startup-visibility ()
6983 "Set the visibility required by startup options and properties."
6984 (cond
6985 ((eq org-startup-folded t)
6986 (org-overview))
6987 ((eq org-startup-folded 'content)
6988 (org-content))
6989 ((or (eq org-startup-folded 'showeverything)
6990 (eq org-startup-folded nil))
6991 (outline-show-all)))
6992 (unless (eq org-startup-folded 'showeverything)
6993 (when org-hide-block-startup (org-hide-block-all))
6994 (org-set-visibility-according-to-property 'no-cleanup)
6995 (org-cycle-hide-archived-subtrees 'all)
6996 (org-cycle-hide-drawers 'all)
6997 (org-cycle-show-empty-lines t)))
6999 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7000 "Switch subtree visibilities according to :VISIBILITY: property."
7001 (interactive)
7002 (org-with-wide-buffer
7003 (goto-char (point-min))
7004 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7005 (if (not (org-at-property-p)) (outline-next-heading)
7006 (let ((state (match-string 3)))
7007 (save-excursion
7008 (org-back-to-heading t)
7009 (outline-hide-subtree)
7010 (org-reveal)
7011 (cond
7012 ((equal state "folded")
7013 (outline-hide-subtree))
7014 ((equal state "children")
7015 (org-show-hidden-entry)
7016 (org-show-children))
7017 ((equal state "content")
7018 (save-excursion
7019 (save-restriction
7020 (org-narrow-to-subtree)
7021 (org-content))))
7022 ((member state '("all" "showall"))
7023 (outline-show-subtree)))))))
7024 (unless no-cleanup
7025 (org-cycle-hide-archived-subtrees 'all)
7026 (org-cycle-hide-drawers 'all)
7027 (org-cycle-show-empty-lines 'all))))
7029 ;; This function uses outline-regexp instead of the more fundamental
7030 ;; org-outline-regexp so that org-cycle-global works outside of Org
7031 ;; buffers, where outline-regexp is needed.
7032 (defun org-overview ()
7033 "Switch to overview mode, showing only top-level headlines.
7034 This shows all headlines with a level equal or greater than the level
7035 of the first headline in the buffer. This is important, because if the
7036 first headline is not level one, then (hide-sublevels 1) gives confusing
7037 results."
7038 (interactive)
7039 (save-excursion
7040 (let ((level
7041 (save-excursion
7042 (goto-char (point-min))
7043 (when (re-search-forward (concat "^" outline-regexp) nil t)
7044 (goto-char (match-beginning 0))
7045 (funcall outline-level)))))
7046 (and level (outline-hide-sublevels level)))))
7048 (defun org-content (&optional arg)
7049 "Show all headlines in the buffer, like a table of contents.
7050 With numerical argument N, show content up to level N."
7051 (interactive "P")
7052 (org-overview)
7053 (save-excursion
7054 ;; Visit all headings and show their offspring
7055 (and (integerp arg) (org-overview))
7056 (goto-char (point-max))
7057 (catch 'exit
7058 (while (and (progn (condition-case nil
7059 (outline-previous-visible-heading 1)
7060 (error (goto-char (point-min))))
7062 (looking-at org-outline-regexp))
7063 (if (integerp arg)
7064 (org-show-children (1- arg))
7065 (outline-show-branches))
7066 (when (bobp) (throw 'exit nil))))))
7068 (defun org-optimize-window-after-visibility-change (state)
7069 "Adjust the window after a change in outline visibility.
7070 This function is the default value of the hook `org-cycle-hook'."
7071 (when (get-buffer-window (current-buffer))
7072 (cond
7073 ((eq state 'content) nil)
7074 ((eq state 'all) nil)
7075 ((eq state 'folded) nil)
7076 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7077 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7079 (defun org-remove-empty-overlays-at (pos)
7080 "Remove outline overlays that do not contain non-white stuff."
7081 (dolist (o (overlays-at pos))
7082 (and (eq 'outline (overlay-get o 'invisible))
7083 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7084 (overlay-end o))))
7085 (delete-overlay o))))
7087 (defun org-clean-visibility-after-subtree-move ()
7088 "Fix visibility issues after moving a subtree."
7089 ;; First, find a reasonable region to look at:
7090 ;; Start two siblings above, end three below
7091 (let* ((beg (save-excursion
7092 (and (org-get-last-sibling)
7093 (org-get-last-sibling))
7094 (point)))
7095 (end (save-excursion
7096 (and (org-get-next-sibling)
7097 (org-get-next-sibling)
7098 (org-get-next-sibling))
7099 (if (org-at-heading-p)
7100 (point-at-eol)
7101 (point))))
7102 (level (looking-at "\\*+"))
7103 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7104 (save-excursion
7105 (save-restriction
7106 (narrow-to-region beg end)
7107 (when re
7108 ;; Properly fold already folded siblings
7109 (goto-char (point-min))
7110 (while (re-search-forward re nil t)
7111 (when (and (not (org-invisible-p))
7112 (save-excursion
7113 (goto-char (point-at-eol)) (org-invisible-p)))
7114 (outline-hide-entry))))
7115 (org-cycle-show-empty-lines 'overview)
7116 (org-cycle-hide-drawers 'overview)))))
7118 (defun org-cycle-show-empty-lines (state)
7119 "Show empty lines above all visible headlines.
7120 The region to be covered depends on STATE when called through
7121 `org-cycle-hook'. Lisp program can use t for STATE to get the
7122 entire buffer covered. Note that an empty line is only shown if there
7123 are at least `org-cycle-separator-lines' empty lines before the headline."
7124 (when (/= org-cycle-separator-lines 0)
7125 (save-excursion
7126 (let* ((n (abs org-cycle-separator-lines))
7127 (re (cond
7128 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7129 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7130 (t (let ((ns (number-to-string (- n 2))))
7131 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7132 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7133 beg end)
7134 (cond
7135 ((memq state '(overview contents t))
7136 (setq beg (point-min) end (point-max)))
7137 ((memq state '(children folded))
7138 (setq beg (point)
7139 end (progn (org-end-of-subtree t t)
7140 (line-beginning-position 2)))))
7141 (when beg
7142 (goto-char beg)
7143 (while (re-search-forward re end t)
7144 (unless (get-char-property (match-end 1) 'invisible)
7145 (let ((e (match-end 1))
7146 (b (if (>= org-cycle-separator-lines 0)
7147 (match-beginning 1)
7148 (save-excursion
7149 (goto-char (match-beginning 0))
7150 (skip-chars-backward " \t\n")
7151 (line-end-position)))))
7152 (outline-flag-region b e nil))))))))
7153 ;; Never hide empty lines at the end of the file.
7154 (save-excursion
7155 (goto-char (point-max))
7156 (outline-previous-heading)
7157 (outline-end-of-heading)
7158 (when (and (looking-at "[ \t\n]+")
7159 (= (match-end 0) (point-max)))
7160 (outline-flag-region (point) (match-end 0) nil))))
7162 (defun org-show-empty-lines-in-parent ()
7163 "Move to the parent and re-show empty lines before visible headlines."
7164 (save-excursion
7165 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7166 (org-cycle-show-empty-lines context))))
7168 (defun org-files-list ()
7169 "Return `org-agenda-files' list, plus all open Org files.
7170 This is useful for operations that need to scan all of a user's
7171 open and agenda-wise Org files."
7172 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7173 (dolist (buf (buffer-list))
7174 (with-current-buffer buf
7175 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7176 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7177 files))
7179 (defsubst org-entry-beginning-position ()
7180 "Return the beginning position of the current entry."
7181 (save-excursion (org-back-to-heading t) (point)))
7183 (defsubst org-entry-end-position ()
7184 "Return the end position of the current entry."
7185 (save-excursion (outline-next-heading) (point)))
7187 (defun org-cycle-hide-drawers (state &optional exceptions)
7188 "Re-hide all drawers after a visibility state change.
7189 STATE should be one of the symbols listed in the docstring of
7190 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7191 a list of strings specifying which drawers should not be hidden."
7192 (when (and (derived-mode-p 'org-mode)
7193 (not (memq state '(overview folded contents))))
7194 (save-excursion
7195 (let* ((globalp (eq state 'all))
7196 (beg (if globalp (point-min) (point)))
7197 (end (if globalp (point-max)
7198 (if (eq state 'children)
7199 (save-excursion (outline-next-heading) (point))
7200 (org-end-of-subtree t)))))
7201 (goto-char beg)
7202 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7203 (unless (member-ignore-case (match-string 1) exceptions)
7204 (let ((drawer (org-element-at-point)))
7205 (when (memq (org-element-type drawer) '(drawer property-drawer))
7206 (org-flag-drawer t drawer)
7207 ;; Make sure to skip drawer entirely or we might flag
7208 ;; it another time when matching its ending line with
7209 ;; `org-drawer-regexp'.
7210 (goto-char (org-element-property :end drawer))))))))))
7212 (defun org-flag-drawer (flag &optional element)
7213 "When FLAG is non-nil, hide the drawer we are at.
7214 Otherwise make it visible. When optional argument ELEMENT is
7215 a parsed drawer, as returned by `org-element-at-point', hide or
7216 show that drawer instead."
7217 (let ((drawer (or element
7218 (and (save-excursion
7219 (beginning-of-line)
7220 (looking-at-p org-drawer-regexp))
7221 (org-element-at-point)))))
7222 (when (memq (org-element-type drawer) '(drawer property-drawer))
7223 (let ((post (org-element-property :post-affiliated drawer)))
7224 (save-excursion
7225 (outline-flag-region
7226 (progn (goto-char post) (line-end-position))
7227 (progn (goto-char (org-element-property :end drawer))
7228 (skip-chars-backward " \r\t\n")
7229 (line-end-position))
7230 flag))
7231 ;; When the drawer is hidden away, make sure point lies in
7232 ;; a visible part of the buffer.
7233 (when (and flag (> (line-beginning-position) post))
7234 (goto-char post))))))
7236 (defun org-subtree-end-visible-p ()
7237 "Is the end of the current subtree visible?"
7238 (pos-visible-in-window-p
7239 (save-excursion (org-end-of-subtree t) (point))))
7241 (defun org-first-headline-recenter ()
7242 "Move cursor to the first headline and recenter the headline."
7243 (let ((window (get-buffer-window)))
7244 (when window
7245 (goto-char (point-min))
7246 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7247 (set-window-start window (line-beginning-position))))))
7249 ;;; Saving and restoring visibility
7251 (defun org-outline-overlay-data (&optional use-markers)
7252 "Return a list of the locations of all outline overlays.
7253 These are overlays with the `invisible' property value `outline'.
7254 The return value is a list of cons cells, with start and stop
7255 positions for each overlay.
7256 If USE-MARKERS is set, return the positions as markers."
7257 (let (beg end)
7258 (org-with-wide-buffer
7259 (delq nil
7260 (mapcar (lambda (o)
7261 (when (eq (overlay-get o 'invisible) 'outline)
7262 (setq beg (overlay-start o)
7263 end (overlay-end o))
7264 (and beg end (> end beg)
7265 (if use-markers
7266 (cons (copy-marker beg)
7267 (copy-marker end t))
7268 (cons beg end)))))
7269 (overlays-in (point-min) (point-max)))))))
7271 (defun org-set-outline-overlay-data (data)
7272 "Create visibility overlays for all positions in DATA.
7273 DATA should have been made by `org-outline-overlay-data'."
7274 (org-with-wide-buffer
7275 (outline-show-all)
7276 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7278 ;;; Folding of blocks
7280 (defvar-local org-hide-block-overlays nil
7281 "Overlays hiding blocks.")
7283 (defun org-block-map (function &optional start end)
7284 "Call FUNCTION at the head of all source blocks in the current buffer.
7285 Optional arguments START and END can be used to limit the range."
7286 (let ((start (or start (point-min)))
7287 (end (or end (point-max))))
7288 (save-excursion
7289 (goto-char start)
7290 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7291 (save-excursion
7292 (save-match-data
7293 (goto-char (match-beginning 0))
7294 (funcall function)))))))
7296 (defun org-hide-block-toggle-all ()
7297 "Toggle the visibility of all blocks in the current buffer."
7298 (org-block-map 'org-hide-block-toggle))
7300 (defun org-hide-block-all ()
7301 "Fold all blocks in the current buffer."
7302 (interactive)
7303 (org-show-block-all)
7304 (org-block-map 'org-hide-block-toggle-maybe))
7306 (defun org-show-block-all ()
7307 "Unfold all blocks in the current buffer."
7308 (interactive)
7309 (mapc #'delete-overlay org-hide-block-overlays)
7310 (setq org-hide-block-overlays nil))
7312 (defun org-hide-block-toggle-maybe ()
7313 "Toggle visibility of block at point.
7314 Unlike to `org-hide-block-toggle', this function does not throw
7315 an error. Return a non-nil value when toggling is successful."
7316 (interactive)
7317 (ignore-errors (org-hide-block-toggle)))
7319 (defun org-hide-block-toggle (&optional force)
7320 "Toggle the visibility of the current block.
7321 When optional argument FORCE is `off', make block visible. If it
7322 is non-nil, hide it unconditionally. Throw an error when not at
7323 a block. Return a non-nil value when toggling is successful."
7324 (interactive)
7325 (let ((element (org-element-at-point)))
7326 (unless (memq (org-element-type element)
7327 '(center-block comment-block dynamic-block example-block
7328 export-block quote-block special-block
7329 src-block verse-block))
7330 (user-error "Not at a block"))
7331 (let* ((start (save-excursion
7332 (goto-char (org-element-property :post-affiliated element))
7333 (line-end-position)))
7334 (end (save-excursion
7335 (goto-char (org-element-property :end element))
7336 (skip-chars-backward " \r\t\n")
7337 (line-end-position)))
7338 (overlays (overlays-at start)))
7339 (cond
7340 ;; Do nothing when not before or at the block opening line or
7341 ;; at the block closing line.
7342 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7343 ((and (not (eq force 'off))
7344 (not (memq t (mapcar
7345 (lambda (o)
7346 (eq (overlay-get o 'invisible) 'org-hide-block))
7347 overlays))))
7348 (let ((ov (make-overlay start end)))
7349 (overlay-put ov 'invisible 'org-hide-block)
7350 ;; Make the block accessible to `isearch'.
7351 (overlay-put
7352 ov 'isearch-open-invisible
7353 (lambda (ov)
7354 (when (memq ov org-hide-block-overlays)
7355 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7356 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7357 (delete-overlay ov))))
7358 (push ov org-hide-block-overlays)
7359 ;; When the block is hidden away, make sure point is left in
7360 ;; a visible part of the buffer.
7361 (when (> (line-beginning-position) start)
7362 (goto-char start)
7363 (beginning-of-line))
7364 ;; Signal successful toggling.
7366 ((or (not force) (eq force 'off))
7367 (dolist (ov overlays t)
7368 (when (memq ov org-hide-block-overlays)
7369 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7370 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7371 (delete-overlay ov))))))))
7373 ;; Remove overlays when changing major mode
7374 (add-hook 'org-mode-hook
7375 (lambda () (add-hook 'change-major-mode-hook
7376 'org-show-block-all 'append 'local)))
7378 ;;; Org-goto
7380 (defvar org-goto-window-configuration nil)
7381 (defvar org-goto-marker nil)
7382 (defvar org-goto-map)
7383 (defun org-goto-map ()
7384 "Set the keymap `org-goto'."
7385 (setq org-goto-map
7386 (let ((map (make-sparse-keymap)))
7387 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7388 mouse-drag-region universal-argument org-occur)))
7389 (dolist (cmd cmds)
7390 (substitute-key-definition cmd cmd map global-map)))
7391 (suppress-keymap map)
7392 (org-defkey map "\C-m" 'org-goto-ret)
7393 (org-defkey map [(return)] 'org-goto-ret)
7394 (org-defkey map [(left)] 'org-goto-left)
7395 (org-defkey map [(right)] 'org-goto-right)
7396 (org-defkey map [(control ?g)] 'org-goto-quit)
7397 (org-defkey map "\C-i" 'org-cycle)
7398 (org-defkey map [(tab)] 'org-cycle)
7399 (org-defkey map [(down)] 'outline-next-visible-heading)
7400 (org-defkey map [(up)] 'outline-previous-visible-heading)
7401 (if org-goto-auto-isearch
7402 (if (fboundp 'define-key-after)
7403 (define-key-after map [t] 'org-goto-local-auto-isearch)
7404 nil)
7405 (org-defkey map "q" 'org-goto-quit)
7406 (org-defkey map "n" 'outline-next-visible-heading)
7407 (org-defkey map "p" 'outline-previous-visible-heading)
7408 (org-defkey map "f" 'outline-forward-same-level)
7409 (org-defkey map "b" 'outline-backward-same-level)
7410 (org-defkey map "u" 'outline-up-heading))
7411 (org-defkey map "/" 'org-occur)
7412 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7413 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7414 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7415 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7416 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7417 map)))
7419 (defconst org-goto-help
7420 "Browse buffer copy, to find location or copy text.%s
7421 RET=jump to location C-g=quit and return to previous location
7422 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7424 (defvar org-goto-start-pos) ; dynamically scoped parameter
7426 (defun org-goto (&optional alternative-interface)
7427 "Look up a different location in the current file, keeping current visibility.
7429 When you want look-up or go to a different location in a
7430 document, the fastest way is often to fold the entire buffer and
7431 then dive into the tree. This method has the disadvantage, that
7432 the previous location will be folded, which may not be what you
7433 want.
7435 This command works around this by showing a copy of the current
7436 buffer in an indirect buffer, in overview mode. You can dive
7437 into the tree in that copy, use org-occur and incremental search
7438 to find a location. When pressing RET or `Q', the command
7439 returns to the original buffer in which the visibility is still
7440 unchanged. After RET it will also jump to the location selected
7441 in the indirect buffer and expose the headline hierarchy above.
7443 With a prefix argument, use the alternative interface: e.g., if
7444 `org-goto-interface' is `outline' use `outline-path-completion'."
7445 (interactive "P")
7446 (org-goto-map)
7447 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7448 (org-refile-use-outline-path t)
7449 (org-refile-target-verify-function nil)
7450 (interface
7451 (if (not alternative-interface)
7452 org-goto-interface
7453 (if (eq org-goto-interface 'outline)
7454 'outline-path-completion
7455 'outline)))
7456 (org-goto-start-pos (point))
7457 (selected-point
7458 (if (eq interface 'outline)
7459 (car (org-get-location (current-buffer) org-goto-help))
7460 (let ((pa (org-refile-get-location "Goto")))
7461 (org-refile-check-position pa)
7462 (nth 3 pa)))))
7463 (if selected-point
7464 (progn
7465 (org-mark-ring-push org-goto-start-pos)
7466 (goto-char selected-point)
7467 (when (or (org-invisible-p) (org-invisible-p2))
7468 (org-show-context 'org-goto)))
7469 (message "Quit"))))
7471 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7472 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7473 (defvar org-goto-local-auto-isearch-map) ; defined below
7475 (defun org-get-location (_buf help)
7476 "Let the user select a location in current buffer.
7477 This function uses a recursive edit. It returns the selected position
7478 or nil."
7479 (org-no-popups
7480 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7481 (isearch-hide-immediately nil)
7482 (isearch-search-fun-function
7483 (lambda () 'org-goto-local-search-headings))
7484 (org-goto-selected-point org-goto-exit-command))
7485 (save-excursion
7486 (save-window-excursion
7487 (delete-other-windows)
7488 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7489 (pop-to-buffer-same-window
7490 (condition-case nil
7491 (make-indirect-buffer (current-buffer) "*org-goto*")
7492 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7493 (with-output-to-temp-buffer "*Org Help*"
7494 (princ (format help (if org-goto-auto-isearch
7495 " Just type for auto-isearch."
7496 " n/p/f/b/u to navigate, q to quit."))))
7497 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7498 (setq buffer-read-only nil)
7499 (let ((org-startup-truncated t)
7500 (org-startup-folded nil)
7501 (org-startup-align-all-tables nil))
7502 (org-mode)
7503 (org-overview))
7504 (setq buffer-read-only t)
7505 (if (and (boundp 'org-goto-start-pos)
7506 (integer-or-marker-p org-goto-start-pos))
7507 (progn (goto-char org-goto-start-pos)
7508 (when (org-invisible-p)
7509 (org-show-set-visibility 'lineage)))
7510 (goto-char (point-min)))
7511 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7512 (message "Select location and press RET")
7513 (use-local-map org-goto-map)
7514 (recursive-edit)))
7515 (kill-buffer "*org-goto*")
7516 (cons org-goto-selected-point org-goto-exit-command))))
7518 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7519 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7520 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7521 (if (fboundp 'isearch-other-control-char)
7522 (progn
7523 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7524 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7525 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7526 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7527 (define-key org-goto-local-auto-isearch-map [return] nil))
7529 (defun org-goto-local-search-headings (string bound noerror)
7530 "Search and make sure that any matches are in headlines."
7531 (catch 'return
7532 (while (if isearch-forward
7533 (search-forward string bound noerror)
7534 (search-backward string bound noerror))
7535 (when (save-match-data
7536 (and (save-excursion
7537 (beginning-of-line)
7538 (looking-at org-complex-heading-regexp))
7539 (or (not (match-beginning 5))
7540 (< (point) (match-beginning 5)))))
7541 (throw 'return (point))))))
7543 (defun org-goto-local-auto-isearch ()
7544 "Start isearch."
7545 (interactive)
7546 (goto-char (point-min))
7547 (let ((keys (this-command-keys)))
7548 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7549 (isearch-mode t)
7550 (isearch-process-search-char (string-to-char keys)))))
7552 (defun org-goto-ret (&optional _arg)
7553 "Finish `org-goto' by going to the new location."
7554 (interactive "P")
7555 (setq org-goto-selected-point (point))
7556 (setq org-goto-exit-command 'return)
7557 (throw 'exit nil))
7559 (defun org-goto-left ()
7560 "Finish `org-goto' by going to the new location."
7561 (interactive)
7562 (if (org-at-heading-p)
7563 (progn
7564 (beginning-of-line 1)
7565 (setq org-goto-selected-point (point)
7566 org-goto-exit-command 'left)
7567 (throw 'exit nil))
7568 (user-error "Not on a heading")))
7570 (defun org-goto-right ()
7571 "Finish `org-goto' by going to the new location."
7572 (interactive)
7573 (if (org-at-heading-p)
7574 (progn
7575 (setq org-goto-selected-point (point)
7576 org-goto-exit-command 'right)
7577 (throw 'exit nil))
7578 (user-error "Not on a heading")))
7580 (defun org-goto-quit ()
7581 "Finish `org-goto' without cursor motion."
7582 (interactive)
7583 (setq org-goto-selected-point nil)
7584 (setq org-goto-exit-command 'quit)
7585 (throw 'exit nil))
7587 ;;; Indirect buffer display of subtrees
7589 (defvar org-indirect-dedicated-frame nil
7590 "This is the frame being used for indirect tree display.")
7591 (defvar org-last-indirect-buffer nil)
7593 (defun org-tree-to-indirect-buffer (&optional arg)
7594 "Create indirect buffer and narrow it to current subtree.
7596 With a numerical prefix ARG, go up to this level and then take that tree.
7597 If ARG is negative, go up that many levels.
7599 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7600 indirect buffer previously made with this command, to avoid proliferation of
7601 indirect buffers. However, when you call the command with a \
7602 `\\[universal-argument]' prefix, or
7603 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7604 so that you can work with several indirect buffers at the same time. If
7605 `org-indirect-buffer-display' is `dedicated-frame', the \
7606 `\\[universal-argument]' prefix also
7607 requests that a new frame be made for the new buffer, so that the dedicated
7608 frame is not changed."
7609 (interactive "P")
7610 (let ((cbuf (current-buffer))
7611 (cwin (selected-window))
7612 (pos (point))
7613 beg end level heading ibuf)
7614 (save-excursion
7615 (org-back-to-heading t)
7616 (when (numberp arg)
7617 (setq level (org-outline-level))
7618 (when (< arg 0) (setq arg (+ level arg)))
7619 (while (> (setq level (org-outline-level)) arg)
7620 (org-up-heading-safe)))
7621 (setq beg (point)
7622 heading (org-get-heading 'no-tags))
7623 (org-end-of-subtree t t)
7624 (when (org-at-heading-p) (backward-char 1))
7625 (setq end (point)))
7626 (when (and (buffer-live-p org-last-indirect-buffer)
7627 (not (eq org-indirect-buffer-display 'new-frame))
7628 (not arg))
7629 (kill-buffer org-last-indirect-buffer))
7630 (setq ibuf (org-get-indirect-buffer cbuf heading)
7631 org-last-indirect-buffer ibuf)
7632 (cond
7633 ((or (eq org-indirect-buffer-display 'new-frame)
7634 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7635 (select-frame (make-frame))
7636 (delete-other-windows)
7637 (pop-to-buffer-same-window ibuf)
7638 (org-set-frame-title heading))
7639 ((eq org-indirect-buffer-display 'dedicated-frame)
7640 (raise-frame
7641 (select-frame (or (and org-indirect-dedicated-frame
7642 (frame-live-p org-indirect-dedicated-frame)
7643 org-indirect-dedicated-frame)
7644 (setq org-indirect-dedicated-frame (make-frame)))))
7645 (delete-other-windows)
7646 (pop-to-buffer-same-window ibuf)
7647 (org-set-frame-title (concat "Indirect: " heading)))
7648 ((eq org-indirect-buffer-display 'current-window)
7649 (pop-to-buffer-same-window ibuf))
7650 ((eq org-indirect-buffer-display 'other-window)
7651 (pop-to-buffer ibuf))
7652 (t (error "Invalid value")))
7653 (narrow-to-region beg end)
7654 (outline-show-all)
7655 (goto-char pos)
7656 (run-hook-with-args 'org-cycle-hook 'all)
7657 (and (window-live-p cwin) (select-window cwin))))
7659 (defun org-get-indirect-buffer (&optional buffer heading)
7660 (setq buffer (or buffer (current-buffer)))
7661 (let ((n 1) (base (buffer-name buffer)) bname)
7662 (while (buffer-live-p
7663 (get-buffer
7664 (setq bname
7665 (concat base "-"
7666 (if heading (concat heading "-" (number-to-string n))
7667 (number-to-string n))))))
7668 (setq n (1+ n)))
7669 (condition-case nil
7670 (make-indirect-buffer buffer bname 'clone)
7671 (error (make-indirect-buffer buffer bname)))))
7673 (defun org-set-frame-title (title)
7674 "Set the title of the current frame to the string TITLE."
7675 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7677 ;;;; Structure editing
7679 ;;; Inserting headlines
7681 (defun org--line-empty-p (n)
7682 "Is the Nth next line empty?
7684 Counts the current line as N = 1 and the previous line as N = 0;
7685 see `beginning-of-line'."
7686 (save-excursion
7687 (and (not (bobp))
7688 (or (beginning-of-line n) t)
7689 (save-match-data
7690 (looking-at "[ \t]*$")))))
7692 (defun org-previous-line-empty-p ()
7693 "Is the previous line a blank line?
7694 When NEXT is non-nil, check the next line instead."
7695 (org--line-empty-p 0))
7697 (defun org-next-line-empty-p ()
7698 "Is the previous line a blank line?
7699 When NEXT is non-nil, check the next line instead."
7700 (org--line-empty-p 2))
7702 (defun org--blank-before-heading-p (&optional parent)
7703 "Non-nil when an empty line should precede a new heading here.
7704 When optional argument PARENT is non-nil, consider parent
7705 headline instead of current one."
7706 (pcase (assq 'heading org-blank-before-new-entry)
7707 (`(heading . auto)
7708 (save-excursion
7709 (org-with-limited-levels
7710 (unless (and (org-before-first-heading-p)
7711 (not (outline-next-heading)))
7712 (org-back-to-heading t)
7713 (when parent (org-up-heading-safe))
7714 (cond ((not (bobp))
7715 (org-previous-line-empty-p))
7716 ((outline-next-heading)
7717 (org-previous-line-empty-p))
7718 ;; Ignore trailing spaces on last buffer line.
7719 ((progn (skip-chars-backward " \t") (bolp))
7720 (org-previous-line-empty-p))
7721 (t nil))))))
7722 (`(heading . ,value) value)
7723 (_ nil)))
7725 (defun org-insert-heading (&optional arg invisible-ok top)
7726 "Insert a new heading or an item with the same depth at point.
7728 If point is at the beginning of a heading, insert a new heading
7729 or a new headline above the current one. When at the beginning
7730 of a regular line of text, turn it into a heading.
7732 If point is in the middle of a line, split it and create a new
7733 headline with the text in the current line after point (see
7734 `org-M-RET-may-split-line' on how to modify this behavior). As
7735 a special case, on a headline, splitting can only happen on the
7736 title itself. E.g., this excludes breaking stars or tags.
7738 With a `\\[universal-argument]' prefix, set \
7739 `org-insert-heading-respect-content' to
7740 a non-nil value for the duration of the command. This forces the
7741 insertion of a heading after the current subtree, independently
7742 on the location of point.
7744 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7745 insert the heading at the end of the tree
7746 above the current heading. For example, if point is within a
7747 2nd-level heading, then it will insert a 2nd-level heading at
7748 the end of the 1st-level parent subtree.
7750 When INVISIBLE-OK is set, stop at invisible headlines when going
7751 back. This is important for non-interactive uses of the
7752 command.
7754 When optional argument TOP is non-nil, insert a level 1 heading,
7755 unconditionally."
7756 (interactive "P")
7757 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7758 (level (org-current-level))
7759 (stars (make-string (if (and level (not top)) level 1) ?*)))
7760 (cond
7761 ((or org-insert-heading-respect-content
7762 (member arg '((4) (16)))
7763 (and (not invisible-ok)
7764 (invisible-p (max (1- (point)) (point-min)))))
7765 ;; Position point at the location of insertion.
7766 (if (not level) ;before first headline
7767 (org-with-limited-levels (outline-next-heading))
7768 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7769 ;; is nil.
7770 (org-with-limited-levels (org-back-to-heading invisible-ok))
7771 (cond ((equal arg '(16))
7772 (org-up-heading-safe)
7773 (org-end-of-subtree t t))
7775 (org-end-of-subtree t t))))
7776 (unless (bolp) (insert "\n")) ;ensure final newline
7777 (unless (and blank? (org-previous-line-empty-p))
7778 (org-N-empty-lines-before-current (if blank? 1 0)))
7779 (insert stars " \n")
7780 (forward-char -1))
7781 ;; At a headline...
7782 ((org-at-heading-p)
7783 (cond ((bolp)
7784 (when blank? (save-excursion (insert "\n")))
7785 (save-excursion (insert stars " \n"))
7786 (unless (and blank? (org-previous-line-empty-p))
7787 (org-N-empty-lines-before-current (if blank? 1 0)))
7788 (end-of-line))
7789 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7790 (org-match-line org-complex-heading-regexp)
7791 (org-pos-in-match-range (point) 4))
7792 ;; Grab the text that should moved to the new headline.
7793 ;; Preserve tags.
7794 (let ((split (delete-and-extract-region (point) (match-end 4))))
7795 (if (looking-at "[ \t]*$") (replace-match "")
7796 (org-set-tags nil t))
7797 (end-of-line)
7798 (when blank? (insert "\n"))
7799 (insert "\n" stars " ")
7800 (when (org-string-nw-p split) (insert split))
7801 (when (eobp) (save-excursion (insert "\n")))))
7803 (end-of-line)
7804 (when blank? (insert "\n"))
7805 (insert "\n" stars " ")
7806 (when (eobp) (save-excursion (insert "\n"))))))
7807 ;; On regular text, turn line into a headline or split, if
7808 ;; appropriate.
7809 ((bolp)
7810 (insert stars " ")
7811 (unless (and blank? (org-previous-line-empty-p))
7812 (org-N-empty-lines-before-current (if blank? 1 0))))
7814 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7815 (end-of-line))
7816 (insert "\n" stars " ")
7817 (unless (and blank? (org-previous-line-empty-p))
7818 (org-N-empty-lines-before-current (if blank? 1 0))))))
7819 (run-hooks 'org-insert-heading-hook))
7821 (defun org-N-empty-lines-before-current (n)
7822 "Make the number of empty lines before current exactly N.
7823 So this will delete or add empty lines."
7824 (let ((column (current-column)))
7825 (beginning-of-line)
7826 (unless (bobp)
7827 (let ((start (save-excursion
7828 (skip-chars-backward " \r\t\n")
7829 (line-end-position))))
7830 (delete-region start (line-end-position 0))))
7831 (insert (make-string n ?\n))
7832 (move-to-column column)))
7834 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7835 "Return the heading of the current entry, without the stars.
7836 When NO-TAGS is non-nil, don't include tags.
7837 When NO-TODO is non-nil, don't include TODO keywords.
7838 When NO-PRIORITY is non-nil, don't include priority cookie.
7839 When NO-COMMENT is non-nil, don't include COMMENT string."
7840 (save-excursion
7841 (org-back-to-heading t)
7842 (let ((case-fold-search nil))
7843 (looking-at org-complex-heading-regexp)
7844 (let ((todo (and (not no-todo) (match-string 2)))
7845 (priority (and (not no-priority) (match-string 3)))
7846 (headline (pcase (match-string 4)
7847 (`nil "")
7848 ((and (guard no-comment) h)
7849 (replace-regexp-in-string
7850 (eval-when-compile
7851 (format "\\`%s[ \t]+" org-comment-string))
7852 "" h))
7853 (h h)))
7854 (tags (and (not no-tags) (match-string 5))))
7855 (mapconcat #'identity
7856 (delq nil (list todo priority headline tags))
7857 " ")))))
7859 (defvar orgstruct-mode) ; defined below
7861 (defun org-heading-components ()
7862 "Return the components of the current heading.
7863 This is a list with the following elements:
7864 - the level as an integer
7865 - the reduced level, different if `org-odd-levels-only' is set.
7866 - the TODO keyword, or nil
7867 - the priority character, like ?A, or nil if no priority is given
7868 - the headline text itself, or the tags string if no headline text
7869 - the tags string, or nil."
7870 (save-excursion
7871 (org-back-to-heading t)
7872 (when (let (case-fold-search)
7873 (looking-at
7874 (if orgstruct-mode
7875 org-heading-regexp
7876 org-complex-heading-regexp)))
7877 (if orgstruct-mode
7878 (list (length (match-string 1))
7879 (org-reduced-level (length (match-string 1)))
7882 (match-string 2)
7883 nil)
7884 (list (length (match-string 1))
7885 (org-reduced-level (length (match-string 1)))
7886 (match-string-no-properties 2)
7887 (and (match-end 3) (aref (match-string 3) 2))
7888 (match-string-no-properties 4)
7889 (match-string-no-properties 5))))))
7891 (defun org-get-entry ()
7892 "Get the entry text, after heading, entire subtree."
7893 (save-excursion
7894 (org-back-to-heading t)
7895 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7897 (defun org-edit-headline (&optional heading)
7898 "Edit the current headline.
7899 Set it to HEADING when provided."
7900 (interactive)
7901 (org-with-wide-buffer
7902 (org-back-to-heading t)
7903 (let ((case-fold-search nil))
7904 (when (looking-at org-complex-heading-regexp)
7905 (let* ((old (match-string-no-properties 4))
7906 (new (save-match-data
7907 (org-trim (or heading (read-string "Edit: " old))))))
7908 (unless (equal old new)
7909 (if old (replace-match new t t nil 4)
7910 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7911 (insert " " new))
7912 (org-set-tags nil t)
7913 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7915 (defun org-insert-heading-after-current ()
7916 "Insert a new heading with same level as current, after current subtree."
7917 (interactive)
7918 (org-back-to-heading)
7919 (org-insert-heading)
7920 (org-move-subtree-down)
7921 (end-of-line 1))
7923 (defun org-insert-heading-respect-content (&optional invisible-ok)
7924 "Insert heading with `org-insert-heading-respect-content' set to t."
7925 (interactive)
7926 (org-insert-heading '(4) invisible-ok))
7928 (defun org-insert-todo-heading-respect-content (&optional force-state)
7929 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7930 (interactive)
7931 (org-insert-todo-heading force-state '(4)))
7933 (defun org-insert-todo-heading (arg &optional force-heading)
7934 "Insert a new heading with the same level and TODO state as current heading.
7936 If the heading has no TODO state, or if the state is DONE, use
7937 the first state (TODO by default). Also with one prefix arg,
7938 force first state. With two prefix args, force inserting at the
7939 end of the parent subtree.
7941 When called at a plain list item, insert a new item with an
7942 unchecked check box."
7943 (interactive "P")
7944 (when (or force-heading (not (org-insert-item 'checkbox)))
7945 (org-insert-heading (or (and (equal arg '(16)) '(16))
7946 force-heading))
7947 (save-excursion
7948 (org-back-to-heading)
7949 (outline-previous-heading)
7950 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7951 (let* ((new-mark-x
7952 (if (or (equal arg '(4))
7953 (not (match-beginning 2))
7954 (member (match-string 2) org-done-keywords))
7955 (car org-todo-keywords-1)
7956 (match-string 2)))
7957 (new-mark
7959 (run-hook-with-args-until-success
7960 'org-todo-get-default-hook new-mark-x nil)
7961 new-mark-x)))
7962 (beginning-of-line 1)
7963 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7964 (if org-treat-insert-todo-heading-as-state-change
7965 (org-todo new-mark)
7966 (insert new-mark " "))))
7967 (when org-provide-todo-statistics
7968 (org-update-parent-todo-statistics))))
7970 (defun org-insert-subheading (arg)
7971 "Insert a new subheading and demote it.
7972 Works for outline headings and for plain lists alike."
7973 (interactive "P")
7974 (org-insert-heading arg)
7975 (cond
7976 ((org-at-heading-p) (org-do-demote))
7977 ((org-at-item-p) (org-indent-item))))
7979 (defun org-insert-todo-subheading (arg)
7980 "Insert a new subheading with TODO keyword or checkbox and demote it.
7981 Works for outline headings and for plain lists alike."
7982 (interactive "P")
7983 (org-insert-todo-heading arg)
7984 (cond
7985 ((org-at-heading-p) (org-do-demote))
7986 ((org-at-item-p) (org-indent-item))))
7988 ;;; Promotion and Demotion
7990 (defvar org-after-demote-entry-hook nil
7991 "Hook run after an entry has been demoted.
7992 The cursor will be at the beginning of the entry.
7993 When a subtree is being demoted, the hook will be called for each node.")
7995 (defvar org-after-promote-entry-hook nil
7996 "Hook run after an entry has been promoted.
7997 The cursor will be at the beginning of the entry.
7998 When a subtree is being promoted, the hook will be called for each node.")
8000 (defun org-promote-subtree ()
8001 "Promote the entire subtree.
8002 See also `org-promote'."
8003 (interactive)
8004 (save-excursion
8005 (org-with-limited-levels (org-map-tree 'org-promote)))
8006 (org-fix-position-after-promote))
8008 (defun org-demote-subtree ()
8009 "Demote the entire subtree.
8010 See `org-demote' and `org-promote'."
8011 (interactive)
8012 (save-excursion
8013 (org-with-limited-levels (org-map-tree 'org-demote)))
8014 (org-fix-position-after-promote))
8016 (defun org-do-promote ()
8017 "Promote the current heading higher up the tree.
8018 If the region is active in `transient-mark-mode', promote all
8019 headings in the region."
8020 (interactive)
8021 (save-excursion
8022 (if (org-region-active-p)
8023 (org-map-region 'org-promote (region-beginning) (region-end))
8024 (org-promote)))
8025 (org-fix-position-after-promote))
8027 (defun org-do-demote ()
8028 "Demote the current heading lower down the tree.
8029 If the region is active in `transient-mark-mode', demote all
8030 headings in the region."
8031 (interactive)
8032 (save-excursion
8033 (if (org-region-active-p)
8034 (org-map-region 'org-demote (region-beginning) (region-end))
8035 (org-demote)))
8036 (org-fix-position-after-promote))
8038 (defun org-fix-position-after-promote ()
8039 "Fix cursor position and indentation after demoting/promoting."
8040 (let ((pos (point)))
8041 (when (save-excursion
8042 (beginning-of-line)
8043 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8044 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8045 (cond ((eobp) (insert " "))
8046 ((eolp) (insert " "))
8047 ((equal (char-after) ?\s) (forward-char 1))))))
8049 (defun org-current-level ()
8050 "Return the level of the current entry, or nil if before the first headline.
8051 The level is the number of stars at the beginning of the
8052 headline. Use `org-reduced-level' to remove the effect of
8053 `org-odd-levels'. Unlike to `org-outline-level', this function
8054 ignores inlinetasks."
8055 (let ((level (org-with-limited-levels (org-outline-level))))
8056 (and (> level 0) level)))
8058 (defun org-get-previous-line-level ()
8059 "Return the outline depth of the last headline before the current line.
8060 Returns 0 for the first headline in the buffer, and nil if before the
8061 first headline."
8062 (and (org-current-level)
8063 (or (and (/= (line-beginning-position) (point-min))
8064 (save-excursion (beginning-of-line 0) (org-current-level)))
8065 0)))
8067 (defun org-reduced-level (l)
8068 "Compute the effective level of a heading.
8069 This takes into account the setting of `org-odd-levels-only'."
8070 (cond
8071 ((zerop l) 0)
8072 (org-odd-levels-only (1+ (floor (/ l 2))))
8073 (t l)))
8075 (defun org-level-increment ()
8076 "Return the number of stars that will be added or removed at a
8077 time to headlines when structure editing, based on the value of
8078 `org-odd-levels-only'."
8079 (if org-odd-levels-only 2 1))
8081 (defun org-get-valid-level (level &optional change)
8082 "Rectify a level change under the influence of `org-odd-levels-only'.
8083 LEVEL is a current level, CHANGE is by how much the level should
8084 be modified. Even if CHANGE is nil, LEVEL may be returned
8085 modified because even level numbers will become the next higher
8086 odd number. Returns values greater than 0."
8087 (if org-odd-levels-only
8088 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8089 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8090 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8091 (max 1 (+ level (or change 0)))))
8093 (defun org-promote ()
8094 "Promote the current heading higher up the tree."
8095 (org-with-wide-buffer
8096 (org-back-to-heading t)
8097 (let* ((after-change-functions (remq 'flyspell-after-change-function
8098 after-change-functions))
8099 (level (save-match-data (funcall outline-level)))
8100 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8101 (diff (abs (- level (length up-head) -1))))
8102 (cond
8103 ((and (= level 1) org-allow-promoting-top-level-subtree)
8104 (replace-match "# " nil t))
8105 ((= level 1)
8106 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8107 (t (replace-match up-head nil t)))
8108 (unless (= level 1)
8109 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8110 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8111 (run-hooks 'org-after-promote-entry-hook))))
8113 (defun org-demote ()
8114 "Demote the current heading lower down the tree."
8115 (org-with-wide-buffer
8116 (org-back-to-heading t)
8117 (let* ((after-change-functions (remq 'flyspell-after-change-function
8118 after-change-functions))
8119 (level (save-match-data (funcall outline-level)))
8120 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8121 (diff (abs (- level (length down-head) -1))))
8122 (replace-match down-head nil t)
8123 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8124 (when org-adapt-indentation (org-fixup-indentation diff))
8125 (run-hooks 'org-after-demote-entry-hook))))
8127 (defun org-cycle-level ()
8128 "Cycle the level of an empty headline through possible states.
8129 This goes first to child, then to parent, level, then up the hierarchy.
8130 After top level, it switches back to sibling level."
8131 (interactive)
8132 (let ((org-adapt-indentation nil))
8133 (when (org-point-at-end-of-empty-headline)
8134 (setq this-command 'org-cycle-level) ; Only needed for caching
8135 (let ((cur-level (org-current-level))
8136 (prev-level (org-get-previous-line-level)))
8137 (cond
8138 ;; If first headline in file, promote to top-level.
8139 ((= prev-level 0)
8140 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8141 do (org-do-promote)))
8142 ;; If same level as prev, demote one.
8143 ((= prev-level cur-level)
8144 (org-do-demote))
8145 ;; If parent is top-level, promote to top level if not already.
8146 ((= prev-level 1)
8147 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8148 do (org-do-promote)))
8149 ;; If top-level, return to prev-level.
8150 ((= cur-level 1)
8151 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8152 do (org-do-demote)))
8153 ;; If less than prev-level, promote one.
8154 ((< cur-level prev-level)
8155 (org-do-promote))
8156 ;; If deeper than prev-level, promote until higher than
8157 ;; prev-level.
8158 ((> cur-level prev-level)
8159 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8160 do (org-do-promote))))
8161 t))))
8163 (defun org-map-tree (fun)
8164 "Call FUN for every heading underneath the current one."
8165 (org-back-to-heading t)
8166 (let ((level (funcall outline-level)))
8167 (save-excursion
8168 (funcall fun)
8169 (while (and (progn
8170 (outline-next-heading)
8171 (> (funcall outline-level) level))
8172 (not (eobp)))
8173 (funcall fun)))))
8175 (defun org-map-region (fun beg end)
8176 "Call FUN for every heading between BEG and END."
8177 (let ((org-ignore-region t))
8178 (save-excursion
8179 (setq end (copy-marker end))
8180 (goto-char beg)
8181 (when (and (re-search-forward org-outline-regexp-bol nil t)
8182 (< (point) end))
8183 (funcall fun))
8184 (while (and (progn
8185 (outline-next-heading)
8186 (< (point) end))
8187 (not (eobp)))
8188 (funcall fun)))))
8190 (defun org-fixup-indentation (diff)
8191 "Change the indentation in the current entry by DIFF.
8193 DIFF is an integer. Indentation is done according to the
8194 following rules:
8196 - Planning information and property drawers are always indented
8197 according to the new level of the headline;
8199 - Footnote definitions and their contents are ignored;
8201 - Inlinetasks' boundaries are not shifted;
8203 - Empty lines are ignored;
8205 - Other lines' indentation are shifted by DIFF columns, unless
8206 it would introduce a structural change in the document, in
8207 which case no shifting is done at all.
8209 Assume point is at a heading or an inlinetask beginning."
8210 (org-with-wide-buffer
8211 (narrow-to-region (line-beginning-position)
8212 (save-excursion
8213 (if (org-with-limited-levels (org-at-heading-p))
8214 (org-with-limited-levels (outline-next-heading))
8215 (org-inlinetask-goto-end))
8216 (point)))
8217 (forward-line)
8218 ;; Indent properly planning info and property drawer.
8219 (when (looking-at-p org-planning-line-re)
8220 (org-indent-line)
8221 (forward-line))
8222 (when (looking-at org-property-drawer-re)
8223 (goto-char (match-end 0))
8224 (forward-line)
8225 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8226 (catch 'no-shift
8227 (when (zerop diff) (throw 'no-shift nil))
8228 ;; If DIFF is negative, first check if a shift is possible at all
8229 ;; (e.g., it doesn't break structure). This can only happen if
8230 ;; some contents are not properly indented.
8231 (let ((case-fold-search t))
8232 (when (< diff 0)
8233 (let ((diff (- diff))
8234 (forbidden-re (concat org-outline-regexp
8235 "\\|"
8236 (substring org-footnote-definition-re 1))))
8237 (save-excursion
8238 (while (not (eobp))
8239 (cond
8240 ((looking-at-p "[ \t]*$") (forward-line))
8241 ((and (looking-at-p org-footnote-definition-re)
8242 (let ((e (org-element-at-point)))
8243 (and (eq (org-element-type e) 'footnote-definition)
8244 (goto-char (org-element-property :end e))))))
8245 ((looking-at-p org-outline-regexp) (forward-line))
8246 ;; Give up if shifting would move before column 0 or
8247 ;; if it would introduce a headline or a footnote
8248 ;; definition.
8250 (skip-chars-forward " \t")
8251 (let ((ind (current-column)))
8252 (when (or (< ind diff)
8253 (and (= ind diff) (looking-at-p forbidden-re)))
8254 (throw 'no-shift nil)))
8255 ;; Ignore contents of example blocks and source
8256 ;; blocks if their indentation is meant to be
8257 ;; preserved. Jump to block's closing line.
8258 (beginning-of-line)
8259 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8260 (let ((e (org-element-at-point)))
8261 (and (memq (org-element-type e)
8262 '(example-block src-block))
8263 (or org-src-preserve-indentation
8264 (org-element-property :preserve-indent e))
8265 (goto-char (org-element-property :end e))
8266 (progn (skip-chars-backward " \r\t\n")
8267 (beginning-of-line)
8268 t))))
8269 (forward-line))))))))
8270 ;; Shift lines but footnote definitions, inlinetasks boundaries
8271 ;; by DIFF. Also skip contents of source or example blocks
8272 ;; when indentation is meant to be preserved.
8273 (while (not (eobp))
8274 (cond
8275 ((and (looking-at-p org-footnote-definition-re)
8276 (let ((e (org-element-at-point)))
8277 (and (eq (org-element-type e) 'footnote-definition)
8278 (goto-char (org-element-property :end e))))))
8279 ((looking-at-p org-outline-regexp) (forward-line))
8280 ((looking-at-p "[ \t]*$") (forward-line))
8282 (indent-line-to (+ (org-get-indentation) diff))
8283 (beginning-of-line)
8284 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8285 (let ((e (org-element-at-point)))
8286 (and (memq (org-element-type e)
8287 '(example-block src-block))
8288 (or org-src-preserve-indentation
8289 (org-element-property :preserve-indent e))
8290 (goto-char (org-element-property :end e))
8291 (progn (skip-chars-backward " \r\t\n")
8292 (beginning-of-line)
8293 t))))
8294 (forward-line)))))))))
8296 (defun org-convert-to-odd-levels ()
8297 "Convert an Org file with all levels allowed to one with odd levels.
8298 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8299 level 5 etc."
8300 (interactive)
8301 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8302 (let ((outline-level 'org-outline-level)
8303 (org-odd-levels-only nil) n)
8304 (save-excursion
8305 (goto-char (point-min))
8306 (while (re-search-forward "^\\*\\*+ " nil t)
8307 (setq n (- (length (match-string 0)) 2))
8308 (while (>= (setq n (1- n)) 0)
8309 (org-demote))
8310 (end-of-line 1))))))
8312 (defun org-convert-to-oddeven-levels ()
8313 "Convert an Org file with only odd levels to one with odd/even levels.
8314 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8315 file contains a section with an even level, conversion would
8316 destroy the structure of the file. An error is signaled in this
8317 case."
8318 (interactive)
8319 (goto-char (point-min))
8320 ;; First check if there are no even levels
8321 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8322 (org-show-set-visibility 'canonical)
8323 (error "Not all levels are odd in this file. Conversion not possible"))
8324 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8325 (let ((outline-regexp org-outline-regexp)
8326 (outline-level 'org-outline-level)
8327 (org-odd-levels-only nil) n)
8328 (save-excursion
8329 (goto-char (point-min))
8330 (while (re-search-forward "^\\*\\*+ " nil t)
8331 (setq n (/ (1- (length (match-string 0))) 2))
8332 (while (>= (setq n (1- n)) 0)
8333 (org-promote))
8334 (end-of-line 1))))))
8336 (defun org-tr-level (n)
8337 "Make N odd if required."
8338 (if org-odd-levels-only (1+ (/ n 2)) n))
8340 ;;; Vertical tree motion, cutting and pasting of subtrees
8342 (defun org-move-subtree-up (&optional arg)
8343 "Move the current subtree up past ARG headlines of the same level."
8344 (interactive "p")
8345 (org-move-subtree-down (- (prefix-numeric-value arg))))
8347 (defun org-move-subtree-down (&optional arg)
8348 "Move the current subtree down past ARG headlines of the same level."
8349 (interactive "p")
8350 (setq arg (prefix-numeric-value arg))
8351 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8352 'org-get-last-sibling))
8353 (ins-point (make-marker))
8354 (cnt (abs arg))
8355 (col (current-column))
8356 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8357 ;; Select the tree
8358 (org-back-to-heading)
8359 (setq beg0 (point))
8360 (save-excursion
8361 (setq ne-beg (org-back-over-empty-lines))
8362 (setq beg (point)))
8363 (save-match-data
8364 (save-excursion (outline-end-of-heading)
8365 (setq folded (org-invisible-p)))
8366 (progn (org-end-of-subtree nil t)
8367 (unless (eobp) (backward-char))))
8368 (outline-next-heading)
8369 (setq ne-end (org-back-over-empty-lines))
8370 (setq end (point))
8371 (goto-char beg0)
8372 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8373 ;; include less whitespace
8374 (save-excursion
8375 (goto-char beg)
8376 (forward-line (- ne-beg ne-end))
8377 (setq beg (point))))
8378 ;; Find insertion point, with error handling
8379 (while (> cnt 0)
8380 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8381 (progn (goto-char beg0)
8382 (user-error "Cannot move past superior level or buffer limit")))
8383 (setq cnt (1- cnt)))
8384 (when (> arg 0)
8385 ;; Moving forward - still need to move over subtree
8386 (org-end-of-subtree t t)
8387 (save-excursion
8388 (org-back-over-empty-lines)
8389 (or (bolp) (newline))))
8390 (setq ne-ins (org-back-over-empty-lines))
8391 (move-marker ins-point (point))
8392 (setq txt (buffer-substring beg end))
8393 (org-save-markers-in-region beg end)
8394 (delete-region beg end)
8395 (org-remove-empty-overlays-at beg)
8396 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8397 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8398 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8399 (let ((bbb (point)))
8400 (insert-before-markers txt)
8401 (org-reinstall-markers-in-region bbb)
8402 (move-marker ins-point bbb))
8403 (or (bolp) (insert "\n"))
8404 (setq ins-end (point))
8405 (goto-char ins-point)
8406 (org-skip-whitespace)
8407 (when (and (< arg 0)
8408 (org-first-sibling-p)
8409 (> ne-ins ne-beg))
8410 ;; Move whitespace back to beginning
8411 (save-excursion
8412 (goto-char ins-end)
8413 (let ((kill-whole-line t))
8414 (kill-line (- ne-ins ne-beg)) (point)))
8415 (insert (make-string (- ne-ins ne-beg) ?\n)))
8416 (move-marker ins-point nil)
8417 (if folded
8418 (outline-hide-subtree)
8419 (org-show-entry)
8420 (org-show-children)
8421 (org-cycle-hide-drawers 'children))
8422 (org-clean-visibility-after-subtree-move)
8423 ;; move back to the initial column we were at
8424 (move-to-column col)))
8426 (defvar org-subtree-clip ""
8427 "Clipboard for cut and paste of subtrees.
8428 This is actually only a copy of the kill, because we use the normal kill
8429 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8431 (defvar org-subtree-clip-folded nil
8432 "Was the last copied subtree folded?
8433 This is used to fold the tree back after pasting.")
8435 (defun org-cut-subtree (&optional n)
8436 "Cut the current subtree into the clipboard.
8437 With prefix arg N, cut this many sequential subtrees.
8438 This is a short-hand for marking the subtree and then cutting it."
8439 (interactive "p")
8440 (org-copy-subtree n 'cut))
8442 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8443 "Copy the current subtree it in the clipboard.
8444 With prefix arg N, copy this many sequential subtrees.
8445 This is a short-hand for marking the subtree and then copying it.
8446 If CUT is non-nil, actually cut the subtree.
8447 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8448 of some markers in the region, even if CUT is non-nil. This is
8449 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8450 (interactive "p")
8451 (let (beg end folded (beg0 (point)))
8452 (if (called-interactively-p 'any)
8453 (org-back-to-heading nil) ; take what looks like a subtree
8454 (org-back-to-heading t)) ; take what is really there
8455 (setq beg (point))
8456 (skip-chars-forward " \t\r\n")
8457 (save-match-data
8458 (if nosubtrees
8459 (outline-next-heading)
8460 (save-excursion (outline-end-of-heading)
8461 (setq folded (org-invisible-p)))
8462 (ignore-errors (org-forward-heading-same-level (1- n) t))
8463 (org-end-of-subtree t t)))
8464 ;; Include the end of an inlinetask
8465 (when (and (featurep 'org-inlinetask)
8466 (looking-at-p (concat (org-inlinetask-outline-regexp)
8467 "END[ \t]*$")))
8468 (end-of-line))
8469 (setq end (point))
8470 (goto-char beg0)
8471 (when (> end beg)
8472 (setq org-subtree-clip-folded folded)
8473 (when (or cut force-store-markers)
8474 (org-save-markers-in-region beg end))
8475 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8476 (setq org-subtree-clip (current-kill 0))
8477 (message "%s: Subtree(s) with %d characters"
8478 (if cut "Cut" "Copied")
8479 (length org-subtree-clip)))))
8481 (defun org-paste-subtree (&optional level tree for-yank remove)
8482 "Paste the clipboard as a subtree, with modification of headline level.
8483 The entire subtree is promoted or demoted in order to match a new headline
8484 level.
8486 If the cursor is at the beginning of a headline, the same level as
8487 that headline is used to paste the tree.
8489 If not, the new level is derived from the *visible* headings
8490 before and after the insertion point, and taken to be the inferior headline
8491 level of the two. So if the previous visible heading is level 3 and the
8492 next is level 4 (or vice versa), level 4 will be used for insertion.
8493 This makes sure that the subtree remains an independent subtree and does
8494 not swallow low level entries.
8496 You can also force a different level, either by using a numeric prefix
8497 argument, or by inserting the heading marker by hand. For example, if the
8498 cursor is after \"*****\", then the tree will be shifted to level 5.
8500 If optional TREE is given, use this text instead of the kill ring.
8502 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8503 move back over whitespace before inserting, and move point to the end of
8504 the inserted text when done.
8506 When REMOVE is non-nil, remove the subtree from the clipboard."
8507 (interactive "P")
8508 (setq tree (or tree (and kill-ring (current-kill 0))))
8509 (unless (org-kill-is-subtree-p tree)
8510 (user-error "%s"
8511 (substitute-command-keys
8512 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8513 (org-with-limited-levels
8514 (let* ((visp (not (org-invisible-p)))
8515 (txt tree)
8516 (^re_ "\\(\\*+\\)[ \t]*")
8517 (old-level (if (string-match org-outline-regexp-bol txt)
8518 (- (match-end 0) (match-beginning 0) 1)
8519 -1))
8520 (force-level (cond (level (prefix-numeric-value level))
8521 ((and (looking-at "[ \t]*$")
8522 (string-match
8523 "^\\*+$" (buffer-substring
8524 (point-at-bol) (point))))
8525 (- (match-end 0) (match-beginning 0)))
8526 ((and (bolp)
8527 (looking-at org-outline-regexp))
8528 (- (match-end 0) (point) 1))))
8529 (previous-level (save-excursion
8530 (condition-case nil
8531 (progn
8532 (outline-previous-visible-heading 1)
8533 (if (looking-at ^re_)
8534 (- (match-end 0) (match-beginning 0) 1)
8536 (error 1))))
8537 (next-level (save-excursion
8538 (condition-case nil
8539 (progn
8540 (or (looking-at org-outline-regexp)
8541 (outline-next-visible-heading 1))
8542 (if (looking-at ^re_)
8543 (- (match-end 0) (match-beginning 0) 1)
8545 (error 1))))
8546 (new-level (or force-level (max previous-level next-level)))
8547 (shift (if (or (= old-level -1)
8548 (= new-level -1)
8549 (= old-level new-level))
8551 (- new-level old-level)))
8552 (delta (if (> shift 0) -1 1))
8553 (func (if (> shift 0) 'org-demote 'org-promote))
8554 (org-odd-levels-only nil)
8555 beg end newend)
8556 ;; Remove the forced level indicator
8557 (when force-level
8558 (delete-region (point-at-bol) (point)))
8559 ;; Paste
8560 (beginning-of-line (if (bolp) 1 2))
8561 (setq beg (point))
8562 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8563 (insert-before-markers txt)
8564 (unless (string-suffix-p "\n" txt) (insert "\n"))
8565 (setq newend (point))
8566 (org-reinstall-markers-in-region beg)
8567 (setq end (point))
8568 (goto-char beg)
8569 (skip-chars-forward " \t\n\r")
8570 (setq beg (point))
8571 (when (and (org-invisible-p) visp)
8572 (save-excursion (outline-show-heading)))
8573 ;; Shift if necessary
8574 (unless (= shift 0)
8575 (save-restriction
8576 (narrow-to-region beg end)
8577 (while (not (= shift 0))
8578 (org-map-region func (point-min) (point-max))
8579 (setq shift (+ delta shift)))
8580 (goto-char (point-min))
8581 (setq newend (point-max))))
8582 (when (or (called-interactively-p 'interactive) for-yank)
8583 (message "Clipboard pasted as level %d subtree" new-level))
8584 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8585 kill-ring
8586 (eq org-subtree-clip (current-kill 0))
8587 org-subtree-clip-folded)
8588 ;; The tree was folded before it was killed/copied
8589 (outline-hide-subtree))
8590 (and for-yank (goto-char newend))
8591 (and remove (setq kill-ring (cdr kill-ring))))))
8593 (defun org-kill-is-subtree-p (&optional txt)
8594 "Check if the current kill is an outline subtree, or a set of trees.
8595 Returns nil if kill does not start with a headline, or if the first
8596 headline level is not the largest headline level in the tree.
8597 So this will actually accept several entries of equal levels as well,
8598 which is OK for `org-paste-subtree'.
8599 If optional TXT is given, check this string instead of the current kill."
8600 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8601 (re (org-get-limited-outline-regexp))
8602 (^re (concat "^" re))
8603 (start-level (and kill
8604 (string-match
8605 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8606 kill)
8607 (- (match-end 2) (match-beginning 2) 1)))
8608 (start (1+ (or (match-beginning 2) -1))))
8609 (if (not start-level)
8610 (progn
8611 nil) ;; does not even start with a heading
8612 (catch 'exit
8613 (while (setq start (string-match ^re kill (1+ start)))
8614 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8615 (throw 'exit nil)))
8616 t))))
8618 (defvar org-markers-to-move nil
8619 "Markers that should be moved with a cut-and-paste operation.
8620 Those markers are stored together with their positions relative to
8621 the start of the region.")
8623 (defun org-save-markers-in-region (beg end)
8624 "Check markers in region.
8625 If these markers are between BEG and END, record their position relative
8626 to BEG, so that after moving the block of text, we can put the markers back
8627 into place.
8628 This function gets called just before an entry or tree gets cut from the
8629 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8630 called immediately, to move the markers with the entries."
8631 (setq org-markers-to-move nil)
8632 (when (featurep 'org-clock)
8633 (org-clock-save-markers-for-cut-and-paste beg end))
8634 (when (featurep 'org-agenda)
8635 (org-agenda-save-markers-for-cut-and-paste beg end)))
8637 (defun org-check-and-save-marker (marker beg end)
8638 "Check if MARKER is between BEG and END.
8639 If yes, remember the marker and the distance to BEG."
8640 (when (and (marker-buffer marker)
8641 (equal (marker-buffer marker) (current-buffer))
8642 (>= marker beg) (< marker end))
8643 (push (cons marker (- marker beg)) org-markers-to-move)))
8645 (defun org-reinstall-markers-in-region (beg)
8646 "Move all remembered markers to their position relative to BEG."
8647 (dolist (x org-markers-to-move)
8648 (move-marker (car x) (+ beg (cdr x))))
8649 (setq org-markers-to-move nil))
8651 (defun org-narrow-to-subtree ()
8652 "Narrow buffer to the current subtree."
8653 (interactive)
8654 (save-excursion
8655 (save-match-data
8656 (org-with-limited-levels
8657 (narrow-to-region
8658 (progn (org-back-to-heading t) (point))
8659 (progn (org-end-of-subtree t t)
8660 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8661 (point)))))))
8663 (defun org-narrow-to-block ()
8664 "Narrow buffer to the current block."
8665 (interactive)
8666 (let* ((case-fold-search t)
8667 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8668 "^[ \t]*#\\+end_.*")))
8669 (if blockp
8670 (narrow-to-region (car blockp) (cdr blockp))
8671 (user-error "Not in a block"))))
8673 (defun org-clone-subtree-with-time-shift (n &optional shift)
8674 "Clone the task (subtree) at point N times.
8675 The clones will be inserted as siblings.
8677 In interactive use, the user will be prompted for the number of
8678 clones to be produced. If the entry has a timestamp, the user
8679 will also be prompted for a time shift, which may be a repeater
8680 as used in time stamps, for example `+3d'. To disable this,
8681 you can call the function with a universal prefix argument.
8683 When a valid repeater is given and the entry contains any time
8684 stamps, the clones will become a sequence in time, with time
8685 stamps in the subtree shifted for each clone produced. If SHIFT
8686 is nil or the empty string, time stamps will be left alone. The
8687 ID property of the original subtree is removed.
8689 In each clone, all the CLOCK entries will be removed. This
8690 prevents Org from considering that the clocked times overlap.
8692 If the original subtree did contain time stamps with a repeater,
8693 the following will happen:
8694 - the repeater will be removed in each clone
8695 - an additional clone will be produced, with the current, unshifted
8696 date(s) in the entry.
8697 - the original entry will be placed *after* all the clones, with
8698 repeater intact.
8699 - the start days in the repeater in the original entry will be shifted
8700 to past the last clone.
8701 In this way you can spell out a number of instances of a repeating task,
8702 and still retain the repeater to cover future instances of the task.
8704 As described above, N+1 clones are produced when the original
8705 subtree has a repeater. Setting N to 0, then, can be used to
8706 remove the repeater from a subtree and create a shifted clone
8707 with the original repeater."
8708 (interactive "nNumber of clones to produce: ")
8709 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8710 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8711 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8712 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8713 (shift
8714 (or shift
8715 (if (and (not (equal current-prefix-arg '(4)))
8716 (save-excursion
8717 (goto-char beg)
8718 (re-search-forward org-ts-regexp-both end-of-tree t)))
8719 (read-from-minibuffer
8720 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8721 ""))) ;No time shift
8722 (doshift
8723 (and (org-string-nw-p shift)
8724 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8725 shift)
8726 (user-error "Invalid shift specification %s" shift)))))
8727 (goto-char end-of-tree)
8728 (unless (bolp) (insert "\n"))
8729 (let* ((end (point))
8730 (template (buffer-substring beg end))
8731 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8732 (shift-what (pcase (and doshift (match-string 2 shift))
8733 (`nil nil)
8734 ("d" 'day)
8735 ("w" (setq shift-n (* 7 shift-n)) 'day)
8736 ("m" 'month)
8737 ("y" 'year)
8738 (_ (error "Unsupported time unit"))))
8739 (nmin 1)
8740 (nmax n)
8741 (n-no-remove -1)
8742 (idprop (org-entry-get nil "ID")))
8743 (when (and doshift
8744 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8745 template))
8746 (delete-region beg end)
8747 (setq end beg)
8748 (setq nmin 0)
8749 (setq nmax (1+ nmax))
8750 (setq n-no-remove nmax))
8751 (goto-char end)
8752 (cl-loop for n from nmin to nmax do
8753 (insert
8754 ;; Prepare clone.
8755 (with-temp-buffer
8756 (insert template)
8757 (org-mode)
8758 (goto-char (point-min))
8759 (org-show-subtree)
8760 (and idprop (if org-clone-delete-id
8761 (org-entry-delete nil "ID")
8762 (org-id-get-create t)))
8763 (unless (= n 0)
8764 (while (re-search-forward org-clock-line-re nil t)
8765 (delete-region (line-beginning-position)
8766 (line-beginning-position 2)))
8767 (goto-char (point-min))
8768 (while (re-search-forward org-drawer-regexp nil t)
8769 (org-remove-empty-drawer-at (point))))
8770 (goto-char (point-min))
8771 (when doshift
8772 (while (re-search-forward org-ts-regexp-both nil t)
8773 (org-timestamp-change (* n shift-n) shift-what))
8774 (unless (= n n-no-remove)
8775 (goto-char (point-min))
8776 (while (re-search-forward org-ts-regexp nil t)
8777 (save-excursion
8778 (goto-char (match-beginning 0))
8779 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8780 (delete-region (match-beginning 1) (match-end 1)))))))
8781 (buffer-string)))))
8782 (goto-char beg)))
8784 ;;; Outline Sorting
8786 (defun org-sort (&optional with-case)
8787 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8788 Optional argument WITH-CASE means sort case-sensitively."
8789 (interactive "P")
8790 (org-call-with-arg
8791 (cond ((org-at-table-p) #'org-table-sort-lines)
8792 ((org-at-item-p) #'org-sort-list)
8793 (t #'org-sort-entries))
8794 with-case))
8796 (defun org-sort-remove-invisible (s)
8797 "Remove invisible part of links and emphasis markers from string S."
8798 (remove-text-properties 0 (length s) org-rm-props s)
8799 (replace-regexp-in-string
8800 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8801 (replace-regexp-in-string
8802 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8803 (org-link-display-format s)
8804 t t) t t))
8806 (defvar org-priority-regexp) ; defined later in the file
8808 (defvar org-after-sorting-entries-or-items-hook nil
8809 "Hook that is run after a bunch of entries or items have been sorted.
8810 When children are sorted, the cursor is in the parent line when this
8811 hook gets called. When a region or a plain list is sorted, the cursor
8812 will be in the first entry of the sorted region/list.")
8814 (defun org-sort-entries
8815 (&optional with-case sorting-type getkey-func compare-func property
8816 interactive?)
8817 "Sort entries on a certain level of an outline tree.
8818 If there is an active region, the entries in the region are sorted.
8819 Else, if the cursor is before the first entry, sort the top-level items.
8820 Else, the children of the entry at point are sorted.
8822 Sorting can be alphabetically, numerically, by date/time as given by
8823 a time stamp, by a property, by priority order, or by a custom function.
8825 The command prompts for the sorting type unless it has been given to the
8826 function through the SORTING-TYPE argument, which needs to be a character,
8827 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8828 the precise meaning of each character:
8830 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8831 c By creation time, which is assumed to be the first inactive time stamp
8832 at the beginning of a line.
8833 d By deadline date/time.
8834 k By clocking time.
8835 n Numerically, by converting the beginning of the entry/item to a number.
8836 o By order of TODO keywords.
8837 p By priority according to the cookie.
8838 r By the value of a property.
8839 s By scheduled date/time.
8840 t By date/time, either the first active time stamp in the entry, or, if
8841 none exist, by the first inactive one.
8843 Capital letters will reverse the sort order.
8845 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8846 called with point at the beginning of the record. It must return a
8847 value that is compatible with COMPARE-FUNC, the function used to
8848 compare entries.
8850 Comparing entries ignores case by default. However, with an optional argument
8851 WITH-CASE, the sorting considers case as well.
8853 Sorting is done against the visible part of the headlines, it ignores hidden
8854 links.
8856 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8858 A non-nil value for INTERACTIVE? is used to signal that this
8859 function is being called interactively."
8860 (interactive (list current-prefix-arg nil nil nil nil t))
8861 (let ((case-func (if with-case 'identity 'downcase))
8862 start beg end stars re re2
8863 txt what tmp)
8864 ;; Find beginning and end of region to sort
8865 (cond
8866 ((org-region-active-p)
8867 ;; we will sort the region
8868 (setq end (region-end)
8869 what "region")
8870 (goto-char (region-beginning))
8871 (unless (org-at-heading-p) (outline-next-heading))
8872 (setq start (point)))
8873 ((or (org-at-heading-p)
8874 (ignore-errors (progn (org-back-to-heading) t)))
8875 ;; we will sort the children of the current headline
8876 (org-back-to-heading)
8877 (setq start (point)
8878 end (progn (org-end-of-subtree t t)
8879 (or (bolp) (insert "\n"))
8880 (when (>= (org-back-over-empty-lines) 1)
8881 (forward-line 1))
8882 (point))
8883 what "children")
8884 (goto-char start)
8885 (outline-show-subtree)
8886 (outline-next-heading))
8888 ;; we will sort the top-level entries in this file
8889 (goto-char (point-min))
8890 (or (org-at-heading-p) (outline-next-heading))
8891 (setq start (point))
8892 (goto-char (point-max))
8893 (beginning-of-line 1)
8894 (when (looking-at ".*?\\S-")
8895 ;; File ends in a non-white line
8896 (end-of-line 1)
8897 (insert "\n"))
8898 (setq end (point-max))
8899 (setq what "top-level")
8900 (goto-char start)
8901 (outline-show-all)))
8903 (setq beg (point))
8904 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8906 (looking-at "\\(\\*+\\)")
8907 (setq stars (match-string 1)
8908 re (concat "^" (regexp-quote stars) " +")
8909 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8910 txt (buffer-substring beg end))
8911 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8912 (when (and (not (equal stars "*")) (string-match re2 txt))
8913 (user-error "Region to sort contains a level above the first entry"))
8915 (unless sorting-type
8916 (message
8917 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8918 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8919 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8920 what)
8921 (setq sorting-type (read-char-exclusive)))
8923 (unless getkey-func
8924 (and (= (downcase sorting-type) ?f)
8925 (setq getkey-func
8926 (or (and interactive?
8927 (org-read-function
8928 "Function for extracting keys: "))
8929 (error "Missing key extractor")))))
8931 (and (= (downcase sorting-type) ?r)
8932 (not property)
8933 (setq property
8934 (completing-read "Property: "
8935 (mapcar #'list (org-buffer-property-keys t))
8936 nil t)))
8938 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8939 (message "Sorting entries...")
8941 (save-restriction
8942 (narrow-to-region start end)
8943 (let ((restore-clock?
8944 ;; The clock marker is lost when using `sort-subr'; mark
8945 ;; the clock with temporary `:org-clock-marker-backup'
8946 ;; text property.
8947 (when (and (eq (org-clock-is-active) (current-buffer))
8948 (<= start (marker-position org-clock-marker))
8949 (>= end (marker-position org-clock-marker)))
8950 (org-with-silent-modifications
8951 (put-text-property (1- org-clock-marker) org-clock-marker
8952 :org-clock-marker-backup t))
8954 (dcst (downcase sorting-type))
8955 (case-fold-search nil)
8956 (now (current-time)))
8957 (sort-subr
8958 (/= dcst sorting-type)
8959 ;; This function moves to the beginning character of the "record" to
8960 ;; be sorted.
8961 (lambda nil
8962 (if (re-search-forward re nil t)
8963 (goto-char (match-beginning 0))
8964 (goto-char (point-max))))
8965 ;; This function moves to the last character of the "record" being
8966 ;; sorted.
8967 (lambda nil
8968 (save-match-data
8969 (condition-case nil
8970 (outline-forward-same-level 1)
8971 (error
8972 (goto-char (point-max))))))
8973 ;; This function returns the value that gets sorted against.
8974 (lambda nil
8975 (cond
8976 ((= dcst ?n)
8977 (if (looking-at org-complex-heading-regexp)
8978 (string-to-number (org-sort-remove-invisible (match-string 4)))
8979 nil))
8980 ((= dcst ?a)
8981 (if (looking-at org-complex-heading-regexp)
8982 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8983 nil))
8984 ((= dcst ?k)
8985 (or (get-text-property (point) :org-clock-minutes) 0))
8986 ((= dcst ?t)
8987 (let ((end (save-excursion (outline-next-heading) (point))))
8988 (if (or (re-search-forward org-ts-regexp end t)
8989 (re-search-forward org-ts-regexp-both end t))
8990 (org-time-string-to-seconds (match-string 0))
8991 (float-time now))))
8992 ((= dcst ?c)
8993 (let ((end (save-excursion (outline-next-heading) (point))))
8994 (if (re-search-forward
8995 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8996 end t)
8997 (org-time-string-to-seconds (match-string 0))
8998 (float-time now))))
8999 ((= dcst ?s)
9000 (let ((end (save-excursion (outline-next-heading) (point))))
9001 (if (re-search-forward org-scheduled-time-regexp end t)
9002 (org-time-string-to-seconds (match-string 1))
9003 (float-time now))))
9004 ((= dcst ?d)
9005 (let ((end (save-excursion (outline-next-heading) (point))))
9006 (if (re-search-forward org-deadline-time-regexp end t)
9007 (org-time-string-to-seconds (match-string 1))
9008 (float-time now))))
9009 ((= dcst ?p)
9010 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9011 (string-to-char (match-string 2))
9012 org-default-priority))
9013 ((= dcst ?r)
9014 (or (org-entry-get nil property) ""))
9015 ((= dcst ?o)
9016 (when (looking-at org-complex-heading-regexp)
9017 (let* ((m (match-string 2))
9018 (s (if (member m org-done-keywords) '- '+)))
9019 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9020 ((= dcst ?f)
9021 (if getkey-func
9022 (progn
9023 (setq tmp (funcall getkey-func))
9024 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9025 tmp)
9026 (error "Invalid key function `%s'" getkey-func)))
9027 (t (error "Invalid sorting type `%c'" sorting-type))))
9029 (cond
9030 ((= dcst ?a) 'string<)
9031 ((= dcst ?f)
9032 (or compare-func
9033 (and interactive?
9034 (org-read-function
9035 (concat "Function for comparing keys "
9036 "(empty for default `sort-subr' predicate): ")
9037 'allow-empty))))
9038 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9039 (when restore-clock?
9040 (move-marker org-clock-marker
9041 (1+ (next-single-property-change
9042 start :org-clock-marker-backup)))
9043 (remove-text-properties (1- org-clock-marker) org-clock-marker
9044 '(:org-clock-marker-backup t)))))
9045 (run-hooks 'org-after-sorting-entries-or-items-hook)
9046 (message "Sorting entries...done")))
9048 ;;; The orgstruct minor mode
9050 ;; Define a minor mode which can be used in other modes in order to
9051 ;; integrate the Org mode structure editing commands.
9053 ;; This is really a hack, because the Org mode structure commands use
9054 ;; keys which normally belong to the major mode. Here is how it
9055 ;; works: The minor mode defines all the keys necessary to operate the
9056 ;; structure commands, but wraps the commands into a function which
9057 ;; tests if the cursor is currently at a headline or a plain list
9058 ;; item. If that is the case, the structure command is used,
9059 ;; temporarily setting many Org mode variables like regular
9060 ;; expressions for filling etc. However, when any of those keys is
9061 ;; used at a different location, function uses `key-binding' to look
9062 ;; up if the key has an associated command in another currently active
9063 ;; keymap (minor modes, major mode, global), and executes that
9064 ;; command. There might be problems if any of the keys is otherwise
9065 ;; used as a prefix key.
9067 (defcustom orgstruct-heading-prefix-regexp ""
9068 "Regexp that matches the custom prefix of Org headlines in
9069 orgstruct(++)-mode."
9070 :group 'org
9071 :version "26.1"
9072 :package-version '(Org . "8.3")
9073 :type 'regexp)
9074 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9076 (defcustom orgstruct-setup-hook nil
9077 "Hook run after orgstruct-mode-map is filled."
9078 :group 'org
9079 :version "24.4"
9080 :package-version '(Org . "8.0")
9081 :type 'hook)
9083 (defvar orgstruct-initialized nil)
9085 (defvar org-local-vars nil
9086 "List of local variables, for use by `orgstruct-mode'.")
9088 ;;;###autoload
9089 (define-minor-mode orgstruct-mode
9090 "Toggle the minor mode `orgstruct-mode'.
9091 This mode is for using Org mode structure commands in other
9092 modes. The following keys behave as if Org mode were active, if
9093 the cursor is on a headline, or on a plain list item (both as
9094 defined by Org mode)."
9095 nil " OrgStruct" (make-sparse-keymap)
9096 (funcall (if orgstruct-mode
9097 'add-to-invisibility-spec
9098 'remove-from-invisibility-spec)
9099 '(outline . t))
9100 (when orgstruct-mode
9101 (org-load-modules-maybe)
9102 (unless orgstruct-initialized
9103 (orgstruct-setup)
9104 (setq orgstruct-initialized t))))
9106 ;;;###autoload
9107 (defun turn-on-orgstruct ()
9108 "Unconditionally turn on `orgstruct-mode'."
9109 (orgstruct-mode 1))
9111 (defvar-local orgstruct-is-++ nil
9112 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9113 (defvar-local org-fb-vars nil)
9114 (defun orgstruct++-mode (&optional arg)
9115 "Toggle `orgstruct-mode', the enhanced version of it.
9116 In addition to setting orgstruct-mode, this also exports all
9117 indentation and autofilling variables from Org mode into the
9118 buffer. It will also recognize item context in multiline items."
9119 (interactive "P")
9120 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9121 (if (< arg 1)
9122 (progn (orgstruct-mode -1)
9123 (dolist (v org-fb-vars)
9124 (set (make-local-variable (car v))
9125 (if (eq (car-safe (cadr v)) 'quote)
9126 (cl-cadadr v)
9127 (nth 1 v)))))
9128 (orgstruct-mode 1)
9129 (setq org-fb-vars nil)
9130 (unless org-local-vars
9131 (setq org-local-vars (org-get-local-variables)))
9132 (let (var val)
9133 (dolist (x org-local-vars)
9134 (when (string-match
9135 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9136 \\|fill-prefix\\|indent-\\)"
9137 (symbol-name (car x)))
9138 (setq var (car x) val (nth 1 x))
9139 (push (list var `(quote ,(eval var))) org-fb-vars)
9140 (set (make-local-variable var)
9141 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9142 (setq-local orgstruct-is-++ t))))
9144 ;;;###autoload
9145 (defun turn-on-orgstruct++ ()
9146 "Unconditionally turn on `orgstruct++-mode'."
9147 (orgstruct++-mode 1))
9149 (defun orgstruct-error ()
9150 "Error when there is no default binding for a structure key."
9151 (interactive)
9152 (funcall (if (fboundp 'user-error)
9153 'user-error
9154 'error)
9155 "This key has no function outside structure elements"))
9157 (defun orgstruct-setup ()
9158 "Setup orgstruct keymap."
9159 (dolist (cell '((org-demote . t)
9160 (org-metaleft . t)
9161 (org-metaright . t)
9162 (org-promote . t)
9163 (org-shiftmetaleft . t)
9164 (org-shiftmetaright . t)
9165 org-backward-element
9166 org-backward-heading-same-level
9167 org-ctrl-c-ret
9168 org-ctrl-c-minus
9169 org-ctrl-c-star
9170 org-cycle
9171 org-force-cycle-archived
9172 org-forward-heading-same-level
9173 org-insert-heading
9174 org-insert-heading-respect-content
9175 org-kill-note-or-show-branches
9176 org-mark-subtree
9177 org-meta-return
9178 org-metadown
9179 org-metaup
9180 org-narrow-to-subtree
9181 org-promote-subtree
9182 org-reveal
9183 org-shiftdown
9184 org-shiftleft
9185 org-shiftmetadown
9186 org-shiftmetaup
9187 org-shiftright
9188 org-shifttab
9189 org-shifttab
9190 org-shiftup
9191 org-show-children
9192 org-show-subtree
9193 org-sort
9194 org-up-element
9195 outline-demote
9196 outline-next-visible-heading
9197 outline-previous-visible-heading
9198 outline-promote
9199 outline-up-heading))
9200 (let ((f (or (car-safe cell) cell))
9201 (disable-when-heading-prefix (cdr-safe cell)))
9202 (when (fboundp f)
9203 (let ((new-bindings))
9204 (dolist (binding (nconc (where-is-internal f org-mode-map)
9205 (where-is-internal f outline-mode-map)))
9206 (push binding new-bindings)
9207 ;; TODO use local-function-key-map
9208 (dolist (rep '(("<tab>" . "TAB")
9209 ("<return>" . "RET")
9210 ("<escape>" . "ESC")
9211 ("<delete>" . "DEL")))
9212 (setq binding (read-kbd-macro
9213 (let ((case-fold-search))
9214 (replace-regexp-in-string
9215 (regexp-quote (cdr rep))
9216 (car rep)
9217 (key-description binding)))))
9218 (cl-pushnew binding new-bindings :test 'equal)))
9219 (dolist (binding new-bindings)
9220 (let ((key (lookup-key orgstruct-mode-map binding)))
9221 (when (or (not key) (numberp key))
9222 (ignore-errors
9223 (org-defkey orgstruct-mode-map
9224 binding
9225 (orgstruct-make-binding
9226 f binding disable-when-heading-prefix))))))))))
9227 (run-hooks 'orgstruct-setup-hook))
9229 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9230 "Create a function for binding in the structure minor mode.
9231 FUN is the command to call inside a table. KEY is the key that
9232 should be checked in for a command to execute outside of tables.
9233 Non-nil `disable-when-heading-prefix' means to disable the command
9234 if `orgstruct-heading-prefix-regexp' is not empty."
9235 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9236 (let ((nname name)
9237 (i 0))
9238 (while (fboundp (intern nname))
9239 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9240 (setq name (intern nname)))
9241 (eval
9242 (let ((bindings '((org-heading-regexp
9243 (concat "^"
9244 orgstruct-heading-prefix-regexp
9245 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9246 (org-outline-regexp
9247 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9248 (org-outline-regexp-bol
9249 (concat "^" org-outline-regexp))
9250 (outline-regexp org-outline-regexp)
9251 (outline-heading-end-regexp "\n")
9252 (outline-level 'org-outline-level)
9253 (outline-heading-alist))))
9254 `(defun ,name (arg)
9255 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9256 "Outside of structure, run the binding of `"
9257 (key-description key) "'."
9258 (when disable-when-heading-prefix
9259 (concat
9260 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9261 "back to the default binding due to limitations of Org's implementation of\n"
9262 "`" (symbol-name fun) "'.")))
9263 (interactive "p")
9264 (let* ((disable
9265 ,(and disable-when-heading-prefix
9266 '(not (string= orgstruct-heading-prefix-regexp ""))))
9267 (fallback
9268 (or disable
9269 (not
9270 (let* ,bindings
9271 (org-context-p 'headline 'item
9272 ,(when (memq fun
9273 '(org-insert-heading
9274 org-insert-heading-respect-content
9275 org-meta-return))
9276 '(when orgstruct-is-++
9277 'item-body))))))))
9278 (if fallback
9279 (let* ((orgstruct-mode)
9280 (binding
9281 (let ((key ,key))
9282 (catch 'exit
9283 (dolist
9284 (rep
9285 '(nil
9286 ("<\\([^>]*\\)tab>" . "\\1TAB")
9287 ("<\\([^>]*\\)return>" . "\\1RET")
9288 ("<\\([^>]*\\)escape>" . "\\1ESC")
9289 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9290 nil)
9291 (when rep
9292 (setq key (read-kbd-macro
9293 (let ((case-fold-search))
9294 (replace-regexp-in-string
9295 (car rep)
9296 (cdr rep)
9297 (key-description key))))))
9298 (when (key-binding key)
9299 (throw 'exit (key-binding key))))))))
9300 (if (keymapp binding)
9301 (org-set-transient-map binding)
9302 (let ((func (or binding
9303 (unless disable
9304 'orgstruct-error))))
9305 (when func
9306 (call-interactively func)))))
9307 (org-run-like-in-org-mode
9308 (lambda ()
9309 (interactive)
9310 (let* ,bindings
9311 (call-interactively ',fun)))))))))
9312 name))
9314 (defun org-contextualize-keys (alist contexts)
9315 "Return valid elements in ALIST depending on CONTEXTS.
9317 `org-agenda-custom-commands' or `org-capture-templates' are the
9318 values used for ALIST, and `org-agenda-custom-commands-contexts'
9319 or `org-capture-templates-contexts' are the associated contexts
9320 definitions."
9321 (let ((contexts
9322 ;; normalize contexts
9323 (mapcar
9324 (lambda(c) (cond ((listp (cadr c))
9325 (list (car c) (car c) (nth 1 c)))
9326 ((string= "" (cadr c))
9327 (list (car c) (car c) (nth 2 c)))
9328 (t c)))
9329 contexts))
9330 (a alist) r s)
9331 ;; loop over all commands or templates
9332 (dolist (c a)
9333 (let (vrules repl)
9334 (cond
9335 ((not (assoc (car c) contexts))
9336 (push c r))
9337 ((and (assoc (car c) contexts)
9338 (setq vrules (org-contextualize-validate-key
9339 (car c) contexts)))
9340 (mapc (lambda (vr)
9341 (unless (equal (car vr) (cadr vr))
9342 (setq repl vr)))
9343 vrules)
9344 (if (not repl) (push c r)
9345 (push (cadr repl) s)
9346 (push
9347 (cons (car c)
9348 (cdr (or (assoc (cadr repl) alist)
9349 (error "Undefined key `%s' as contextual replacement for `%s'"
9350 (cadr repl) (car c)))))
9351 r))))))
9352 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9353 (delq
9355 (delete-dups
9356 (mapcar (lambda (x)
9357 (let ((tpl (car x)))
9358 (unless (delq
9360 (mapcar (lambda (y)
9361 (equal y tpl))
9363 x)))
9364 (reverse r))))))
9366 (defun org-contextualize-validate-key (key contexts)
9367 "Check CONTEXTS for agenda or capture KEY."
9368 (let (res)
9369 (dolist (r contexts)
9370 (dolist (rr (car (last r)))
9371 (when
9372 (and (equal key (car r))
9373 (if (functionp rr) (funcall rr)
9374 (or (and (eq (car rr) 'in-file)
9375 (buffer-file-name)
9376 (string-match (cdr rr) (buffer-file-name)))
9377 (and (eq (car rr) 'in-mode)
9378 (string-match (cdr rr) (symbol-name major-mode)))
9379 (and (eq (car rr) 'in-buffer)
9380 (string-match (cdr rr) (buffer-name)))
9381 (when (and (eq (car rr) 'not-in-file)
9382 (buffer-file-name))
9383 (not (string-match (cdr rr) (buffer-file-name))))
9384 (when (eq (car rr) 'not-in-mode)
9385 (not (string-match (cdr rr) (symbol-name major-mode))))
9386 (when (eq (car rr) 'not-in-buffer)
9387 (not (string-match (cdr rr) (buffer-name)))))))
9388 (push r res))))
9389 (delete-dups (delq nil res))))
9391 (defun org-context-p (&rest contexts)
9392 "Check if local context is any of CONTEXTS.
9393 Possible values in the list of contexts are `table', `headline', and `item'."
9394 (let ((pos (point)))
9395 (goto-char (point-at-bol))
9396 (prog1 (or (and (memq 'table contexts)
9397 (looking-at "[ \t]*|"))
9398 (and (memq 'headline contexts)
9399 (looking-at org-outline-regexp))
9400 (and (memq 'item contexts)
9401 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9402 (and (memq 'item-body contexts)
9403 (org-in-item-p)))
9404 (goto-char pos))))
9406 ;;;###autoload
9407 (defun org-run-like-in-org-mode (cmd)
9408 "Run a command, pretending that the current buffer is in Org mode.
9409 This will temporarily bind local variables that are typically bound in
9410 Org mode to the values they have in Org mode, and then interactively
9411 call CMD."
9412 (org-load-modules-maybe)
9413 (unless org-local-vars
9414 (setq org-local-vars (org-get-local-variables)))
9415 (let (binds)
9416 (dolist (var org-local-vars)
9417 (when (or (not (boundp (car var)))
9418 (eq (symbol-value (car var))
9419 (default-value (car var))))
9420 (push (list (car var) `(quote ,(cadr var))) binds)))
9421 (eval `(let ,binds
9422 (call-interactively (quote ,cmd))))))
9424 (defun org-get-category (&optional pos force-refresh)
9425 "Get the category applying to position POS."
9426 (save-match-data
9427 (when force-refresh (org-refresh-category-properties))
9428 (let ((pos (or pos (point))))
9429 (or (get-text-property pos 'org-category)
9430 (progn (org-refresh-category-properties)
9431 (get-text-property pos 'org-category))))))
9433 ;;; Refresh properties
9435 (defun org-refresh-properties (dprop tprop)
9436 "Refresh buffer text properties.
9437 DPROP is the drawer property and TPROP is either the
9438 corresponding text property to set, or an alist with each element
9439 being a text property (as a symbol) and a function to apply to
9440 the value of the drawer property."
9441 (let* ((case-fold-search t)
9442 (inhibit-read-only t)
9443 (inherit? (org-property-inherit-p dprop))
9444 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9445 (global (and inherit? (org--property-global-value dprop nil))))
9446 (org-with-silent-modifications
9447 (org-with-point-at 1
9448 ;; Set global values (e.g., values defined through
9449 ;; "#+PROPERTY:" keywords) to the whole buffer.
9450 (when global (put-text-property (point-min) (point-max) tprop global))
9451 ;; Set local values.
9452 (while (re-search-forward property-re nil t)
9453 (when (org-at-property-p)
9454 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9455 (outline-next-heading))))))
9457 (defun org-refresh-property (tprop p &optional inherit)
9458 "Refresh the buffer text property TPROP from the drawer property P.
9459 The refresh happens only for the current headline, or the whole
9460 sub-tree if optional argument INHERIT is non-nil."
9461 (unless (org-before-first-heading-p)
9462 (save-excursion
9463 (org-back-to-heading t)
9464 (let ((start (point))
9465 (end (save-excursion
9466 (if inherit (org-end-of-subtree t t)
9467 (or (outline-next-heading) (point-max))))))
9468 (if (symbolp tprop)
9469 ;; TPROP is a text property symbol.
9470 (put-text-property start end tprop p)
9471 ;; TPROP is an alist with (property . function) elements.
9472 (pcase-dolist (`(,prop . ,f) tprop)
9473 (put-text-property start end prop (funcall f p))))))))
9475 (defun org-refresh-category-properties ()
9476 "Refresh category text properties in the buffer."
9477 (let ((case-fold-search t)
9478 (inhibit-read-only t)
9479 (default-category
9480 (cond ((null org-category)
9481 (if buffer-file-name
9482 (file-name-sans-extension
9483 (file-name-nondirectory buffer-file-name))
9484 "???"))
9485 ((symbolp org-category) (symbol-name org-category))
9486 (t org-category))))
9487 (org-with-silent-modifications
9488 (org-with-wide-buffer
9489 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9490 ;; This is the default category for the buffer. If none is
9491 ;; found, fall-back to `org-category' or buffer file name.
9492 (put-text-property
9493 (point-min) (point-max)
9494 'org-category
9495 (catch 'buffer-category
9496 (goto-char (point-max))
9497 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9498 (let ((element (org-element-at-point)))
9499 (when (eq (org-element-type element) 'keyword)
9500 (throw 'buffer-category
9501 (org-element-property :value element)))))
9502 default-category))
9503 ;; Set sub-tree specific categories.
9504 (goto-char (point-min))
9505 (let ((regexp (org-re-property "CATEGORY")))
9506 (while (re-search-forward regexp nil t)
9507 (let ((value (match-string-no-properties 3)))
9508 (when (org-at-property-p)
9509 (put-text-property
9510 (save-excursion (org-back-to-heading t) (point))
9511 (save-excursion (org-end-of-subtree t t) (point))
9512 'org-category
9513 value)))))))))
9515 (defun org-refresh-stats-properties ()
9516 "Refresh stats text properties in the buffer."
9517 (org-with-silent-modifications
9518 (org-with-point-at 1
9519 (let ((regexp (concat org-outline-regexp-bol
9520 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9521 (while (re-search-forward regexp nil t)
9522 (let* ((numerator (string-to-number (match-string 1)))
9523 (denominator (and (match-end 2)
9524 (string-to-number (match-string 2))))
9525 (stats (cond ((not denominator) numerator) ;percent
9526 ((= denominator 0) 0)
9527 (t (/ (* numerator 100) denominator)))))
9528 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9529 'org-stats stats)))))))
9531 (defun org-refresh-effort-properties ()
9532 "Refresh effort properties"
9533 (org-refresh-properties
9534 org-effort-property
9535 '((effort . identity)
9536 (effort-minutes . org-duration-to-minutes))))
9538 ;;;; Link Stuff
9540 ;;; Link abbreviations
9542 (defun org-link-expand-abbrev (link)
9543 "Apply replacements as defined in `org-link-abbrev-alist'."
9544 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9545 (let* ((key (match-string 1 link))
9546 (as (or (assoc key org-link-abbrev-alist-local)
9547 (assoc key org-link-abbrev-alist)))
9548 (tag (and (match-end 2) (match-string 3 link)))
9549 rpl)
9550 (if (not as)
9551 link
9552 (setq rpl (cdr as))
9553 (cond
9554 ((symbolp rpl) (funcall rpl tag))
9555 ((string-match "%(\\([^)]+\\))" rpl)
9556 (replace-match
9557 (save-match-data
9558 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9559 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9560 ((string-match "%h" rpl)
9561 (replace-match (url-hexify-string (or tag "")) t t rpl))
9562 (t (concat rpl tag)))))
9563 link))
9565 ;;; Storing and inserting links
9567 (defvar org-insert-link-history nil
9568 "Minibuffer history for links inserted with `org-insert-link'.")
9570 (defvar org-stored-links nil
9571 "Contains the links stored with `org-store-link'.")
9573 (defvar org-store-link-plist nil
9574 "Plist with info about the most recently link created with `org-store-link'.")
9576 (defun org-store-link-functions ()
9577 "Return a list of functions that are called to create and store a link.
9578 The functions defined in the :store property of
9579 `org-link-parameters'.
9581 Each function will be called in turn until one returns a non-nil
9582 value. Each function should check if it is responsible for
9583 creating this link (for example by looking at the major mode).
9584 If not, it must exit and return nil. If yes, it should return
9585 a non-nil value after calling `org-store-link-props' with a list
9586 of properties and values. Special properties are:
9588 :type The link prefix, like \"http\". This must be given.
9589 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9590 This is obligatory as well.
9591 :description Optional default description for the second pair
9592 of brackets in an Org mode link. The user can still change
9593 this when inserting this link into an Org mode buffer.
9595 In addition to these, any additional properties can be specified
9596 and then used in capture templates."
9597 (cl-loop for link in org-link-parameters
9598 with store-func
9599 do (setq store-func (org-link-get-parameter (car link) :store))
9600 if store-func
9601 collect store-func))
9603 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9604 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9606 ;;;###autoload
9607 (defun org-store-link (arg)
9608 "Store an org-link to the current location.
9609 \\<org-mode-map>
9610 This link is added to `org-stored-links' and can later be inserted
9611 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9613 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9614 A single
9615 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9616 `org-gnus-prefer-web-links' for links to Usenet articles.
9618 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9619 skipping storing functions that are not
9620 part of Org core.
9622 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9623 prefix ARG forces storing a link for each line in the
9624 active region."
9625 (interactive "P")
9626 (org-load-modules-maybe)
9627 (if (and (equal arg '(64)) (org-region-active-p))
9628 (save-excursion
9629 (let ((end (region-end)))
9630 (goto-char (region-beginning))
9631 (set-mark (point))
9632 (while (< (point-at-eol) end)
9633 (move-end-of-line 1) (activate-mark)
9634 (let (current-prefix-arg)
9635 (call-interactively 'org-store-link))
9636 (move-beginning-of-line 2)
9637 (set-mark (point)))))
9638 (setq org-store-link-plist nil)
9639 (let (link cpltxt desc description search
9640 txt custom-id agenda-link sfuns sfunsn)
9641 (cond
9643 ;; Store a link using an external link type
9644 ((and (not (equal arg '(16)))
9645 (setq sfuns
9646 (delq
9647 nil (mapcar (lambda (f)
9648 (let (fs) (if (funcall f) (push f fs))))
9649 (org-store-link-functions)))
9650 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9651 (or (and (cdr sfuns)
9652 (funcall (intern
9653 (completing-read
9654 "Which function for creating the link? "
9655 sfunsn nil t (car sfunsn)))))
9656 (funcall (caar sfuns)))
9657 (setq link (plist-get org-store-link-plist :link)
9658 desc (or (plist-get org-store-link-plist
9659 :description)
9660 link))))
9662 ;; Store a link from a source code buffer.
9663 ((org-src-edit-buffer-p)
9664 (let ((coderef-format (org-src-coderef-format)))
9665 (cond ((save-excursion
9666 (beginning-of-line)
9667 (looking-at (org-src-coderef-regexp coderef-format)))
9668 (setq link (format "(%s)" (match-string-no-properties 3))))
9669 ((called-interactively-p 'any)
9670 (let ((label (read-string "Code line label: ")))
9671 (end-of-line)
9672 (setq link (format coderef-format label))
9673 (let ((gc (- 79 (length link))))
9674 (if (< (current-column) gc)
9675 (org-move-to-column gc t)
9676 (insert " ")))
9677 (insert link)
9678 (setq link (concat "(" label ")"))
9679 (setq desc nil)))
9680 (t (setq link nil)))))
9682 ;; We are in the agenda, link to referenced location
9683 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9684 (let ((m (or (get-text-property (point) 'org-hd-marker)
9685 (get-text-property (point) 'org-marker))))
9686 (when m
9687 (org-with-point-at m
9688 (setq agenda-link
9689 (if (called-interactively-p 'any)
9690 (call-interactively 'org-store-link)
9691 (org-store-link nil)))))))
9693 ((eq major-mode 'calendar-mode)
9694 (let ((cd (calendar-cursor-to-date)))
9695 (setq link
9696 (format-time-string
9697 (car org-time-stamp-formats)
9698 (apply 'encode-time
9699 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9700 nil nil nil))))
9701 (org-store-link-props :type "calendar" :date cd)))
9703 ((eq major-mode 'help-mode)
9704 (setq link (concat "help:" (save-excursion
9705 (goto-char (point-min))
9706 (looking-at "^[^ ]+")
9707 (match-string 0))))
9708 (org-store-link-props :type "help"))
9710 ((eq major-mode 'w3-mode)
9711 (setq cpltxt (if (and (buffer-name)
9712 (not (string-match "Untitled" (buffer-name))))
9713 (buffer-name)
9714 (url-view-url t))
9715 link (url-view-url t))
9716 (org-store-link-props :type "w3" :url (url-view-url t)))
9718 ((eq major-mode 'image-mode)
9719 (setq cpltxt (concat "file:"
9720 (abbreviate-file-name buffer-file-name))
9721 link cpltxt)
9722 (org-store-link-props :type "image" :file buffer-file-name))
9724 ;; In dired, store a link to the file of the current line
9725 ((derived-mode-p 'dired-mode)
9726 (let ((file (dired-get-filename nil t)))
9727 (setq file (if file
9728 (abbreviate-file-name
9729 (expand-file-name (dired-get-filename nil t)))
9730 ;; otherwise, no file so use current directory.
9731 default-directory))
9732 (setq cpltxt (concat "file:" file)
9733 link cpltxt)))
9735 ((setq search (run-hook-with-args-until-success
9736 'org-create-file-search-functions))
9737 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9738 "::" search))
9739 (setq cpltxt (or description link)))
9741 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9742 (org-with-limited-levels
9743 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9744 (cond
9745 ;; Store a link using the target at point
9746 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9747 (setq cpltxt
9748 (concat "file:"
9749 (abbreviate-file-name
9750 (buffer-file-name (buffer-base-buffer)))
9751 "::" (match-string 1))
9752 link cpltxt))
9753 ((and (featurep 'org-id)
9754 (or (eq org-id-link-to-org-use-id t)
9755 (and (called-interactively-p 'any)
9756 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9757 (and (eq org-id-link-to-org-use-id
9758 'create-if-interactive-and-no-custom-id)
9759 (not custom-id))))
9760 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9761 ;; Store a link using the ID at point
9762 (setq link (condition-case nil
9763 (prog1 (org-id-store-link)
9764 (setq desc (or (plist-get org-store-link-plist
9765 :description)
9766 "")))
9767 (error
9768 ;; Probably before first headline, link only to file
9769 (concat "file:"
9770 (abbreviate-file-name
9771 (buffer-file-name (buffer-base-buffer))))))))
9773 ;; Just link to current headline
9774 (setq cpltxt (concat "file:"
9775 (abbreviate-file-name
9776 (buffer-file-name (buffer-base-buffer)))))
9777 ;; Add a context search string
9778 (when (org-xor org-context-in-file-links
9779 (equal arg '(4)))
9780 (let* ((element (org-element-at-point))
9781 (name (org-element-property :name element)))
9782 (setq txt (cond
9783 ((org-at-heading-p) nil)
9784 (name)
9785 ((org-region-active-p)
9786 (buffer-substring (region-beginning) (region-end)))))
9787 (when (or (null txt) (string-match "\\S-" txt))
9788 (setq cpltxt
9789 (concat cpltxt "::"
9790 (condition-case nil
9791 (org-make-org-heading-search-string txt)
9792 (error "")))
9793 desc (or name
9794 (nth 4 (ignore-errors (org-heading-components)))
9795 "NONE")))))
9796 (when (string-match "::\\'" cpltxt)
9797 (setq cpltxt (substring cpltxt 0 -2)))
9798 (setq link cpltxt)))))
9800 ((buffer-file-name (buffer-base-buffer))
9801 ;; Just link to this file here.
9802 (setq cpltxt (concat "file:"
9803 (abbreviate-file-name
9804 (buffer-file-name (buffer-base-buffer)))))
9805 ;; Add a context string.
9806 (when (org-xor org-context-in-file-links
9807 (equal arg '(4)))
9808 (setq txt (if (org-region-active-p)
9809 (buffer-substring (region-beginning) (region-end))
9810 (buffer-substring (point-at-bol) (point-at-eol))))
9811 ;; Only use search option if there is some text.
9812 (when (string-match "\\S-" txt)
9813 (setq cpltxt
9814 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9815 desc "NONE")))
9816 (setq link cpltxt))
9818 ((called-interactively-p 'interactive)
9819 (user-error "No method for storing a link from this buffer"))
9821 (t (setq link nil)))
9823 ;; We're done setting link and desc, clean up
9824 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9825 (setq link (or link cpltxt)
9826 desc (or desc cpltxt))
9827 (cond ((not desc))
9828 ((equal desc "NONE") (setq desc nil))
9829 (t (setq desc
9830 (replace-regexp-in-string
9831 org-bracket-link-analytic-regexp
9832 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9833 desc))))
9834 ;; Return the link
9835 (if (not (and (or (called-interactively-p 'any)
9836 executing-kbd-macro)
9837 link))
9838 (or agenda-link (and link (org-make-link-string link desc)))
9839 (push (list link desc) org-stored-links)
9840 (message "Stored: %s" (or desc link))
9841 (when custom-id
9842 (setq link (concat "file:" (abbreviate-file-name
9843 (buffer-file-name)) "::#" custom-id))
9844 (push (list link desc) org-stored-links))
9845 (car org-stored-links)))))
9847 (defun org-store-link-props (&rest plist)
9848 "Store link properties, extract names, addresses and dates."
9849 (let ((x (plist-get plist :from)))
9850 (when x
9851 (let ((adr (mail-extract-address-components x)))
9852 (setq plist (plist-put plist :fromname (car adr)))
9853 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9854 (let ((x (plist-get plist :to)))
9855 (when x
9856 (let ((adr (mail-extract-address-components x)))
9857 (setq plist (plist-put plist :toname (car adr)))
9858 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9859 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9860 (when x
9861 (setq plist (plist-put plist :date-timestamp
9862 (format-time-string
9863 (org-time-stamp-format t) x)))
9864 (setq plist (plist-put plist :date-timestamp-inactive
9865 (format-time-string
9866 (org-time-stamp-format t t) x)))))
9867 (let ((from (plist-get plist :from))
9868 (to (plist-get plist :to)))
9869 (when (and from to org-from-is-user-regexp)
9870 (setq plist
9871 (plist-put plist :fromto
9872 (if (string-match org-from-is-user-regexp from)
9873 (concat "to %t")
9874 (concat "from %f"))))))
9875 (setq org-store-link-plist plist))
9877 (defun org-add-link-props (&rest plist)
9878 "Add these properties to the link property list."
9879 (let (key value)
9880 (while plist
9881 (setq key (pop plist) value (pop plist))
9882 (setq org-store-link-plist
9883 (plist-put org-store-link-plist key value)))))
9885 (defun org-email-link-description (&optional fmt)
9886 "Return the description part of an email link.
9887 This takes information from `org-store-link-plist' and formats it
9888 according to FMT (default from `org-email-link-description-format')."
9889 (setq fmt (or fmt org-email-link-description-format))
9890 (let* ((p org-store-link-plist)
9891 (to (plist-get p :toaddress))
9892 (from (plist-get p :fromaddress))
9893 (table
9894 (list
9895 (cons "%c" (plist-get p :fromto))
9896 (cons "%F" (plist-get p :from))
9897 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9898 (cons "%T" (plist-get p :to))
9899 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9900 (cons "%s" (plist-get p :subject))
9901 (cons "%d" (plist-get p :date))
9902 (cons "%m" (plist-get p :message-id)))))
9903 (when (string-match "%c" fmt)
9904 ;; Check if the user wrote this message
9905 (if (and org-from-is-user-regexp from to
9906 (save-match-data (string-match org-from-is-user-regexp from)))
9907 (setq fmt (replace-match "to %t" t t fmt))
9908 (setq fmt (replace-match "from %f" t t fmt))))
9909 (org-replace-escapes fmt table)))
9911 (defun org-make-org-heading-search-string (&optional string)
9912 "Make search string for the current headline or STRING."
9913 (let ((s (or string
9914 (and (derived-mode-p 'org-mode)
9915 (save-excursion
9916 (org-back-to-heading t)
9917 (org-element-property :raw-value (org-element-at-point))))))
9918 (lines org-context-in-file-links))
9919 (unless string (setq s (concat "*" s))) ;Add * for headlines
9920 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9921 (when (and string (integerp lines) (> lines 0))
9922 (let ((slines (org-split-string s "\n")))
9923 (when (< lines (length slines))
9924 (setq s (mapconcat
9925 'identity
9926 (reverse (nthcdr (- (length slines) lines)
9927 (reverse slines))) "\n")))))
9928 (mapconcat #'identity (split-string s) " ")))
9930 (defun org-make-link-string (link &optional description)
9931 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9932 (unless (org-string-nw-p link) (error "Empty link"))
9933 (let ((uri (cond ((string-match org-link-types-re link)
9934 (concat (match-string 1 link)
9935 (org-link-escape (substring link (match-end 1)))))
9936 ;; For readability, url-encode internal links only
9937 ;; when absolutely needed (i.e, when they contain
9938 ;; square brackets). File links however, are
9939 ;; encoded since, e.g., spaces are significant.
9940 ((or (file-name-absolute-p link)
9941 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9942 (org-link-escape link))
9943 (t link)))
9944 (description
9945 (and (org-string-nw-p description)
9946 ;; Remove brackets from description, as they are fatal.
9947 (replace-regexp-in-string
9948 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9949 (org-trim description)))))
9950 (format "[[%s]%s]"
9952 (if description (format "[%s]" description) ""))))
9954 (defconst org-link-escape-chars
9955 ;;%20 %5B %5D %25
9956 '(?\s ?\[ ?\] ?%)
9957 "List of characters that should be escaped in a link when stored to Org.
9958 This is the list that is used for internal purposes.")
9960 (defun org-link-escape (text &optional table merge)
9961 "Return percent escaped representation of TEXT.
9962 TEXT is a string with the text to escape.
9963 Optional argument TABLE is a list with characters that should be
9964 escaped. When nil, `org-link-escape-chars' is used.
9965 If optional argument MERGE is set, merge TABLE into
9966 `org-link-escape-chars'."
9967 (let ((characters-to-encode
9968 (cond ((null table) org-link-escape-chars)
9969 (merge (append org-link-escape-chars table))
9970 (t table))))
9971 (mapconcat
9972 (lambda (c)
9973 (if (or (memq c characters-to-encode)
9974 (and org-url-hexify-p (or (< c 32) (> c 126))))
9975 (mapconcat (lambda (e) (format "%%%.2X" e))
9976 (or (encode-coding-char c 'utf-8)
9977 (error "Unable to percent escape character: %c" c))
9979 (char-to-string c)))
9980 text "")))
9982 (defun org-link-unescape (str)
9983 "Unhex hexified Unicode parts in string STR.
9984 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9985 reciprocal of `org-link-escape', which see."
9986 (if (org-string-nw-p str)
9987 (replace-regexp-in-string
9988 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9989 str))
9991 (defun org-link-unescape-compound (hex)
9992 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9993 Note: this function also decodes single byte encodings like
9994 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9995 (save-match-data
9996 (let* ((bytes (cdr (split-string hex "%")))
9997 (ret "")
9998 (eat 0)
9999 (sum 0))
10000 (while bytes
10001 (let* ((val (string-to-number (pop bytes) 16))
10002 (shift-xor
10003 (if (= 0 eat)
10004 (cond
10005 ((>= val 252) (cons 6 252))
10006 ((>= val 248) (cons 5 248))
10007 ((>= val 240) (cons 4 240))
10008 ((>= val 224) (cons 3 224))
10009 ((>= val 192) (cons 2 192))
10010 (t (cons 0 0)))
10011 (cons 6 128))))
10012 (when (>= val 192) (setq eat (car shift-xor)))
10013 (setq val (logxor val (cdr shift-xor)))
10014 (setq sum (+ (lsh sum (car shift-xor)) val))
10015 (when (> eat 0) (setq eat (- eat 1)))
10016 (cond
10017 ((= 0 eat) ;multi byte
10018 (setq ret (concat ret (char-to-string sum)))
10019 (setq sum 0))
10020 ((not bytes) ; single byte(s)
10021 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10022 ret)))
10024 (defun org-link-unescape-single-byte-sequence (hex)
10025 "Unhexify hex-encoded single byte character sequences."
10026 (mapconcat (lambda (byte)
10027 (char-to-string (string-to-number byte 16)))
10028 (cdr (split-string hex "%")) ""))
10030 (defun org-xor (a b)
10031 "Exclusive or."
10032 (if a (not b) b))
10034 (defun org-fixup-message-id-for-http (s)
10035 "Replace special characters in a message id, so it can be used in an http query."
10036 (when (string-match "%" s)
10037 (setq s (mapconcat (lambda (c)
10038 (if (eq c ?%)
10039 "%25"
10040 (char-to-string c)))
10041 s "")))
10042 (while (string-match "<" s)
10043 (setq s (replace-match "%3C" t t s)))
10044 (while (string-match ">" s)
10045 (setq s (replace-match "%3E" t t s)))
10046 (while (string-match "@" s)
10047 (setq s (replace-match "%40" t t s)))
10050 (defun org-link-prettify (link)
10051 "Return a human-readable representation of LINK.
10052 The car of LINK must be a raw link.
10053 The cdr of LINK must be either a link description or nil."
10054 (let ((desc (or (cadr link) "<no description>")))
10055 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10056 "<" (car link) ">")))
10058 ;;;###autoload
10059 (defun org-insert-link-global ()
10060 "Insert a link like Org mode does.
10061 This command can be called in any mode to insert a link in Org syntax."
10062 (interactive)
10063 (org-load-modules-maybe)
10064 (org-run-like-in-org-mode 'org-insert-link))
10066 (defun org-insert-all-links (arg &optional pre post)
10067 "Insert all links in `org-stored-links'.
10068 When a universal prefix, do not delete the links from `org-stored-links'.
10069 When `ARG' is a number, insert the last N link(s).
10070 `PRE' and `POST' are optional arguments to define a string to
10071 prepend or to append."
10072 (interactive "P")
10073 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10074 (links (copy-sequence org-stored-links))
10075 (pr (or pre "- "))
10076 (po (or post "\n"))
10077 (cnt 1) l)
10078 (if (null org-stored-links)
10079 (message "No link to insert")
10080 (while (and (or (listp arg) (>= arg cnt))
10081 (setq l (if (listp arg)
10082 (pop links)
10083 (pop org-stored-links))))
10084 (setq cnt (1+ cnt))
10085 (insert pr)
10086 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10087 (insert po)))))
10089 (defun org-insert-last-stored-link (arg)
10090 "Insert the last link stored in `org-stored-links'."
10091 (interactive "p")
10092 (org-insert-all-links arg "" "\n"))
10094 (defun org-link-fontify-links-to-this-file ()
10095 "Fontify links to the current file in `org-stored-links'."
10096 (let ((f (buffer-file-name)) a b)
10097 (setq a (mapcar (lambda(l)
10098 (let ((ll (car l)))
10099 (when (and (string-match "^file:\\(.+\\)::" ll)
10100 (equal f (expand-file-name (match-string 1 ll))))
10101 ll)))
10102 org-stored-links))
10103 (when (featurep 'org-id)
10104 (setq b (mapcar (lambda(l)
10105 (let ((ll (car l)))
10106 (when (and (string-match "^id:\\(.+\\)$" ll)
10107 (equal f (expand-file-name
10108 (or (org-id-find-id-file
10109 (match-string 1 ll)) ""))))
10110 ll)))
10111 org-stored-links)))
10112 (mapcar (lambda(l)
10113 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10114 (delq nil (append a b)))))
10116 (defvar org--links-history nil)
10117 (defun org-insert-link (&optional complete-file link-location default-description)
10118 "Insert a link. At the prompt, enter the link.
10120 Completion can be used to insert any of the link protocol prefixes in use.
10122 The history can be used to select a link previously stored with
10123 `org-store-link'. When the empty string is entered (i.e. if you just
10124 press `RET' at the prompt), the link defaults to the most recently
10125 stored link. As `SPC' triggers completion in the minibuffer, you need to
10126 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10128 You will also be prompted for a description, and if one is given, it will
10129 be displayed in the buffer instead of the link.
10131 If there is already a link at point, this command will allow you to edit
10132 link and description parts.
10134 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10135 file name can be
10136 selected using completion. The path to the file will be relative to the
10137 current directory if the file is in the current directory or a subdirectory.
10138 Otherwise, the link will be the absolute path as completed in the minibuffer
10139 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10140 option `org-link-file-path-type'.
10142 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10143 absolute path even if the file is in
10144 the current directory or below.
10146 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10147 prefix negates `org-keep-stored-link-after-insertion'.
10149 If the LINK-LOCATION parameter is non-nil, this value will be used as
10150 the link location instead of reading one interactively.
10152 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10153 be used as the default description. Otherwise, if
10154 `org-make-link-description-function' is non-nil, this function
10155 will be called with the link target, and the result will be the
10156 default link description."
10157 (interactive "P")
10158 (let* ((wcf (current-window-configuration))
10159 (origbuf (current-buffer))
10160 (region (when (org-region-active-p)
10161 (buffer-substring (region-beginning) (region-end))))
10162 (remove (and region (list (region-beginning) (region-end))))
10163 (desc region)
10164 (link link-location)
10165 (abbrevs org-link-abbrev-alist-local)
10166 entry all-prefixes auto-desc)
10167 (cond
10168 (link-location) ; specified by arg, just use it.
10169 ((org-in-regexp org-bracket-link-regexp 1)
10170 ;; We do have a link at point, and we are going to edit it.
10171 (setq remove (list (match-beginning 0) (match-end 0)))
10172 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10173 (setq link (read-string "Link: "
10174 (org-link-unescape
10175 (match-string-no-properties 1)))))
10176 ((or (org-in-regexp org-angle-link-re)
10177 (org-in-regexp org-plain-link-re))
10178 ;; Convert to bracket link
10179 (setq remove (list (match-beginning 0) (match-end 0))
10180 link (read-string "Link: "
10181 (org-unbracket-string "<" ">" (match-string 0)))))
10182 ((member complete-file '((4) (16)))
10183 ;; Completing read for file names.
10184 (setq link (org-file-complete-link complete-file)))
10186 ;; Read link, with completion for stored links.
10187 (org-link-fontify-links-to-this-file)
10188 (org-switch-to-buffer-other-window "*Org Links*")
10189 (with-current-buffer "*Org Links*"
10190 (erase-buffer)
10191 (insert "Insert a link.
10192 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10193 (when org-stored-links
10194 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10195 (insert (mapconcat 'org-link-prettify
10196 (reverse org-stored-links) "\n")))
10197 (goto-char (point-min)))
10198 (let ((cw (selected-window)))
10199 (select-window (get-buffer-window "*Org Links*" 'visible))
10200 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10201 (unless (pos-visible-in-window-p (point-max))
10202 (org-fit-window-to-buffer))
10203 (and (window-live-p cw) (select-window cw)))
10204 (setq all-prefixes (append (mapcar 'car abbrevs)
10205 (mapcar 'car org-link-abbrev-alist)
10206 (org-link-types)))
10207 (unwind-protect
10208 ;; Fake a link history, containing the stored links.
10209 (let ((org--links-history
10210 (append (mapcar #'car org-stored-links)
10211 org-insert-link-history)))
10212 (setq link
10213 (org-completing-read
10214 "Link: "
10215 (append
10216 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10217 (mapcar #'car org-stored-links))
10218 nil nil nil
10219 'org--links-history
10220 (caar org-stored-links)))
10221 (unless (org-string-nw-p link) (user-error "No link selected"))
10222 (dolist (l org-stored-links)
10223 (when (equal link (cadr l))
10224 (setq link (car l))
10225 (setq auto-desc t)))
10226 (when (or (member link all-prefixes)
10227 (and (equal ":" (substring link -1))
10228 (member (substring link 0 -1) all-prefixes)
10229 (setq link (substring link 0 -1))))
10230 (setq link (with-current-buffer origbuf
10231 (org-link-try-special-completion link)))))
10232 (set-window-configuration wcf)
10233 (kill-buffer "*Org Links*"))
10234 (setq entry (assoc link org-stored-links))
10235 (or entry (push link org-insert-link-history))
10236 (setq desc (or desc (nth 1 entry)))))
10238 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10239 (not org-keep-stored-link-after-insertion))
10240 (setq org-stored-links (delq (assoc link org-stored-links)
10241 org-stored-links)))
10243 (when (and (string-match org-plain-link-re link)
10244 (not (string-match org-ts-regexp link)))
10245 ;; URL-like link, normalize the use of angular brackets.
10246 (setq link (org-unbracket-string "<" ">" link)))
10248 ;; Check if we are linking to the current file with a search
10249 ;; option If yes, simplify the link by using only the search
10250 ;; option.
10251 (when (and buffer-file-name
10252 (let ((case-fold-search nil))
10253 (string-match "\\`file:\\(.+?\\)::" link)))
10254 (let ((path (match-string-no-properties 1 link))
10255 (search (substring-no-properties link (match-end 0))))
10256 (save-match-data
10257 (when (equal (file-truename buffer-file-name) (file-truename path))
10258 ;; We are linking to this same file, with a search option
10259 (setq link search)))))
10261 ;; Check if we can/should use a relative path. If yes, simplify the link
10262 (let ((case-fold-search nil))
10263 (when (string-match "\\`\\(file\\|docview\\):" link)
10264 (let* ((type (match-string-no-properties 0 link))
10265 (path (substring-no-properties link (match-end 0)))
10266 (origpath path))
10267 (cond
10268 ((or (eq org-link-file-path-type 'absolute)
10269 (equal complete-file '(16)))
10270 (setq path (abbreviate-file-name (expand-file-name path))))
10271 ((eq org-link-file-path-type 'noabbrev)
10272 (setq path (expand-file-name path)))
10273 ((eq org-link-file-path-type 'relative)
10274 (setq path (file-relative-name path)))
10276 (save-match-data
10277 (if (string-match (concat "^" (regexp-quote
10278 (expand-file-name
10279 (file-name-as-directory
10280 default-directory))))
10281 (expand-file-name path))
10282 ;; We are linking a file with relative path name.
10283 (setq path (substring (expand-file-name path)
10284 (match-end 0)))
10285 (setq path (abbreviate-file-name (expand-file-name path)))))))
10286 (setq link (concat type path))
10287 (when (equal desc origpath)
10288 (setq desc path)))))
10290 (unless auto-desc
10291 (let ((initial-input
10292 (cond
10293 (default-description)
10294 ((not org-make-link-description-function) desc)
10295 (t (condition-case nil
10296 (funcall org-make-link-description-function link desc)
10297 (error
10298 (message "Can't get link description from `%s'"
10299 (symbol-name org-make-link-description-function))
10300 (sit-for 2)
10301 nil))))))
10302 (setq desc (read-string "Description: " initial-input))))
10304 (unless (string-match "\\S-" desc) (setq desc nil))
10305 (when remove (apply 'delete-region remove))
10306 (insert (org-make-link-string link desc))
10307 ;; Redisplay so as the new link has proper invisible characters.
10308 (sit-for 0)))
10310 (defun org-link-try-special-completion (type)
10311 "If there is completion support for link type TYPE, offer it."
10312 (let ((fun (org-link-get-parameter type :complete)))
10313 (if (functionp fun)
10314 (funcall fun)
10315 (read-string "Link (no completion support): " (concat type ":")))))
10317 (defun org-file-complete-link (&optional arg)
10318 "Create a file link using completion."
10319 (let ((file (read-file-name "File: "))
10320 (pwd (file-name-as-directory (expand-file-name ".")))
10321 (pwd1 (file-name-as-directory (abbreviate-file-name
10322 (expand-file-name ".")))))
10323 (cond ((equal arg '(16))
10324 (concat "file:"
10325 (abbreviate-file-name (expand-file-name file))))
10326 ((string-match
10327 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10328 (concat "file:" (match-string 1 file)))
10329 ((string-match
10330 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10331 (expand-file-name file))
10332 (concat "file:"
10333 (match-string 1 (expand-file-name file))))
10334 (t (concat "file:" file)))))
10336 (defun org-completing-read (&rest args)
10337 "Completing-read with SPACE being a normal character."
10338 (let ((enable-recursive-minibuffers t)
10339 (minibuffer-local-completion-map
10340 (copy-keymap minibuffer-local-completion-map)))
10341 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10342 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10343 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10344 'org-time-stamp-inactive)
10345 (apply #'completing-read args)))
10347 ;;; Opening/following a link
10349 (defvar org-link-search-failed nil)
10351 (defvar org-open-link-functions nil
10352 "Hook for functions finding a plain text link.
10353 These functions must take a single argument, the link content.
10354 They will be called for links that look like [[link text][description]]
10355 when LINK TEXT does not have a protocol like \"http:\" and does not look
10356 like a filename (e.g. \"./blue.png\").
10358 These functions will be called *before* Org attempts to resolve the
10359 link by doing text searches in the current buffer - so if you want a
10360 link \"[[target]]\" to still find \"<<target>>\", your function should
10361 handle this as a special case.
10363 When the function does handle the link, it must return a non-nil value.
10364 If it decides that it is not responsible for this link, it must return
10365 nil to indicate that that Org can continue with other options like
10366 exact and fuzzy text search.")
10368 (defun org-next-link (&optional search-backward)
10369 "Move forward to the next link.
10370 If the link is in hidden text, expose it."
10371 (interactive "P")
10372 (when (and org-link-search-failed (eq this-command last-command))
10373 (goto-char (point-min))
10374 (message "Link search wrapped back to beginning of buffer"))
10375 (setq org-link-search-failed nil)
10376 (let* ((pos (point))
10377 (ct (org-context))
10378 (a (assq :link ct))
10379 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10380 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10381 ((looking-at org-any-link-re)
10382 ;; Don't stay stuck at link without an org-link face
10383 (forward-char (if search-backward -1 1))))
10384 (if (funcall srch-fun org-any-link-re nil t)
10385 (progn
10386 (goto-char (match-beginning 0))
10387 (when (org-invisible-p) (org-show-context)))
10388 (goto-char pos)
10389 (setq org-link-search-failed t)
10390 (message "No further link found"))))
10392 (defun org-previous-link ()
10393 "Move backward to the previous link.
10394 If the link is in hidden text, expose it."
10395 (interactive)
10396 (funcall 'org-next-link t))
10398 (defun org-translate-link (s)
10399 "Translate a link string if a translation function has been defined."
10400 (with-temp-buffer
10401 (insert (org-trim s))
10402 (org-trim (org-element-interpret-data (org-element-context)))))
10404 (defun org-translate-link-from-planner (type path)
10405 "Translate a link from Emacs Planner syntax so that Org can follow it.
10406 This is still an experimental function, your mileage may vary."
10407 (cond
10408 ((member type '("http" "https" "news" "ftp"))
10409 ;; standard Internet links are the same.
10410 nil)
10411 ((and (equal type "irc") (string-match "^//" path))
10412 ;; Planner has two / at the beginning of an irc link, we have 1.
10413 ;; We should have zero, actually....
10414 (setq path (substring path 1)))
10415 ((and (equal type "lisp") (string-match "^/" path))
10416 ;; Planner has a slash, we do not.
10417 (setq type "elisp" path (substring path 1)))
10418 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10419 ;; A typical message link. Planner has the id after the final slash,
10420 ;; we separate it with a hash mark
10421 (setq path (concat (match-string 1 path) "#"
10422 (org-unbracket-string "<" ">" (match-string 2 path))))))
10423 (cons type path))
10425 (defun org-find-file-at-mouse (ev)
10426 "Open file link or URL at mouse."
10427 (interactive "e")
10428 (mouse-set-point ev)
10429 (org-open-at-point 'in-emacs))
10431 (defun org-open-at-mouse (ev)
10432 "Open file link or URL at mouse.
10433 See the docstring of `org-open-file' for details."
10434 (interactive "e")
10435 (mouse-set-point ev)
10436 (when (eq major-mode 'org-agenda-mode)
10437 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10438 (org-open-at-point))
10440 (defvar org-window-config-before-follow-link nil
10441 "The window configuration before following a link.
10442 This is saved in case the need arises to restore it.")
10444 ;;;###autoload
10445 (defun org-open-at-point-global ()
10446 "Follow a link or time-stamp like Org mode does.
10447 This command can be called in any mode to follow an external link
10448 or a time-stamp that has Org mode syntax. Its behavior is
10449 undefined when called on internal links (e.g., fuzzy links).
10450 Raise an error when there is nothing to follow. "
10451 (interactive)
10452 (cond ((org-in-regexp org-any-link-re)
10453 (org-open-link-from-string (match-string-no-properties 0)))
10454 ((or (org-in-regexp org-ts-regexp-both nil t)
10455 (org-in-regexp org-tsr-regexp-both nil t))
10456 (org-follow-timestamp-link))
10457 (t (user-error "No link found"))))
10459 ;;;###autoload
10460 (defun org-open-link-from-string (s &optional arg reference-buffer)
10461 "Open a link in the string S, as if it was in Org mode."
10462 (interactive "sLink: \nP")
10463 (let ((reference-buffer (or reference-buffer (current-buffer))))
10464 (with-temp-buffer
10465 (let ((org-inhibit-startup (not reference-buffer)))
10466 (org-mode)
10467 (insert s)
10468 (goto-char (point-min))
10469 (when reference-buffer
10470 (setq org-link-abbrev-alist-local
10471 (with-current-buffer reference-buffer
10472 org-link-abbrev-alist-local)))
10473 (org-open-at-point arg reference-buffer)))))
10475 (defvar org-open-at-point-functions nil
10476 "Hook that is run when following a link at point.
10478 Functions in this hook must return t if they identify and follow
10479 a link at point. If they don't find anything interesting at point,
10480 they must return nil.")
10482 (defvar org-link-search-inhibit-query nil)
10483 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10484 (defun org--open-doi-link (path)
10485 "Open a \"doi\" type link.
10486 PATH is a the path to search for, as a string."
10487 (browse-url (url-encode-url (concat org-doi-server-url path))))
10489 (defun org--open-elisp-link (path)
10490 "Open a \"elisp\" type link.
10491 PATH is the sexp to evaluate, as a string."
10492 (let ((cmd path))
10493 (if (or (and (org-string-nw-p
10494 org-confirm-elisp-link-not-regexp)
10495 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10496 (not org-confirm-elisp-link-function)
10497 (funcall org-confirm-elisp-link-function
10498 (format "Execute \"%s\" as elisp? "
10499 (org-add-props cmd nil 'face 'org-warning))))
10500 (message "%s => %s" cmd
10501 (if (eq (string-to-char cmd) ?\()
10502 (eval (read cmd))
10503 (call-interactively (read cmd))))
10504 (user-error "Abort"))))
10506 (defun org--open-help-link (path)
10507 "Open a \"help\" type link.
10508 PATH is a symbol name, as a string."
10509 (pcase (intern path)
10510 ((and (pred fboundp) variable) (describe-function variable))
10511 ((and (pred boundp) function) (describe-variable function))
10512 (name (user-error "Unknown function or variable: %s" name))))
10514 (defun org--open-shell-link (path)
10515 "Open a \"shell\" type link.
10516 PATH is the command to execute, as a string."
10517 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10518 (cmd path))
10519 (if (or (and (org-string-nw-p
10520 org-confirm-shell-link-not-regexp)
10521 (string-match
10522 org-confirm-shell-link-not-regexp cmd))
10523 (not org-confirm-shell-link-function)
10524 (funcall org-confirm-shell-link-function
10525 (format "Execute \"%s\" in shell? "
10526 (org-add-props cmd nil
10527 'face 'org-warning))))
10528 (progn
10529 (message "Executing %s" cmd)
10530 (shell-command cmd buf)
10531 (when (featurep 'midnight)
10532 (setq clean-buffer-list-kill-buffer-names
10533 (cons (buffer-name buf)
10534 clean-buffer-list-kill-buffer-names))))
10535 (user-error "Abort"))))
10537 (defun org-open-at-point (&optional arg reference-buffer)
10538 "Open link, timestamp, footnote or tags at point.
10540 When point is on a link, follow it. Normally, files will be
10541 opened by an appropriate application. If the optional prefix
10542 argument ARG is non-nil, Emacs will visit the file. With
10543 a double prefix argument, try to open outside of Emacs, in the
10544 application the system uses for this file type.
10546 When point is on a timestamp, open the agenda at the day
10547 specified.
10549 When point is a footnote definition, move to the first reference
10550 found. If it is on a reference, move to the associated
10551 definition.
10553 When point is on a headline, display a list of every link in the
10554 entry, so it is possible to pick one, or all, of them. If point
10555 is on a tag, call `org-tags-view' instead.
10557 When optional argument REFERENCE-BUFFER is non-nil, it should
10558 specify a buffer from where the link search should happen. This
10559 is used internally by `org-open-link-from-string'.
10561 On top of syntactically correct links, this function will also
10562 try to open links and time-stamps in comments, example
10563 blocks... i.e., whenever point is on something looking like
10564 a timestamp or a link."
10565 (interactive "P")
10566 ;; On a code block, open block's results.
10567 (unless (call-interactively 'org-babel-open-src-block-result)
10568 (org-load-modules-maybe)
10569 (setq org-window-config-before-follow-link (current-window-configuration))
10570 (org-remove-occur-highlights nil nil t)
10571 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10572 (let* ((context
10573 ;; Only consider supported types, even if they are not
10574 ;; the closest one.
10575 (org-element-lineage
10576 (org-element-context)
10577 '(clock footnote-definition footnote-reference headline
10578 inlinetask link timestamp)
10580 (type (org-element-type context))
10581 (value (org-element-property :value context)))
10582 (cond
10583 ;; On a headline or an inlinetask, but not on a timestamp,
10584 ;; a link, a footnote reference.
10585 ((memq type '(headline inlinetask))
10586 (org-match-line org-complex-heading-regexp)
10587 (if (and (match-beginning 5)
10588 (>= (point) (match-beginning 5))
10589 (< (point) (match-end 5)))
10590 ;; On tags.
10591 (org-tags-view arg (substring (match-string 5) 0 -1))
10592 ;; Not on tags.
10593 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10594 (`(nil . ,_)
10595 (require 'org-attach)
10596 (org-attach-reveal 'if-exists))
10597 (`(,links . ,links-end)
10598 (dolist (link (if (stringp links) (list links) links))
10599 (search-forward link nil links-end)
10600 (goto-char (match-beginning 0))
10601 (org-open-at-point))))))
10602 ;; On a footnote reference or at definition's label.
10603 ((or (eq type 'footnote-reference)
10604 (and (eq type 'footnote-definition)
10605 (save-excursion
10606 ;; Do not validate action when point is on the
10607 ;; spaces right after the footnote label, in
10608 ;; order to be on par with behaviour on links.
10609 (skip-chars-forward " \t")
10610 (let ((begin
10611 (org-element-property :contents-begin context)))
10612 (if begin (< (point) begin)
10613 (= (org-element-property :post-affiliated context)
10614 (line-beginning-position)))))))
10615 (org-footnote-action))
10616 ;; No valid context. Ignore catch-all types like `headline'.
10617 ;; If point is on something looking like a link or
10618 ;; a time-stamp, try opening it. It may be useful in
10619 ;; comments, example blocks...
10620 ((memq type '(footnote-definition headline inlinetask nil))
10621 (call-interactively #'org-open-at-point-global))
10622 ;; On a clock line, make sure point is on the timestamp
10623 ;; before opening it.
10624 ((and (eq type 'clock)
10625 value
10626 (>= (point) (org-element-property :begin value))
10627 (<= (point) (org-element-property :end value)))
10628 (org-follow-timestamp-link))
10629 ;; Do nothing on white spaces after an object.
10630 ((>= (point)
10631 (save-excursion
10632 (goto-char (org-element-property :end context))
10633 (skip-chars-backward " \t")
10634 (point)))
10635 (user-error "No link found"))
10636 ((eq type 'timestamp) (org-follow-timestamp-link))
10637 ((eq type 'link)
10638 (let ((type (org-element-property :type context))
10639 (path (org-link-unescape (org-element-property :path context))))
10640 ;; Switch back to REFERENCE-BUFFER needed when called in
10641 ;; a temporary buffer through `org-open-link-from-string'.
10642 (with-current-buffer (or reference-buffer (current-buffer))
10643 (cond
10644 ((equal type "file")
10645 (if (string-match "[*?{]" (file-name-nondirectory path))
10646 (dired path)
10647 ;; Look into `org-link-parameters' in order to find
10648 ;; a DEDICATED-FUNCTION to open file. The function
10649 ;; will be applied on raw link instead of parsed
10650 ;; link due to the limitation in `org-add-link-type'
10651 ;; ("open" function called with a single argument).
10652 ;; If no such function is found, fallback to
10653 ;; `org-open-file'.
10654 (let* ((option (org-element-property :search-option context))
10655 (app (org-element-property :application context))
10656 (dedicated-function
10657 (org-link-get-parameter
10658 (if app (concat type "+" app) type)
10659 :follow)))
10660 (if dedicated-function
10661 (funcall dedicated-function
10662 (concat path
10663 (and option (concat "::" option))))
10664 (apply #'org-open-file
10665 path
10666 (cond (arg)
10667 ((equal app "emacs") 'emacs)
10668 ((equal app "sys") 'system))
10669 (cond ((not option) nil)
10670 ((string-match-p "\\`[0-9]+\\'" option)
10671 (list (string-to-number option)))
10672 (t (list nil
10673 (org-link-unescape option)))))))))
10674 ((functionp (org-link-get-parameter type :follow))
10675 (funcall (org-link-get-parameter type :follow) path))
10676 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10677 (unless (run-hook-with-args-until-success
10678 'org-open-link-functions path)
10679 (if (not arg) (org-mark-ring-push)
10680 (switch-to-buffer-other-window
10681 (org-get-buffer-for-internal-link (current-buffer))))
10682 (let ((destination
10683 (org-with-wide-buffer
10684 (if (equal type "radio")
10685 (org-search-radio-target
10686 (org-element-property :path context))
10687 (org-link-search
10688 (if (member type '("custom-id" "coderef"))
10689 (org-element-property :raw-link context)
10690 path)
10691 ;; Prevent fuzzy links from matching
10692 ;; themselves.
10693 (and (equal type "fuzzy")
10694 (+ 2 (org-element-property :begin context)))))
10695 (point))))
10696 (unless (and (<= (point-min) destination)
10697 (>= (point-max) destination))
10698 (widen))
10699 (goto-char destination))))
10700 (t (browse-url-at-point))))))
10701 (t (user-error "No link found")))))
10702 (run-hook-with-args 'org-follow-link-hook)))
10704 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10705 "Offer links in the current entry and return the selected link.
10706 If there is only one link, return it.
10707 If NTH is an integer, return the NTH link found.
10708 If ZERO is a string, check also this string for a link, and if
10709 there is one, return it."
10710 (with-current-buffer buffer
10711 (org-with-wide-buffer
10712 (goto-char marker)
10713 (let ((cnt ?0)
10714 have-zero end links link c)
10715 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10716 (push (match-string 0 zero) links)
10717 (setq cnt (1- cnt) have-zero t))
10718 (save-excursion
10719 (org-back-to-heading t)
10720 (setq end (save-excursion (outline-next-heading) (point)))
10721 (while (re-search-forward org-any-link-re end t)
10722 (push (match-string 0) links))
10723 (setq links (org-uniquify (reverse links))))
10724 (cond
10725 ((null links)
10726 (message "No links"))
10727 ((equal (length links) 1)
10728 (setq link (car links)))
10729 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10730 (setq link (nth (if have-zero nth (1- nth)) links)))
10731 (t ; we have to select a link
10732 (save-excursion
10733 (save-window-excursion
10734 (delete-other-windows)
10735 (with-output-to-temp-buffer "*Select Link*"
10736 (dolist (l links)
10737 (cond
10738 ((not (string-match org-bracket-link-regexp l))
10739 (princ (format "[%c] %s\n" (cl-incf cnt)
10740 (org-unbracket-string "<" ">" l))))
10741 ((match-end 3)
10742 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10743 (match-string 3 l) (match-string 1 l))))
10744 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10745 (match-string 1 l)))))))
10746 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10747 (message "Select link to open, RET to open all:")
10748 (setq c (read-char-exclusive))
10749 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10750 (when (equal c ?q) (user-error "Abort"))
10751 (if (equal c ?\C-m)
10752 (setq link links)
10753 (setq nth (- c ?0))
10754 (when have-zero (setq nth (1+ nth)))
10755 (unless (and (integerp nth) (>= (length links) nth))
10756 (user-error "Invalid link selection"))
10757 (setq link (nth (1- nth) links)))))
10758 (cons link end)))))
10760 ;; TODO: These functions are deprecated since `org-open-at-point'
10761 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10762 (defun org-open-file-with-system (path)
10763 "Open file at PATH using the system way of opening it."
10764 (org-open-file path 'system))
10765 (defun org-open-file-with-emacs (path)
10766 "Open file at PATH in Emacs."
10767 (org-open-file path 'emacs))
10770 ;;; File search
10772 (defvar org-create-file-search-functions nil
10773 "List of functions to construct the right search string for a file link.
10774 These functions are called in turn with point at the location to
10775 which the link should point.
10777 A function in the hook should first test if it would like to
10778 handle this file type, for example by checking the `major-mode'
10779 or the file extension. If it decides not to handle this file, it
10780 should just return nil to give other functions a chance. If it
10781 does handle the file, it must return the search string to be used
10782 when following the link. The search string will be part of the
10783 file link, given after a double colon, and `org-open-at-point'
10784 will automatically search for it. If special measures must be
10785 taken to make the search successful, another function should be
10786 added to the companion hook `org-execute-file-search-functions',
10787 which see.
10789 A function in this hook may also use `setq' to set the variable
10790 `description' to provide a suggestion for the descriptive text to
10791 be used for this link when it gets inserted into an Org buffer
10792 with \\[org-insert-link].")
10794 (defvar org-execute-file-search-functions nil
10795 "List of functions to execute a file search triggered by a link.
10797 Functions added to this hook must accept a single argument, the
10798 search string that was part of the file link, the part after the
10799 double colon. The function must first check if it would like to
10800 handle this search, for example by checking the `major-mode' or
10801 the file extension. If it decides not to handle this search, it
10802 should just return nil to give other functions a chance. If it
10803 does handle the search, it must return a non-nil value to keep
10804 other functions from trying.
10806 Each function can access the current prefix argument through the
10807 variable `current-prefix-arg'. Note that a single prefix is used
10808 to force opening a link in Emacs, so it may be good to only use a
10809 numeric or double prefix to guide the search function.
10811 In case this is needed, a function in this hook can also restore
10812 the window configuration before `org-open-at-point' was called using:
10814 (set-window-configuration org-window-config-before-follow-link)")
10816 (defun org-search-radio-target (target)
10817 "Search a radio target matching TARGET in current buffer.
10818 White spaces are not significant."
10819 (let ((re (format "<<<%s>>>"
10820 (mapconcat #'regexp-quote
10821 (split-string target)
10822 "[ \t]+\\(?:\n[ \t]*\\)?")))
10823 (origin (point)))
10824 (goto-char (point-min))
10825 (catch :radio-match
10826 (while (re-search-forward re nil t)
10827 (backward-char)
10828 (let ((object (org-element-context)))
10829 (when (eq (org-element-type object) 'radio-target)
10830 (goto-char (org-element-property :begin object))
10831 (org-show-context 'link-search)
10832 (throw :radio-match nil))))
10833 (goto-char origin)
10834 (user-error "No match for radio target: %s" target))))
10836 (defun org-link-search (s &optional avoid-pos stealth)
10837 "Search for a search string S.
10839 If S starts with \"#\", it triggers a custom ID search.
10841 If S is enclosed within parenthesis, it initiates a coderef
10842 search.
10844 If S is surrounded by forward slashes, it is interpreted as
10845 a regular expression. In Org mode files, this will create an
10846 `org-occur' sparse tree. In ordinary files, `occur' will be used
10847 to list matches. If the current buffer is in `dired-mode', grep
10848 will be used to search in all files.
10850 When AVOID-POS is given, ignore matches near that position.
10852 When optional argument STEALTH is non-nil, do not modify
10853 visibility around point, thus ignoring `org-show-context-detail'
10854 variable.
10856 Search is case-insensitive and ignores white spaces. Return type
10857 of matched result, which is either `dedicated' or `fuzzy'."
10858 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10859 (let* ((case-fold-search t)
10860 (origin (point))
10861 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10862 (starred (eq (string-to-char normalized) ?*))
10863 (words (split-string (if starred (substring s 1) s)))
10864 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10865 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10866 type)
10867 (cond
10868 ;; Check if there are any special search functions.
10869 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10870 ((eq (string-to-char s) ?#)
10871 ;; Look for a custom ID S if S starts with "#".
10872 (let* ((id (substring normalized 1))
10873 (match (org-find-property "CUSTOM_ID" id)))
10874 (if match (progn (goto-char match) (setf type 'dedicated))
10875 (error "No match for custom ID: %s" id))))
10876 ((string-match "\\`(\\(.*\\))\\'" normalized)
10877 ;; Look for coderef targets if S is enclosed within parenthesis.
10878 (let ((coderef (match-string-no-properties 1 normalized))
10879 (re (substring s-single-re 1 -1)))
10880 (goto-char (point-min))
10881 (catch :coderef-match
10882 (while (re-search-forward re nil t)
10883 (let ((element (org-element-at-point)))
10884 (when (and (memq (org-element-type element)
10885 '(example-block src-block))
10886 ;; Build proper regexp according to current
10887 ;; block's label format.
10888 (let ((label-fmt
10889 (regexp-quote
10890 (or (org-element-property :label-fmt element)
10891 org-coderef-label-format))))
10892 (save-excursion
10893 (beginning-of-line)
10894 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10895 (format label-fmt coderef))))))
10896 (setq type 'dedicated)
10897 (goto-char (match-beginning 1))
10898 (throw :coderef-match nil))))
10899 (goto-char origin)
10900 (error "No match for coderef: %s" coderef))))
10901 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10902 ;; Look for a regular expression.
10903 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10904 (match-string 1 s)))
10905 ;; From here, we handle fuzzy links.
10907 ;; Look for targets, only if not in a headline search.
10908 ((and (not starred)
10909 (let ((target (format "<<%s>>" s-multi-re)))
10910 (catch :target-match
10911 (goto-char (point-min))
10912 (while (re-search-forward target nil t)
10913 (backward-char)
10914 (let ((context (org-element-context)))
10915 (when (eq (org-element-type context) 'target)
10916 (setq type 'dedicated)
10917 (goto-char (org-element-property :begin context))
10918 (throw :target-match t))))
10919 nil))))
10920 ;; Look for elements named after S, only if not in a headline
10921 ;; search.
10922 ((and (not starred)
10923 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10924 (catch :name-match
10925 (goto-char (point-min))
10926 (while (re-search-forward name nil t)
10927 (let ((element (org-element-at-point)))
10928 (when (equal words
10929 (split-string
10930 (org-element-property :name element)))
10931 (setq type 'dedicated)
10932 (beginning-of-line)
10933 (throw :name-match t))))
10934 nil))))
10935 ;; Regular text search. Prefer headlines in Org mode buffers.
10936 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10937 ;; statistics cookies and tags.
10938 ((and (derived-mode-p 'org-mode)
10939 (let ((title-re
10940 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10941 org-outline-regexp-bol
10942 org-comment-string
10943 (mapconcat #'regexp-quote words ".+")))
10944 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10945 (comment-re (eval-when-compile
10946 (format "\\`%s[ \t]+" org-comment-string))))
10947 (goto-char (point-min))
10948 (catch :found
10949 (while (re-search-forward title-re nil t)
10950 (when (equal words
10951 (split-string
10952 (replace-regexp-in-string
10953 cookie-re ""
10954 (replace-regexp-in-string
10955 comment-re "" (org-get-heading t t t)))))
10956 (throw :found t)))
10957 nil)))
10958 (beginning-of-line)
10959 (setq type 'dedicated))
10960 ;; Offer to create non-existent headline depending on
10961 ;; `org-link-search-must-match-exact-headline'.
10962 ((and (derived-mode-p 'org-mode)
10963 (not org-link-search-inhibit-query)
10964 (eq org-link-search-must-match-exact-headline 'query-to-create)
10965 (yes-or-no-p "No match - create this as a new heading? "))
10966 (goto-char (point-max))
10967 (unless (bolp) (newline))
10968 (org-insert-heading nil t t)
10969 (insert s "\n")
10970 (beginning-of-line 0))
10971 ;; Only headlines are looked after. No need to process
10972 ;; further: throw an error.
10973 ((and (derived-mode-p 'org-mode)
10974 (or starred org-link-search-must-match-exact-headline))
10975 (goto-char origin)
10976 (error "No match for fuzzy expression: %s" normalized))
10977 ;; Regular text search.
10978 ((catch :fuzzy-match
10979 (goto-char (point-min))
10980 (while (re-search-forward s-multi-re nil t)
10981 ;; Skip match if it contains AVOID-POS or it is included in
10982 ;; a link with a description but outside the description.
10983 (unless (or (and avoid-pos
10984 (<= (match-beginning 0) avoid-pos)
10985 (> (match-end 0) avoid-pos))
10986 (and (save-match-data
10987 (org-in-regexp org-bracket-link-regexp))
10988 (match-beginning 3)
10989 (or (> (match-beginning 3) (point))
10990 (<= (match-end 3) (point)))
10991 (org-element-lineage
10992 (save-match-data (org-element-context))
10993 '(link) t)))
10994 (goto-char (match-beginning 0))
10995 (setq type 'fuzzy)
10996 (throw :fuzzy-match t)))
10997 nil))
10998 ;; All failed. Throw an error.
10999 (t (goto-char origin)
11000 (error "No match for fuzzy expression: %s" normalized)))
11001 ;; Disclose surroundings of match, if appropriate.
11002 (when (and (derived-mode-p 'org-mode) (not stealth))
11003 (org-show-context 'link-search))
11004 type))
11006 (defun org-get-buffer-for-internal-link (buffer)
11007 "Return a buffer to be used for displaying the link target of internal links."
11008 (cond
11009 ((not org-display-internal-link-with-indirect-buffer)
11010 buffer)
11011 ((string-suffix-p "(Clone)" (buffer-name buffer))
11012 (message "Buffer is already a clone, not making another one")
11013 ;; we also do not modify visibility in this case
11014 buffer)
11015 (t ; make a new indirect buffer for displaying the link
11016 (let* ((bn (buffer-name buffer))
11017 (ibn (concat bn "(Clone)"))
11018 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11019 (with-current-buffer ib (org-overview))
11020 ib))))
11022 (defun org-do-occur (regexp &optional cleanup)
11023 "Call the Emacs command `occur'.
11024 If CLEANUP is non-nil, remove the printout of the regular expression
11025 in the *Occur* buffer. This is useful if the regex is long and not useful
11026 to read."
11027 (occur regexp)
11028 (when cleanup
11029 (let ((cwin (selected-window)) win beg end)
11030 (when (setq win (get-buffer-window "*Occur*"))
11031 (select-window win))
11032 (goto-char (point-min))
11033 (when (re-search-forward "match[a-z]+" nil t)
11034 (setq beg (match-end 0))
11035 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11036 (setq end (1- (match-beginning 0)))))
11037 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11038 (goto-char (point-min))
11039 (select-window cwin))))
11041 ;;; The mark ring for links jumps
11043 (defvar org-mark-ring nil
11044 "Mark ring for positions before jumps in Org mode.")
11045 (defvar org-mark-ring-last-goto nil
11046 "Last position in the mark ring used to go back.")
11047 ;; Fill and close the ring
11048 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11049 (dotimes (_ org-mark-ring-length)
11050 (push (make-marker) org-mark-ring))
11051 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11052 org-mark-ring)
11054 (defun org-mark-ring-push (&optional pos buffer)
11055 "Put the current position or POS into the mark ring and rotate it."
11056 (interactive)
11057 (setq pos (or pos (point)))
11058 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11059 (move-marker (car org-mark-ring)
11060 (or pos (point))
11061 (or buffer (current-buffer)))
11062 (message "%s"
11063 (substitute-command-keys
11064 "Position saved to mark ring, go back with \
11065 `\\[org-mark-ring-goto]'.")))
11067 (defun org-mark-ring-goto (&optional n)
11068 "Jump to the previous position in the mark ring.
11069 With prefix arg N, jump back that many stored positions. When
11070 called several times in succession, walk through the entire ring.
11071 Org mode commands jumping to a different position in the current file,
11072 or to another Org file, automatically push the old position onto the ring."
11073 (interactive "p")
11074 (let (p m)
11075 (if (eq last-command this-command)
11076 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11077 (setq p org-mark-ring))
11078 (setq org-mark-ring-last-goto p)
11079 (setq m (car p))
11080 (pop-to-buffer-same-window (marker-buffer m))
11081 (goto-char m)
11082 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11084 (defun org-add-angle-brackets (s)
11085 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11086 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11089 ;;; Following specific links
11091 (defvar org-agenda-buffer-tmp-name)
11092 (defvar org-agenda-start-on-weekday)
11093 (defun org-follow-timestamp-link ()
11094 "Open an agenda view for the time-stamp date/range at point."
11095 (cond
11096 ((org-at-date-range-p t)
11097 (let ((org-agenda-start-on-weekday)
11098 (t1 (match-string 1))
11099 (t2 (match-string 2)) tt1 tt2)
11100 (setq tt1 (time-to-days (org-time-string-to-time t1))
11101 tt2 (time-to-days (org-time-string-to-time t2)))
11102 (let ((org-agenda-buffer-tmp-name
11103 (format "*Org Agenda(a:%s)"
11104 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11105 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11106 ((org-at-timestamp-p 'lax)
11107 (let ((org-agenda-buffer-tmp-name
11108 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11109 (org-agenda-list nil (time-to-days (org-time-string-to-time
11110 (substring (match-string 1) 0 10)))
11111 1)))
11112 (t (error "This should not happen"))))
11115 ;;; Following file links
11116 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11117 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11118 (declare-function mailcap-mime-info
11119 "mailcap" (string &optional request no-decode))
11120 (defvar org-wait nil)
11121 (defun org-open-file (path &optional in-emacs line search)
11122 "Open the file at PATH.
11123 First, this expands any special file name abbreviations. Then the
11124 configuration variable `org-file-apps' is checked if it contains an
11125 entry for this file type, and if yes, the corresponding command is launched.
11127 If no application is found, Emacs simply visits the file.
11129 With optional prefix argument IN-EMACS, Emacs will visit the file.
11130 With a double \\[universal-argument] \\[universal-argument] \
11131 prefix arg, Org tries to avoid opening in Emacs
11132 and to use an external application to visit the file.
11134 Optional LINE specifies a line to go to, optional SEARCH a string
11135 to search for. If LINE or SEARCH is given, the file will be
11136 opened in Emacs, unless an entry from org-file-apps that makes
11137 use of groups in a regexp matches.
11139 If you want to change the way frames are used when following a
11140 link, please customize `org-link-frame-setup'.
11142 If the file does not exist, an error is thrown."
11143 (let* ((file (if (equal path "")
11144 buffer-file-name
11145 (substitute-in-file-name (expand-file-name path))))
11146 (file-apps (append org-file-apps (org-default-apps)))
11147 (apps (cl-remove-if
11148 'org-file-apps-entry-match-against-dlink-p file-apps))
11149 (apps-dlink (cl-remove-if-not
11150 'org-file-apps-entry-match-against-dlink-p file-apps))
11151 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11152 (dirp (unless remp (file-directory-p file)))
11153 (file (if (and dirp org-open-directory-means-index-dot-org)
11154 (concat (file-name-as-directory file) "index.org")
11155 file))
11156 (a-m-a-p (assq 'auto-mode apps))
11157 (dfile (downcase file))
11158 ;; Reconstruct the original link from the PATH, LINE and
11159 ;; SEARCH args.
11160 (link (cond (line (concat file "::" (number-to-string line)))
11161 (search (concat file "::" search))
11162 (t file)))
11163 (dlink (downcase link))
11164 (ext
11165 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11166 (match-string 1 dfile)))
11167 (save-position-maybe
11168 (let ((old-buffer (current-buffer))
11169 (old-pos (point))
11170 (old-mode major-mode))
11171 (lambda ()
11172 (and (derived-mode-p 'org-mode)
11173 (eq old-mode 'org-mode)
11174 (or (not (eq old-buffer (current-buffer)))
11175 (not (eq old-pos (point))))
11176 (org-mark-ring-push old-pos old-buffer)))))
11177 cmd link-match-data)
11178 (cond
11179 ((member in-emacs '((16) system))
11180 (setq cmd (cdr (assq 'system apps))))
11181 (in-emacs (setq cmd 'emacs))
11183 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11184 (and dirp (cdr (assq 'directory apps)))
11185 ;; First, try matching against apps-dlink if we
11186 ;; get a match here, store the match data for
11187 ;; later.
11188 (let ((match (assoc-default dlink apps-dlink
11189 'string-match)))
11190 (if match
11191 (progn (setq link-match-data (match-data))
11192 match)
11193 (progn (setq in-emacs (or in-emacs line search))
11194 nil))) ; if we have no match in apps-dlink,
11195 ; always open the file in emacs if line or search
11196 ; is given (for backwards compatibility)
11197 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11198 'string-match)
11199 (cdr (assoc ext apps))
11200 (cdr (assq t apps))))))
11201 (when (eq cmd 'system)
11202 (setq cmd (cdr (assq 'system apps))))
11203 (when (eq cmd 'default)
11204 (setq cmd (cdr (assoc t apps))))
11205 (when (eq cmd 'mailcap)
11206 (require 'mailcap)
11207 (mailcap-parse-mailcaps)
11208 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11209 (command (mailcap-mime-info mime-type)))
11210 (if (stringp command)
11211 (setq cmd command)
11212 (setq cmd 'emacs))))
11213 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11214 (not (file-exists-p file))
11215 (not org-open-non-existing-files))
11216 (user-error "No such file: %s" file))
11217 (cond
11218 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11219 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11220 (while (string-match "['\"]%s['\"]" cmd)
11221 (setq cmd (replace-match "%s" t t cmd)))
11222 (setq cmd (replace-regexp-in-string
11223 "%s"
11224 (shell-quote-argument (convert-standard-filename file))
11226 nil t))
11228 ;; Replace "%1", "%2" etc. in command with group matches from regex
11229 (save-match-data
11230 (let ((match-index 1)
11231 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11232 (set-match-data link-match-data)
11233 (while (<= match-index number-of-groups)
11234 (let ((regex (concat "%" (number-to-string match-index)))
11235 (replace-with (match-string match-index dlink)))
11236 (while (string-match regex cmd)
11237 (setq cmd (replace-match replace-with t t cmd))))
11238 (setq match-index (+ match-index 1)))))
11240 (save-window-excursion
11241 (message "Running %s...done" cmd)
11242 (start-process-shell-command cmd nil cmd)
11243 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11244 ((or (stringp cmd)
11245 (eq cmd 'emacs))
11246 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11247 (widen)
11248 (cond (line (org-goto-line line)
11249 (when (derived-mode-p 'org-mode) (org-reveal)))
11250 (search (condition-case err
11251 (org-link-search search)
11252 ;; Save position before error-ing out so user
11253 ;; can easily move back to the original buffer.
11254 (error (funcall save-position-maybe)
11255 (error (nth 1 err)))))))
11256 ((functionp cmd)
11257 (save-match-data
11258 (set-match-data link-match-data)
11259 (condition-case nil
11260 (funcall cmd file link)
11261 ;; FIXME: Remove this check when most default installations
11262 ;; of Emacs have at least Org 9.0.
11263 ((debug wrong-number-of-arguments wrong-type-argument
11264 invalid-function)
11265 (user-error "Please see Org News for version 9.0 about \
11266 `org-file-apps'--Lisp error: %S" cmd)))))
11267 ((consp cmd)
11268 ;; FIXME: Remove this check when most default installations of
11269 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11270 ;; fall back to `org-link-frame-setup' for an old usage of
11271 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11272 (user-error "Please see Org News for version 9.0 about \
11273 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11274 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11275 (funcall save-position-maybe)))
11277 (defun org-file-apps-entry-match-against-dlink-p (entry)
11278 "This function returns non-nil if `entry' uses a regular
11279 expression which should be matched against the whole link by
11280 org-open-file.
11282 It assumes that is the case when the entry uses a regular
11283 expression which has at least one grouping construct and the
11284 action is either a lisp form or a command string containing
11285 `%1', i.e. using at least one subexpression match as a
11286 parameter."
11287 (let ((selector (car entry))
11288 (action (cdr entry)))
11289 (if (stringp selector)
11290 (and (> (regexp-opt-depth selector) 0)
11291 (or (and (stringp action)
11292 (string-match "%[0-9]" action))
11293 (consp action)))
11294 nil)))
11296 (defun org-default-apps ()
11297 "Return the default applications for this operating system."
11298 (cond
11299 ((eq system-type 'darwin)
11300 org-file-apps-defaults-macosx)
11301 ((eq system-type 'windows-nt)
11302 org-file-apps-defaults-windowsnt)
11303 (t org-file-apps-defaults-gnu)))
11305 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11306 "Convert extensions to regular expressions in the cars of LIST.
11307 Also, weed out any non-string entries, because the return value is used
11308 only for regexp matching.
11309 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11310 point to the symbol `emacs', indicating that the file should
11311 be opened in Emacs."
11312 (append
11313 (delq nil
11314 (mapcar (lambda (x)
11315 (unless (not (stringp (car x)))
11316 (if (string-match "\\W" (car x))
11318 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11319 list))
11320 (when add-auto-mode
11321 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11323 (defvar ange-ftp-name-format)
11324 (defun org-file-remote-p (file)
11325 "Test whether FILE specifies a location on a remote system.
11326 Return non-nil if the location is indeed remote.
11328 For example, the filename \"/user@host:/foo\" specifies a location
11329 on the system \"/user@host:\"."
11330 (cond ((fboundp 'file-remote-p)
11331 (file-remote-p file))
11332 ((fboundp 'tramp-handle-file-remote-p)
11333 (tramp-handle-file-remote-p file))
11334 ((and (boundp 'ange-ftp-name-format)
11335 (string-match (car ange-ftp-name-format) file))
11336 t)))
11339 ;;;; Refiling
11341 (defun org-get-org-file ()
11342 "Read a filename, with default directory `org-directory'."
11343 (let ((default (or org-default-notes-file remember-data-file)))
11344 (read-file-name (format "File name [%s]: " default)
11345 (file-name-as-directory org-directory)
11346 default)))
11348 (defun org-notes-order-reversed-p ()
11349 "Check if the current file should receive notes in reversed order."
11350 (cond
11351 ((not org-reverse-note-order) nil)
11352 ((eq t org-reverse-note-order) t)
11353 ((not (listp org-reverse-note-order)) nil)
11354 (t (catch 'exit
11355 (dolist (entry org-reverse-note-order)
11356 (when (string-match (car entry) buffer-file-name)
11357 (throw 'exit (cdr entry))))))))
11359 (defvar org-refile-target-table nil
11360 "The list of refile targets, created by `org-refile'.")
11362 (defvar org-agenda-new-buffers nil
11363 "Buffers created to visit agenda files.")
11365 (defvar org-refile-cache nil
11366 "Cache for refile targets.")
11368 (defvar org-refile-markers nil
11369 "All the markers used for caching refile locations.")
11371 (defun org-refile-marker (pos)
11372 "Get a new refile marker, but only if caching is in use."
11373 (if (not org-refile-use-cache)
11375 (let ((m (make-marker)))
11376 (move-marker m pos)
11377 (push m org-refile-markers)
11378 m)))
11380 (defun org-refile-cache-clear ()
11381 "Clear the refile cache and disable all the markers."
11382 (dolist (m org-refile-markers) (move-marker m nil))
11383 (setq org-refile-markers nil)
11384 (setq org-refile-cache nil)
11385 (message "Refile cache has been cleared"))
11387 (defun org-refile-cache-check-set (set)
11388 "Check if all the markers in the cache still have live buffers."
11389 (let (marker)
11390 (catch 'exit
11391 (while (and set (setq marker (nth 3 (pop set))))
11392 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11393 (when (and marker (null (marker-buffer marker)))
11394 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11395 (sit-for 3)
11396 (throw 'exit nil)))
11397 t)))
11399 (defun org-refile-cache-put (set &rest identifiers)
11400 "Push the refile targets SET into the cache, under IDENTIFIERS."
11401 (let* ((key (sha1 (prin1-to-string identifiers)))
11402 (entry (assoc key org-refile-cache)))
11403 (if entry
11404 (setcdr entry set)
11405 (push (cons key set) org-refile-cache))))
11407 (defun org-refile-cache-get (&rest identifiers)
11408 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11409 (cond
11410 ((not org-refile-cache) nil)
11411 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11413 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11414 org-refile-cache))))
11415 (and set (org-refile-cache-check-set set) set)))))
11417 (defvar org-outline-path-cache nil
11418 "Alist between buffer positions and outline paths.
11419 It value is an alist (POSITION . PATH) where POSITION is the
11420 buffer position at the beginning of an entry and PATH is a list
11421 of strings describing the outline path for that entry, in reverse
11422 order.")
11424 (defun org-refile-get-targets (&optional default-buffer)
11425 "Produce a table with refile targets."
11426 (let ((case-fold-search nil)
11427 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11428 (entries (or org-refile-targets '((nil . (:level . 1)))))
11429 targets tgs files desc descre)
11430 (message "Getting targets...")
11431 (with-current-buffer (or default-buffer (current-buffer))
11432 (dolist (entry entries)
11433 (setq files (car entry) desc (cdr entry))
11434 (cond
11435 ((null files) (setq files (list (current-buffer))))
11436 ((eq files 'org-agenda-files)
11437 (setq files (org-agenda-files 'unrestricted)))
11438 ((and (symbolp files) (fboundp files))
11439 (setq files (funcall files)))
11440 ((and (symbolp files) (boundp files))
11441 (setq files (symbol-value files))))
11442 (when (stringp files) (setq files (list files)))
11443 (cond
11444 ((eq (car desc) :tag)
11445 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11446 ((eq (car desc) :todo)
11447 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11448 ((eq (car desc) :regexp)
11449 (setq descre (cdr desc)))
11450 ((eq (car desc) :level)
11451 (setq descre (concat "^\\*\\{" (number-to-string
11452 (if org-odd-levels-only
11453 (1- (* 2 (cdr desc)))
11454 (cdr desc)))
11455 "\\}[ \t]")))
11456 ((eq (car desc) :maxlevel)
11457 (setq descre (concat "^\\*\\{1," (number-to-string
11458 (if org-odd-levels-only
11459 (1- (* 2 (cdr desc)))
11460 (cdr desc)))
11461 "\\}[ \t]")))
11462 (t (error "Bad refiling target description %s" desc)))
11463 (dolist (f files)
11464 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11466 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11467 (progn
11468 (when (bufferp f)
11469 (setq f (buffer-file-name (buffer-base-buffer f))))
11470 (setq f (and f (expand-file-name f)))
11471 (when (eq org-refile-use-outline-path 'file)
11472 (push (list (file-name-nondirectory f) f nil nil) tgs))
11473 (when (eq org-refile-use-outline-path 'buffer-name)
11474 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11475 (when (eq org-refile-use-outline-path 'full-file-path)
11476 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11477 (org-with-wide-buffer
11478 (goto-char (point-min))
11479 (setq org-outline-path-cache nil)
11480 (while (re-search-forward descre nil t)
11481 (beginning-of-line)
11482 (let ((case-fold-search nil))
11483 (looking-at org-complex-heading-regexp))
11484 (let ((begin (point))
11485 (heading (match-string-no-properties 4)))
11486 (unless (or (and
11487 org-refile-target-verify-function
11488 (not
11489 (funcall org-refile-target-verify-function)))
11490 (not heading))
11491 (let ((re (format org-complex-heading-regexp-format
11492 (regexp-quote heading)))
11493 (target
11494 (if (not org-refile-use-outline-path) heading
11495 (mapconcat
11496 #'identity
11497 (append
11498 (pcase org-refile-use-outline-path
11499 (`file (list (file-name-nondirectory
11500 (buffer-file-name
11501 (buffer-base-buffer)))))
11502 (`full-file-path
11503 (list (buffer-file-name
11504 (buffer-base-buffer))))
11505 (`buffer-name
11506 (list (buffer-name
11507 (buffer-base-buffer))))
11508 (_ nil))
11509 (mapcar (lambda (s) (replace-regexp-in-string
11510 "/" "\\/" s nil t))
11511 (org-get-outline-path t t)))
11512 "/"))))
11513 (push (list target f re (org-refile-marker (point)))
11514 tgs)))
11515 (when (= (point) begin)
11516 ;; Verification function has not moved point.
11517 (end-of-line)))))))
11518 (when org-refile-use-cache
11519 (org-refile-cache-put tgs (buffer-file-name) descre))
11520 (setq targets (append tgs targets))))))
11521 (message "Getting targets...done")
11522 (delete-dups (nreverse targets))))
11524 (defun org--get-outline-path-1 (&optional use-cache)
11525 "Return outline path to current headline.
11527 Outline path is a list of strings, in reverse order. When
11528 optional argument USE-CACHE is non-nil, make use of a cache. See
11529 `org-get-outline-path' for details.
11531 Assume buffer is widened and point is on a headline."
11532 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11533 (let ((p (point))
11534 (heading (let ((case-fold-search nil))
11535 (looking-at org-complex-heading-regexp)
11536 (if (not (match-end 4)) ""
11537 ;; Remove statistics cookies.
11538 (org-trim
11539 (org-link-display-format
11540 (replace-regexp-in-string
11541 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11542 (match-string-no-properties 4))))))))
11543 (if (org-up-heading-safe)
11544 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11545 (when use-cache
11546 (push (cons p path) org-outline-path-cache))
11547 path)
11548 ;; This is a new root node. Since we assume we are moving
11549 ;; forward, we can drop previous cache so as to limit number
11550 ;; of associations there.
11551 (let ((path (list heading)))
11552 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11553 path)))))
11555 (defun org-get-outline-path (&optional with-self use-cache)
11556 "Return the outline path to the current entry.
11558 An outline path is a list of ancestors for current headline, as
11559 a list of strings. Statistics cookies are removed and links are
11560 replaced with their description, if any, or their path otherwise.
11562 When optional argument WITH-SELF is non-nil, the path also
11563 includes the current headline.
11565 When optional argument USE-CACHE is non-nil, cache outline paths
11566 between calls to this function so as to avoid backtracking. This
11567 argument is useful when planning to find more than one outline
11568 path in the same document. In that case, there are two
11569 conditions to satisfy:
11570 - `org-outline-path-cache' is set to nil before starting the
11571 process;
11572 - outline paths are computed by increasing buffer positions."
11573 (org-with-wide-buffer
11574 (and (or (and with-self (org-back-to-heading t))
11575 (org-up-heading-safe))
11576 (reverse (org--get-outline-path-1 use-cache)))))
11578 (defun org-format-outline-path (path &optional width prefix separator)
11579 "Format the outline path PATH for display.
11580 WIDTH is the maximum number of characters that is available.
11581 PREFIX is a prefix to be included in the returned string,
11582 such as the file name.
11583 SEPARATOR is inserted between the different parts of the path,
11584 the default is \"/\"."
11585 (setq width (or width 79))
11586 (setq path (delq nil path))
11587 (unless (> width 0)
11588 (user-error "Argument `width' must be positive"))
11589 (setq separator (or separator "/"))
11590 (let* ((org-odd-levels-only nil)
11591 (fpath (concat
11592 prefix (and prefix path separator)
11593 (mapconcat
11594 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11595 (cl-loop for head in path
11596 for n from 0
11597 collect (org-add-props
11598 head nil 'face
11599 (nth (% n org-n-level-faces) org-level-faces)))
11600 separator))))
11601 (when (> (length fpath) width)
11602 (if (< width 7)
11603 ;; It's unlikely that `width' will be this small, but don't
11604 ;; waste characters by adding ".." if it is.
11605 (setq fpath (substring fpath 0 width))
11606 (setf (substring fpath (- width 2)) "..")))
11607 fpath))
11609 (defun org-display-outline-path (&optional file current separator just-return-string)
11610 "Display the current outline path in the echo area.
11612 If FILE is non-nil, prepend the output with the file name.
11613 If CURRENT is non-nil, append the current heading to the output.
11614 SEPARATOR is passed through to `org-format-outline-path'. It separates
11615 the different parts of the path and defaults to \"/\".
11616 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11617 (interactive "P")
11618 (let* (case-fold-search
11619 (bfn (buffer-file-name (buffer-base-buffer)))
11620 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11621 res)
11622 (when current (setq path (append path
11623 (save-excursion
11624 (org-back-to-heading t)
11625 (when (looking-at org-complex-heading-regexp)
11626 (list (match-string 4)))))))
11627 (setq res
11628 (org-format-outline-path
11629 path
11630 (1- (frame-width))
11631 (and file bfn (concat (file-name-nondirectory bfn) separator))
11632 separator))
11633 (if just-return-string
11634 (org-no-properties res)
11635 (org-unlogged-message "%s" res))))
11637 (defvar org-refile-history nil
11638 "History for refiling operations.")
11640 (defvar org-after-refile-insert-hook nil
11641 "Hook run after `org-refile' has inserted its stuff at the new location.
11642 Note that this is still *before* the stuff will be removed from
11643 the *old* location.")
11645 (defvar org-capture-last-stored-marker)
11646 (defvar org-refile-keep nil
11647 "Non-nil means `org-refile' will copy instead of refile.")
11649 (defun org-copy ()
11650 "Like `org-refile', but copy."
11651 (interactive)
11652 (let ((org-refile-keep t))
11653 (funcall 'org-refile nil nil nil "Copy")))
11655 (defun org-refile (&optional arg default-buffer rfloc msg)
11656 "Move the entry or entries at point to another heading.
11658 The list of target headings is compiled using the information in
11659 `org-refile-targets', which see.
11661 At the target location, the entry is filed as a subitem of the
11662 target heading. Depending on `org-reverse-note-order', the new
11663 subitem will either be the first or the last subitem.
11665 If there is an active region, all entries in that region will be
11666 refiled. However, the region must fulfill the requirement that
11667 the first heading sets the top-level of the moved text.
11669 With a `\\[universal-argument]' ARG, the command will only visit the target \
11670 location
11671 and not actually move anything.
11673 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11674 location where the last
11675 refiling operation has put the subtree.
11677 With a numeric prefix argument of `2', refile to the running clock.
11679 With a numeric prefix argument of `3', emulate `org-refile-keep'
11680 being set to t and copy to the target location, don't move it.
11681 Beware that keeping refiled entries may result in duplicated ID
11682 properties.
11684 RFLOC can be a refile location obtained in a different way.
11686 MSG is a string to replace \"Refile\" in the default prompt with
11687 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11689 See also `org-refile-use-outline-path'.
11691 If you are using target caching (see `org-refile-use-cache'), you
11692 have to clear the target cache in order to find new targets.
11693 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11694 prefix argument (`C-u C-u C-u C-c C-w')."
11695 (interactive "P")
11696 (if (member arg '(0 (64)))
11697 (org-refile-cache-clear)
11698 (let* ((actionmsg (cond (msg msg)
11699 ((equal arg 3) "Refile (and keep)")
11700 (t "Refile")))
11701 (regionp (org-region-active-p))
11702 (region-start (and regionp (region-beginning)))
11703 (region-end (and regionp (region-end)))
11704 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11705 pos it nbuf file level reversed)
11706 (setq last-command nil)
11707 (when regionp
11708 (goto-char region-start)
11709 (or (bolp) (goto-char (point-at-bol)))
11710 (setq region-start (point))
11711 (unless (or (org-kill-is-subtree-p
11712 (buffer-substring region-start region-end))
11713 (prog1 org-refile-active-region-within-subtree
11714 (let ((s (point-at-eol)))
11715 (org-toggle-heading)
11716 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11717 (user-error "The region is not a (sequence of) subtree(s)")))
11718 (if (equal arg '(16))
11719 (org-refile-goto-last-stored)
11720 (when (or
11721 (and (equal arg 2)
11722 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11723 (prog1
11724 (setq it (list (or org-clock-heading "running clock")
11725 (buffer-file-name
11726 (marker-buffer org-clock-hd-marker))
11728 (marker-position org-clock-hd-marker)))
11729 (setq arg nil)))
11730 (setq it
11731 (or rfloc
11732 (let (heading-text)
11733 (save-excursion
11734 (unless (and arg (listp arg))
11735 (org-back-to-heading t)
11736 (setq heading-text
11737 (replace-regexp-in-string
11738 org-bracket-link-regexp
11739 "\\3"
11740 (or (nth 4 (org-heading-components))
11741 ""))))
11742 (org-refile-get-location
11743 (cond ((and arg (listp arg)) "Goto")
11744 (regionp (concat actionmsg " region to"))
11745 (t (concat actionmsg " subtree \""
11746 heading-text "\" to")))
11747 default-buffer
11748 (and (not (equal '(4) arg))
11749 org-refile-allow-creating-parent-nodes)))))))
11750 (setq file (nth 1 it)
11751 pos (nth 3 it))
11752 (when (and (not arg)
11754 (equal (buffer-file-name) file)
11755 (if regionp
11756 (and (>= pos region-start)
11757 (<= pos region-end))
11758 (and (>= pos (point))
11759 (< pos (save-excursion
11760 (org-end-of-subtree t t))))))
11761 (error "Cannot refile to position inside the tree or region"))
11762 (setq nbuf (or (find-buffer-visiting file)
11763 (find-file-noselect file)))
11764 (if (and arg (not (equal arg 3)))
11765 (progn
11766 (pop-to-buffer-same-window nbuf)
11767 (goto-char (cond (pos)
11768 ((org-notes-order-reversed-p) (point-min))
11769 (t (point-max))))
11770 (org-show-context 'org-goto))
11771 (if regionp
11772 (progn
11773 (org-kill-new (buffer-substring region-start region-end))
11774 (org-save-markers-in-region region-start region-end))
11775 (org-copy-subtree 1 nil t))
11776 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11777 (find-file-noselect file)))
11778 (setq reversed (org-notes-order-reversed-p))
11779 (org-with-wide-buffer
11780 (if pos
11781 (progn
11782 (goto-char pos)
11783 (setq level (org-get-valid-level (funcall outline-level) 1))
11784 (goto-char
11785 (if reversed
11786 (or (outline-next-heading) (point-max))
11787 (or (save-excursion (org-get-next-sibling))
11788 (org-end-of-subtree t t)
11789 (point-max)))))
11790 (setq level 1)
11791 (if (not reversed)
11792 (goto-char (point-max))
11793 (goto-char (point-min))
11794 (or (outline-next-heading) (goto-char (point-max)))))
11795 (unless (bolp) (newline))
11796 (org-paste-subtree level nil nil t)
11797 (when org-log-refile
11798 (org-add-log-setup 'refile nil nil org-log-refile)
11799 (unless (eq org-log-refile 'note)
11800 (save-excursion (org-add-log-note))))
11801 (and org-auto-align-tags
11802 (let ((org-loop-over-headlines-in-active-region nil))
11803 (org-set-tags nil t)))
11804 (let ((bookmark-name (plist-get org-bookmark-names-plist
11805 :last-refile)))
11806 (when bookmark-name
11807 (with-demoted-errors
11808 (bookmark-set bookmark-name))))
11809 ;; If we are refiling for capture, make sure that the
11810 ;; last-capture pointers point here
11811 (when (bound-and-true-p org-capture-is-refiling)
11812 (let ((bookmark-name (plist-get org-bookmark-names-plist
11813 :last-capture-marker)))
11814 (when bookmark-name
11815 (with-demoted-errors
11816 (bookmark-set bookmark-name))))
11817 (move-marker org-capture-last-stored-marker (point)))
11818 (when (fboundp 'deactivate-mark) (deactivate-mark))
11819 (run-hooks 'org-after-refile-insert-hook)))
11820 (unless org-refile-keep
11821 (if regionp
11822 (delete-region (point) (+ (point) (- region-end region-start)))
11823 (delete-region
11824 (and (org-back-to-heading t) (point))
11825 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11826 (when (featurep 'org-inlinetask)
11827 (org-inlinetask-remove-END-maybe))
11828 (setq org-markers-to-move nil)
11829 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11831 (defun org-refile-goto-last-stored ()
11832 "Go to the location where the last refile was stored."
11833 (interactive)
11834 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11835 (message "This is the location of the last refile"))
11837 (defun org-refile--get-location (refloc tbl)
11838 "When user refile to REFLOC, find the associated target in TBL.
11839 Also check `org-refile-target-table'."
11840 (car (delq
11842 (mapcar
11843 (lambda (r) (or (assoc r tbl)
11844 (assoc r org-refile-target-table)))
11845 (list (replace-regexp-in-string "/$" "" refloc)
11846 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11848 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11849 "Prompt the user for a refile location, using PROMPT.
11850 PROMPT should not be suffixed with a colon and a space, because
11851 this function appends the default value from
11852 `org-refile-history' automatically, if that is not empty."
11853 (let ((org-refile-targets org-refile-targets)
11854 (org-refile-use-outline-path org-refile-use-outline-path))
11855 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11856 (unless org-refile-target-table
11857 (user-error "No refile targets"))
11858 (let* ((cbuf (current-buffer))
11859 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11860 (cfunc (if (and org-refile-use-outline-path
11861 org-outline-path-complete-in-steps)
11862 #'org-olpath-completing-read
11863 #'completing-read))
11864 (extra (if org-refile-use-outline-path "/" ""))
11865 (cbnex (concat (buffer-name) extra))
11866 (filename (and cfn (expand-file-name cfn)))
11867 (tbl (mapcar
11868 (lambda (x)
11869 (if (and (not (member org-refile-use-outline-path
11870 '(file full-file-path)))
11871 (not (equal filename (nth 1 x))))
11872 (cons (concat (car x) extra " ("
11873 (file-name-nondirectory (nth 1 x)) ")")
11874 (cdr x))
11875 (cons (concat (car x) extra) (cdr x))))
11876 org-refile-target-table))
11877 (completion-ignore-case t)
11878 cdef
11879 (prompt (concat prompt
11880 (or (and (car org-refile-history)
11881 (concat " (default " (car org-refile-history) ")"))
11882 (and (assoc cbnex tbl) (setq cdef cbnex)
11883 (concat " (default " cbnex ")"))) ": "))
11884 pa answ parent-target child parent old-hist)
11885 (setq old-hist org-refile-history)
11886 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11887 nil 'org-refile-history (or cdef (car org-refile-history))))
11888 (if (setq pa (org-refile--get-location answ tbl))
11889 (progn
11890 (org-refile-check-position pa)
11891 (when (or (not org-refile-history)
11892 (not (eq old-hist org-refile-history))
11893 (not (equal (car pa) (car org-refile-history))))
11894 (setq org-refile-history
11895 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11896 org-refile-history
11897 (cdr org-refile-history))))
11898 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11899 (pop org-refile-history)))
11901 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11902 (progn
11903 (setq parent (match-string 1 answ)
11904 child (match-string 2 answ))
11905 (setq parent-target (org-refile--get-location parent tbl))
11906 (when (and parent-target
11907 (or (eq new-nodes t)
11908 (and (eq new-nodes 'confirm)
11909 (y-or-n-p (format "Create new node \"%s\"? "
11910 child)))))
11911 (org-refile-new-child parent-target child)))
11912 (user-error "Invalid target location")))))
11914 (declare-function org-string-nw-p "org-macs" (s))
11915 (defun org-refile-check-position (refile-pointer)
11916 "Check if the refile pointer matches the headline to which it points."
11917 (let* ((file (nth 1 refile-pointer))
11918 (re (nth 2 refile-pointer))
11919 (pos (nth 3 refile-pointer))
11920 buffer)
11921 (if (and (not (markerp pos)) (not file))
11922 (user-error "Please indicate a target file in the refile path")
11923 (when (org-string-nw-p re)
11924 (setq buffer (if (markerp pos)
11925 (marker-buffer pos)
11926 (or (find-buffer-visiting file)
11927 (find-file-noselect file))))
11928 (with-current-buffer buffer
11929 (org-with-wide-buffer
11930 (goto-char pos)
11931 (beginning-of-line 1)
11932 (unless (looking-at-p re)
11933 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11935 (defun org-refile-new-child (parent-target child)
11936 "Use refile target PARENT-TARGET to add new CHILD below it."
11937 (unless parent-target
11938 (error "Cannot find parent for new node"))
11939 (let ((file (nth 1 parent-target))
11940 (pos (nth 3 parent-target))
11941 level)
11942 (with-current-buffer (or (find-buffer-visiting file)
11943 (find-file-noselect file))
11944 (org-with-wide-buffer
11945 (if pos
11946 (goto-char pos)
11947 (goto-char (point-max))
11948 (unless (bolp) (newline)))
11949 (when (looking-at org-outline-regexp)
11950 (setq level (funcall outline-level))
11951 (org-end-of-subtree t t))
11952 (org-back-over-empty-lines)
11953 (insert "\n" (make-string
11954 (if pos (org-get-valid-level level 1) 1) ?*)
11955 " " child "\n")
11956 (beginning-of-line 0)
11957 (list (concat (car parent-target) "/" child) file "" (point))))))
11959 (defun org-olpath-completing-read (prompt collection &rest args)
11960 "Read an outline path like a file name."
11961 (let ((thetable collection))
11962 (apply #'completing-read
11963 prompt
11964 (lambda (string predicate &optional flag)
11965 (cond
11966 ((eq flag nil) (try-completion string thetable))
11967 ((eq flag t)
11968 (let ((l (length string)))
11969 (mapcar (lambda (x)
11970 (let ((r (substring x l))
11971 (f (if (string-match " ([^)]*)$" x)
11972 (match-string 0 x)
11973 "")))
11974 (if (string-match "/" r)
11975 (concat string (substring r 0 (match-end 0)) f)
11976 x)))
11977 (all-completions string thetable predicate))))
11978 ;; Exact match?
11979 ((eq flag 'lambda) (assoc string thetable))))
11980 args)))
11982 ;;;; Dynamic blocks
11984 (defun org-find-dblock (name)
11985 "Find the first dynamic block with name NAME in the buffer.
11986 If not found, stay at current position and return nil."
11987 (let ((case-fold-search t) pos)
11988 (save-excursion
11989 (goto-char (point-min))
11990 (setq pos (and (re-search-forward
11991 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11992 (match-beginning 0))))
11993 (when pos (goto-char pos))
11994 pos))
11996 (defun org-create-dblock (plist)
11997 "Create a dynamic block section, with parameters taken from PLIST.
11998 PLIST must contain a :name entry which is used as the name of the block."
11999 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12000 (end-of-line 1)
12001 (newline))
12002 (let ((col (current-column))
12003 (name (plist-get plist :name)))
12004 (insert "#+BEGIN: " name)
12005 (while plist
12006 (if (eq (car plist) :name)
12007 (setq plist (cddr plist))
12008 (insert " " (prin1-to-string (pop plist)))))
12009 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12010 (beginning-of-line -2)))
12012 (defun org-prepare-dblock ()
12013 "Prepare dynamic block for refresh.
12014 This empties the block, puts the cursor at the insert position and returns
12015 the property list including an extra property :name with the block name."
12016 (unless (looking-at org-dblock-start-re)
12017 (user-error "Not at a dynamic block"))
12018 (let* ((begdel (1+ (match-end 0)))
12019 (name (org-no-properties (match-string 1)))
12020 (params (append (list :name name)
12021 (read (concat "(" (match-string 3) ")")))))
12022 (save-excursion
12023 (beginning-of-line 1)
12024 (skip-chars-forward " \t")
12025 (setq params (plist-put params :indentation-column (current-column))))
12026 (unless (re-search-forward org-dblock-end-re nil t)
12027 (error "Dynamic block not terminated"))
12028 (setq params
12029 (append params
12030 (list :content (buffer-substring
12031 begdel (match-beginning 0)))))
12032 (delete-region begdel (match-beginning 0))
12033 (goto-char begdel)
12034 (open-line 1)
12035 params))
12037 (defun org-map-dblocks (&optional command)
12038 "Apply COMMAND to all dynamic blocks in the current buffer.
12039 If COMMAND is not given, use `org-update-dblock'."
12040 (let ((cmd (or command 'org-update-dblock)))
12041 (save-excursion
12042 (goto-char (point-min))
12043 (while (re-search-forward org-dblock-start-re nil t)
12044 (goto-char (match-beginning 0))
12045 (save-excursion
12046 (condition-case nil
12047 (funcall cmd)
12048 (error (message "Error during update of dynamic block"))))
12049 (unless (re-search-forward org-dblock-end-re nil t)
12050 (error "Dynamic block not terminated"))))))
12052 (defun org-dblock-update (&optional arg)
12053 "User command for updating dynamic blocks.
12054 Update the dynamic block at point. With prefix ARG, update all dynamic
12055 blocks in the buffer."
12056 (interactive "P")
12057 (if arg
12058 (org-update-all-dblocks)
12059 (or (looking-at org-dblock-start-re)
12060 (org-beginning-of-dblock))
12061 (org-update-dblock)))
12063 (defun org-update-dblock ()
12064 "Update the dynamic block at point.
12065 This means to empty the block, parse for parameters and then call
12066 the correct writing function."
12067 (interactive)
12068 (save-excursion
12069 (let* ((win (selected-window))
12070 (pos (point))
12071 (line (org-current-line))
12072 (params (org-prepare-dblock))
12073 (name (plist-get params :name))
12074 (indent (plist-get params :indentation-column))
12075 (cmd (intern (concat "org-dblock-write:" name))))
12076 (message "Updating dynamic block `%s' at line %d..." name line)
12077 (funcall cmd params)
12078 (message "Updating dynamic block `%s' at line %d...done" name line)
12079 (goto-char pos)
12080 (when (and indent (> indent 0))
12081 (setq indent (make-string indent ?\ ))
12082 (save-excursion
12083 (select-window win)
12084 (org-beginning-of-dblock)
12085 (forward-line 1)
12086 (while (not (looking-at org-dblock-end-re))
12087 (insert indent)
12088 (beginning-of-line 2))
12089 (when (looking-at org-dblock-end-re)
12090 (and (looking-at "[ \t]+")
12091 (replace-match ""))
12092 (insert indent)))))))
12094 (defun org-beginning-of-dblock ()
12095 "Find the beginning of the dynamic block at point.
12096 Error if there is no such block at point."
12097 (let ((pos (point))
12098 beg)
12099 (end-of-line 1)
12100 (if (and (re-search-backward org-dblock-start-re nil t)
12101 (setq beg (match-beginning 0))
12102 (re-search-forward org-dblock-end-re nil t)
12103 (> (match-end 0) pos))
12104 (goto-char beg)
12105 (goto-char pos)
12106 (error "Not in a dynamic block"))))
12108 (defun org-update-all-dblocks ()
12109 "Update all dynamic blocks in the buffer.
12110 This function can be used in a hook."
12111 (interactive)
12112 (when (derived-mode-p 'org-mode)
12113 (org-map-dblocks 'org-update-dblock)))
12116 ;;;; Completion
12118 (declare-function org-export-backend-options "ox" (cl-x) t)
12119 (defun org-get-export-keywords ()
12120 "Return a list of all currently understood export keywords.
12121 Export keywords include options, block names, attributes and
12122 keywords relative to each registered export back-end."
12123 (let (keywords)
12124 (dolist (backend
12125 (bound-and-true-p org-export-registered-backends)
12126 (delq nil keywords))
12127 ;; Back-end name (for keywords, like #+LATEX:)
12128 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12129 (dolist (option-entry (org-export-backend-options backend))
12130 ;; Back-end options.
12131 (push (nth 1 option-entry) keywords)))))
12133 (defconst org-options-keywords
12134 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12135 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12136 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12137 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12138 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12140 (defcustom org-structure-template-alist
12141 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12142 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12143 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12144 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12145 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12146 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12147 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12148 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12149 ("L" "#+LaTeX: ")
12150 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12151 ("H" "#+HTML: ")
12152 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12153 ("A" "#+ASCII: ")
12154 ("i" "#+INDEX: ?")
12155 ("I" "#+INCLUDE: %file ?"))
12156 "Structure completion elements.
12157 This is a list of abbreviation keys and values. The value gets inserted
12158 if you type `<' followed by the key and then press the completion key,
12159 usually `TAB'. %file will be replaced by a file name after prompting
12160 for the file using completion. The cursor will be placed at the position
12161 of the `?' in the template.
12162 There are two templates for each key, the first uses the original Org syntax,
12163 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12164 the default when the /org-mtags.el/ module has been loaded. See also the
12165 variable `org-mtags-prefer-muse-templates'."
12166 :group 'org-completion
12167 :type '(repeat
12168 (list
12169 (string :tag "Key")
12170 (string :tag "Template")))
12171 :version "26.1"
12172 :package-version '(Org . "8.3"))
12174 (defun org-try-structure-completion ()
12175 "Try to complete a structure template before point.
12176 This looks for strings like \"<e\" on an otherwise empty line and
12177 expands them."
12178 (let ((l (buffer-substring (point-at-bol) (point)))
12180 (when (and (looking-at "[ \t]*$")
12181 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12182 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12183 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12184 (match-beginning 1)) a)
12185 t)))
12187 (defun org-complete-expand-structure-template (start cell)
12188 "Expand a structure template."
12189 (let ((rpl (nth 1 cell))
12190 (ind ""))
12191 (delete-region start (point))
12192 (when (string-match "\\`[ \t]*#\\+" rpl)
12193 (cond
12194 ((bolp))
12195 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12196 (setq ind (buffer-substring (point-at-bol) (point))))
12197 (t (newline))))
12198 (setq start (point))
12199 (when (string-match "%file" rpl)
12200 (setq rpl (replace-match
12201 (concat
12202 "\""
12203 (save-match-data
12204 (abbreviate-file-name (read-file-name "Include file: ")))
12205 "\"")
12206 t t rpl)))
12207 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12208 (concat "\n" ind)))
12209 (insert rpl)
12210 (when (re-search-backward "\\?" start t) (delete-char 1))))
12212 ;;;; TODO, DEADLINE, Comments
12214 (defun org-toggle-comment ()
12215 "Change the COMMENT state of an entry."
12216 (interactive)
12217 (save-excursion
12218 (org-back-to-heading)
12219 (let ((case-fold-search nil))
12220 (looking-at org-complex-heading-regexp))
12221 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12222 (skip-chars-forward " \t")
12223 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12224 (if (org-in-commented-heading-p t)
12225 (delete-region (point)
12226 (progn (search-forward " " (line-end-position) 'move)
12227 (skip-chars-forward " \t")
12228 (point)))
12229 (insert org-comment-string)
12230 (unless (eolp) (insert " ")))))
12232 (defvar org-last-todo-state-is-todo nil
12233 "This is non-nil when the last TODO state change led to a TODO state.
12234 If the last change removed the TODO tag or switched to DONE, then
12235 this is nil.")
12237 (defvar org-setting-tags nil) ; dynamically skipped
12239 (defvar org-todo-setup-filter-hook nil
12240 "Hook for functions that pre-filter todo specs.
12241 Each function takes a todo spec and returns either nil or the spec
12242 transformed into canonical form." )
12244 (defvar org-todo-get-default-hook nil
12245 "Hook for functions that get a default item for todo.
12246 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12247 nil or a string to be used for the todo mark." )
12249 (defvar org-agenda-headline-snapshot-before-repeat)
12251 (defun org-current-effective-time ()
12252 "Return current time adjusted for `org-extend-today-until' variable."
12253 (let* ((ct (org-current-time))
12254 (dct (decode-time ct))
12255 (ct1
12256 (cond
12257 (org-use-last-clock-out-time-as-effective-time
12258 (or (org-clock-get-last-clock-out-time) ct))
12259 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12260 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12261 (t ct))))
12262 ct1))
12264 (defun org-todo-yesterday (&optional arg)
12265 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12266 (interactive "P")
12267 (if (eq major-mode 'org-agenda-mode)
12268 (apply 'org-agenda-todo-yesterday arg)
12269 (let* ((org-use-effective-time t)
12270 (hour (nth 2 (decode-time (org-current-time))))
12271 (org-extend-today-until (1+ hour)))
12272 (org-todo arg))))
12274 (defvar org-block-entry-blocking ""
12275 "First entry preventing the TODO state change.")
12277 (defun org-cancel-repeater ()
12278 "Cancel a repeater by setting its numeric value to zero."
12279 (interactive)
12280 (save-excursion
12281 (org-back-to-heading t)
12282 (let ((bound1 (point))
12283 (bound0 (save-excursion (outline-next-heading) (point))))
12284 (when (and (re-search-forward
12285 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12286 org-deadline-time-regexp "\\)\\|\\("
12287 org-ts-regexp "\\)")
12288 bound0 t)
12289 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12290 bound1 t))
12291 (replace-match "0" t nil nil 1)))))
12293 (defvar org-state)
12294 (defvar org-blocked-by-checkboxes)
12295 (defun org-todo (&optional arg)
12296 "Change the TODO state of an item.
12298 The state of an item is given by a keyword at the start of the heading,
12299 like
12300 *** TODO Write paper
12301 *** DONE Call mom
12303 The different keywords are specified in the variable `org-todo-keywords'.
12304 By default the available states are \"TODO\" and \"DONE\". So, for this
12305 example: when the item starts with TODO, it is changed to DONE.
12306 When it starts with DONE, the DONE is removed. And when neither TODO nor
12307 DONE are present, add TODO at the beginning of the heading.
12309 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12310 state.
12311 With numeric prefix ARG, switch to that state.
12312 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12313 next set of TODO \
12314 keywords (nextset).
12315 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12316 prefix, circumvent any state blocking.
12317 With a numeric prefix arg of 0, inhibit note taking for the change.
12318 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12320 When called through ELisp, arg is also interpreted in the following way:
12321 `none' -> empty state
12322 \"\" -> switch to empty state
12323 `done' -> switch to DONE
12324 `nextset' -> switch to the next set of keywords
12325 `previousset' -> switch to the previous set of keywords
12326 \"WAITING\" -> switch to the specified keyword, but only if it
12327 really is a member of `org-todo-keywords'."
12328 (interactive "P")
12329 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12330 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12331 'region-start-level 'region))
12332 org-loop-over-headlines-in-active-region)
12333 (org-map-entries
12334 `(org-todo ,arg)
12335 org-loop-over-headlines-in-active-region
12336 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12337 (when (equal arg '(16)) (setq arg 'nextset))
12338 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12339 (let ((org-blocker-hook org-blocker-hook)
12340 commentp
12341 case-fold-search)
12342 (when (equal arg '(64))
12343 (setq arg nil org-blocker-hook nil))
12344 (when (and org-blocker-hook
12345 (or org-inhibit-blocking
12346 (org-entry-get nil "NOBLOCKING")))
12347 (setq org-blocker-hook nil))
12348 (save-excursion
12349 (catch 'exit
12350 (org-back-to-heading t)
12351 (when (org-in-commented-heading-p t)
12352 (org-toggle-comment)
12353 (setq commentp t))
12354 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12355 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12356 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12357 (let* ((match-data (match-data))
12358 (startpos (point-at-bol))
12359 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12360 (org-log-done org-log-done)
12361 (org-log-repeat org-log-repeat)
12362 (org-todo-log-states org-todo-log-states)
12363 (org-inhibit-logging
12364 (if (equal arg 0)
12365 (progn (setq arg nil) 'note) org-inhibit-logging))
12366 (this (match-string 1))
12367 (hl-pos (match-beginning 0))
12368 (head (org-get-todo-sequence-head this))
12369 (ass (assoc head org-todo-kwd-alist))
12370 (interpret (nth 1 ass))
12371 (done-word (nth 3 ass))
12372 (final-done-word (nth 4 ass))
12373 (org-last-state (or this ""))
12374 (completion-ignore-case t)
12375 (member (member this org-todo-keywords-1))
12376 (tail (cdr member))
12377 (org-state (cond
12378 ((and org-todo-key-trigger
12379 (or (and (equal arg '(4))
12380 (eq org-use-fast-todo-selection 'prefix))
12381 (and (not arg) org-use-fast-todo-selection
12382 (not (eq org-use-fast-todo-selection
12383 'prefix)))))
12384 ;; Use fast selection.
12385 (org-fast-todo-selection))
12386 ((and (equal arg '(4))
12387 (or (not org-use-fast-todo-selection)
12388 (not org-todo-key-trigger)))
12389 ;; Read a state with completion.
12390 (completing-read
12391 "State: " (mapcar #'list org-todo-keywords-1)
12392 nil t))
12393 ((eq arg 'right)
12394 (if this
12395 (if tail (car tail) nil)
12396 (car org-todo-keywords-1)))
12397 ((eq arg 'left)
12398 (unless (equal member org-todo-keywords-1)
12399 (if this
12400 (nth (- (length org-todo-keywords-1)
12401 (length tail) 2)
12402 org-todo-keywords-1)
12403 (org-last org-todo-keywords-1))))
12404 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12405 (setq arg nil))) ;hack to fall back to cycling
12406 (arg
12407 ;; User or caller requests a specific state.
12408 (cond
12409 ((equal arg "") nil)
12410 ((eq arg 'none) nil)
12411 ((eq arg 'done) (or done-word (car org-done-keywords)))
12412 ((eq arg 'nextset)
12413 (or (car (cdr (member head org-todo-heads)))
12414 (car org-todo-heads)))
12415 ((eq arg 'previousset)
12416 (let ((org-todo-heads (reverse org-todo-heads)))
12417 (or (car (cdr (member head org-todo-heads)))
12418 (car org-todo-heads))))
12419 ((car (member arg org-todo-keywords-1)))
12420 ((stringp arg)
12421 (user-error "State `%s' not valid in this file" arg))
12422 ((nth (1- (prefix-numeric-value arg))
12423 org-todo-keywords-1))))
12424 ((null member) (or head (car org-todo-keywords-1)))
12425 ((equal this final-done-word) nil) ;-> make empty
12426 ((null tail) nil) ;-> first entry
12427 ((memq interpret '(type priority))
12428 (if (eq this-command last-command)
12429 (car tail)
12430 (if (> (length tail) 0)
12431 (or done-word (car org-done-keywords))
12432 nil)))
12434 (car tail))))
12435 (org-state (or
12436 (run-hook-with-args-until-success
12437 'org-todo-get-default-hook org-state org-last-state)
12438 org-state))
12439 (next (if org-state (concat " " org-state " ") " "))
12440 (change-plist (list :type 'todo-state-change :from this :to org-state
12441 :position startpos))
12442 dolog now-done-p)
12443 (when org-blocker-hook
12444 (let (org-blocked-by-checkboxes block-reason)
12445 (setq org-last-todo-state-is-todo
12446 (not (member this org-done-keywords)))
12447 (unless (save-excursion
12448 (save-match-data
12449 (org-with-wide-buffer
12450 (run-hook-with-args-until-failure
12451 'org-blocker-hook change-plist))))
12452 (setq block-reason (if org-blocked-by-checkboxes
12453 "contained checkboxes"
12454 (format "\"%s\"" org-block-entry-blocking)))
12455 (if (called-interactively-p 'interactive)
12456 (user-error "TODO state change from %s to %s blocked (by %s)"
12457 this org-state block-reason)
12458 ;; Fail silently.
12459 (message "TODO state change from %s to %s blocked (by %s)"
12460 this org-state block-reason)
12461 (throw 'exit nil)))))
12462 (store-match-data match-data)
12463 (replace-match next t t)
12464 (cond ((equal this org-state)
12465 (message "TODO state was already %s" (org-trim next)))
12466 ((not (pos-visible-in-window-p hl-pos))
12467 (message "TODO state changed to %s" (org-trim next))))
12468 (unless head
12469 (setq head (org-get-todo-sequence-head org-state)
12470 ass (assoc head org-todo-kwd-alist)
12471 interpret (nth 1 ass)
12472 done-word (nth 3 ass)
12473 final-done-word (nth 4 ass)))
12474 (when (memq arg '(nextset previousset))
12475 (message "Keyword-Set %d/%d: %s"
12476 (- (length org-todo-sets) -1
12477 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12478 (length org-todo-sets)
12479 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12480 (setq org-last-todo-state-is-todo
12481 (not (member org-state org-done-keywords)))
12482 (setq now-done-p (and (member org-state org-done-keywords)
12483 (not (member this org-done-keywords))))
12484 (and logging (org-local-logging logging))
12485 (when (and (or org-todo-log-states org-log-done)
12486 (not (eq org-inhibit-logging t))
12487 (not (memq arg '(nextset previousset))))
12488 ;; We need to look at recording a time and note.
12489 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12490 (nth 2 (assoc this org-todo-log-states))))
12491 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12492 (setq dolog 'time))
12493 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12494 (and org-state
12495 (member org-state org-not-done-keywords)
12496 (not (member this org-not-done-keywords))))
12497 ;; This is now a todo state and was not one before
12498 ;; If there was a CLOSED time stamp, get rid of it.
12499 (org-add-planning-info nil nil 'closed))
12500 (when (and now-done-p org-log-done)
12501 ;; It is now done, and it was not done before.
12502 (org-add-planning-info 'closed (org-current-effective-time))
12503 (when (and (not dolog) (eq 'note org-log-done))
12504 (org-add-log-setup 'done org-state this 'note)))
12505 (when (and org-state dolog)
12506 ;; This is a non-nil state, and we need to log it.
12507 (org-add-log-setup 'state org-state this dolog)))
12508 ;; Fixup tag positioning.
12509 (org-todo-trigger-tag-changes org-state)
12510 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12511 (when org-provide-todo-statistics
12512 (org-update-parent-todo-statistics))
12513 (run-hooks 'org-after-todo-state-change-hook)
12514 (when (and arg (not (member org-state org-done-keywords)))
12515 (setq head (org-get-todo-sequence-head org-state)))
12516 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12517 ;; Do we need to trigger a repeat?
12518 (when now-done-p
12519 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12520 ;; This is for the agenda, take a snapshot of the headline.
12521 (save-match-data
12522 (setq org-agenda-headline-snapshot-before-repeat
12523 (org-get-heading))))
12524 (org-auto-repeat-maybe org-state))
12525 ;; Fixup cursor location if close to the keyword.
12526 (when (and (outline-on-heading-p)
12527 (not (bolp))
12528 (save-excursion (beginning-of-line 1)
12529 (looking-at org-todo-line-regexp))
12530 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12531 (goto-char (or (match-end 2) (match-end 1)))
12532 (and (looking-at " ") (just-one-space)))
12533 (when org-trigger-hook
12534 (save-excursion
12535 (run-hook-with-args 'org-trigger-hook change-plist)))
12536 (when commentp (org-toggle-comment))))))))
12538 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12539 "Block turning an entry into a TODO, using the hierarchy.
12540 This checks whether the current task should be blocked from state
12541 changes. Such blocking occurs when:
12543 1. The task has children which are not all in a completed state.
12545 2. A task has a parent with the property :ORDERED:, and there
12546 are siblings prior to the current task with incomplete
12547 status.
12549 3. The parent of the task is blocked because it has siblings that should
12550 be done first, or is child of a block grandparent TODO entry."
12552 (if (not org-enforce-todo-dependencies)
12553 t ; if locally turned off don't block
12554 (catch 'dont-block
12555 ;; If this is not a todo state change, or if this entry is already DONE,
12556 ;; do not block
12557 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12558 (member (plist-get change-plist :from)
12559 (cons 'done org-done-keywords))
12560 (member (plist-get change-plist :to)
12561 (cons 'todo org-not-done-keywords))
12562 (not (plist-get change-plist :to)))
12563 (throw 'dont-block t))
12564 ;; If this task has children, and any are undone, it's blocked
12565 (save-excursion
12566 (org-back-to-heading t)
12567 (let ((this-level (funcall outline-level)))
12568 (outline-next-heading)
12569 (let ((child-level (funcall outline-level)))
12570 (while (and (not (eobp))
12571 (> child-level this-level))
12572 ;; this todo has children, check whether they are all
12573 ;; completed
12574 (when (and (not (org-entry-is-done-p))
12575 (org-entry-is-todo-p))
12576 (setq org-block-entry-blocking (org-get-heading))
12577 (throw 'dont-block nil))
12578 (outline-next-heading)
12579 (setq child-level (funcall outline-level))))))
12580 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12581 ;; any previous siblings are undone, it's blocked
12582 (save-excursion
12583 (org-back-to-heading t)
12584 (let* ((pos (point))
12585 (parent-pos (and (org-up-heading-safe) (point)))
12586 (case-fold-search nil))
12587 (unless parent-pos (throw 'dont-block t)) ; no parent
12588 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12589 (forward-line 1)
12590 (re-search-forward org-not-done-heading-regexp pos t))
12591 (setq org-block-entry-blocking (match-string 0))
12592 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12593 ;; Search further up the hierarchy, to see if an ancestor is blocked
12594 (while t
12595 (goto-char parent-pos)
12596 (unless (looking-at org-not-done-heading-regexp)
12597 (throw 'dont-block t)) ; do not block, parent is not a TODO
12598 (setq pos (point))
12599 (setq parent-pos (and (org-up-heading-safe) (point)))
12600 (unless parent-pos (throw 'dont-block t)) ; no parent
12601 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12602 (forward-line 1)
12603 (re-search-forward org-not-done-heading-regexp pos t)
12604 (setq org-block-entry-blocking (org-get-heading)))
12605 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12607 (defcustom org-track-ordered-property-with-tag nil
12608 "Should the ORDERED property also be shown as a tag?
12609 The ORDERED property decides if an entry should require subtasks to be
12610 completed in sequence. Since a property is not very visible, setting
12611 this option means that toggling the ORDERED property with the command
12612 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12613 not relevant for the behavior, but it makes things more visible.
12615 Note that toggling the tag with tags commands will not change the property
12616 and therefore not influence behavior!
12618 This can be t, meaning the tag ORDERED should be used, It can also be a
12619 string to select a different tag for this task."
12620 :group 'org-todo
12621 :type '(choice
12622 (const :tag "No tracking" nil)
12623 (const :tag "Track with ORDERED tag" t)
12624 (string :tag "Use other tag")))
12626 (defun org-toggle-ordered-property ()
12627 "Toggle the ORDERED property of the current entry.
12628 For better visibility, you can track the value of this property with a tag.
12629 See variable `org-track-ordered-property-with-tag'."
12630 (interactive)
12631 (let* ((t1 org-track-ordered-property-with-tag)
12632 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12633 (save-excursion
12634 (org-back-to-heading)
12635 (if (org-entry-get nil "ORDERED")
12636 (progn
12637 (org-delete-property "ORDERED")
12638 (and tag (org-toggle-tag tag 'off))
12639 (message "Subtasks can be completed in arbitrary order"))
12640 (org-entry-put nil "ORDERED" "t")
12641 (and tag (org-toggle-tag tag 'on))
12642 (message "Subtasks must be completed in sequence")))))
12644 (defun org-block-todo-from-checkboxes (change-plist)
12645 "Block turning an entry into a TODO, using checkboxes.
12646 This checks whether the current task should be blocked from state
12647 changes because there are unchecked boxes in this entry."
12648 (if (not org-enforce-todo-checkbox-dependencies)
12649 t ; if locally turned off don't block
12650 (catch 'dont-block
12651 ;; If this is not a todo state change, or if this entry is already DONE,
12652 ;; do not block
12653 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12654 (member (plist-get change-plist :from)
12655 (cons 'done org-done-keywords))
12656 (member (plist-get change-plist :to)
12657 (cons 'todo org-not-done-keywords))
12658 (not (plist-get change-plist :to)))
12659 (throw 'dont-block t))
12660 ;; If this task has checkboxes that are not checked, it's blocked
12661 (save-excursion
12662 (org-back-to-heading t)
12663 (let ((beg (point)) end)
12664 (outline-next-heading)
12665 (setq end (point))
12666 (goto-char beg)
12667 (when (org-list-search-forward
12668 (concat (org-item-beginning-re)
12669 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12670 "\\[[- ]\\]")
12671 end t)
12672 (when (boundp 'org-blocked-by-checkboxes)
12673 (setq org-blocked-by-checkboxes t))
12674 (throw 'dont-block nil))))
12675 t))) ; do not block
12677 (defun org-entry-blocked-p ()
12678 "Non-nil if entry at point is blocked."
12679 (and (not (org-entry-get nil "NOBLOCKING"))
12680 (member (org-entry-get nil "TODO") org-not-done-keywords)
12681 (not (run-hook-with-args-until-failure
12682 'org-blocker-hook
12683 (list :type 'todo-state-change
12684 :position (point)
12685 :from 'todo
12686 :to 'done)))))
12688 (defun org-update-statistics-cookies (all)
12689 "Update the statistics cookie, either from TODO or from checkboxes.
12690 This should be called with the cursor in a line with a statistics
12691 cookie. When called with a \\[universal-argument] prefix, update
12692 all statistics cookies in the buffer."
12693 (interactive "P")
12694 (if all
12695 (progn
12696 (org-update-checkbox-count 'all)
12697 (org-map-entries 'org-update-parent-todo-statistics))
12698 (if (not (org-at-heading-p))
12699 (org-update-checkbox-count)
12700 (let ((pos (point-marker))
12701 end l1 l2)
12702 (ignore-errors (org-back-to-heading t))
12703 (if (not (org-at-heading-p))
12704 (org-update-checkbox-count)
12705 (setq l1 (org-outline-level))
12706 (setq end (save-excursion
12707 (outline-next-heading)
12708 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12709 (point)))
12710 (if (and (save-excursion
12711 (re-search-forward
12712 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12713 (not (save-excursion (re-search-forward
12714 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12715 (org-update-checkbox-count)
12716 (if (and l2 (> l2 l1))
12717 (progn
12718 (goto-char end)
12719 (org-update-parent-todo-statistics))
12720 (goto-char pos)
12721 (beginning-of-line 1)
12722 (while (re-search-forward
12723 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12724 (point-at-eol) t)
12725 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12726 (goto-char pos)
12727 (move-marker pos nil)))))
12729 (defvar org-entry-property-inherited-from) ;; defined below
12730 (defun org-update-parent-todo-statistics ()
12731 "Update any statistics cookie in the parent of the current headline.
12732 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12733 the entire subtree and this will travel up the hierarchy and update
12734 statistics everywhere."
12735 (let* ((prop (save-excursion (org-up-heading-safe)
12736 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12737 (recursive (or (not org-hierarchical-todo-statistics)
12738 (and prop (string-match "\\<recursive\\>" prop))))
12739 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12741 (first t)
12742 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12743 level ltoggle l1 new ndel
12744 (cnt-all 0) (cnt-done 0) is-percent kwd
12745 checkbox-beg cookie-present)
12746 (catch 'exit
12747 (save-excursion
12748 (beginning-of-line 1)
12749 (setq ltoggle (funcall outline-level))
12750 ;; Three situations are to consider:
12752 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12753 ;; to the top-level ancestor on the headline;
12755 ;; 2. If parent has "recursive" property, repeat up to the
12756 ;; headline setting that property, taking inheritance into
12757 ;; account;
12759 ;; 3. Else, move up to direct parent and proceed only once.
12760 (while (and (setq level (org-up-heading-safe))
12761 (or recursive first)
12762 (>= (point) lim))
12763 (setq first nil cookie-present nil)
12764 (unless (and level
12765 (not (string-match
12766 "\\<checkbox\\>"
12767 (downcase (or (org-entry-get nil "COOKIE_DATA")
12768 "")))))
12769 (throw 'exit nil))
12770 (while (re-search-forward box-re (point-at-eol) t)
12771 (setq cnt-all 0 cnt-done 0 cookie-present t)
12772 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12773 (save-match-data
12774 (unless (outline-next-heading) (throw 'exit nil))
12775 (while (and (looking-at org-complex-heading-regexp)
12776 (> (setq l1 (length (match-string 1))) level))
12777 (setq kwd (and (or recursive (= l1 ltoggle))
12778 (match-string 2)))
12779 (if (or (eq org-provide-todo-statistics 'all-headlines)
12780 (and (eq org-provide-todo-statistics t)
12781 (or (member kwd org-done-keywords)))
12782 (and (listp org-provide-todo-statistics)
12783 (stringp (car org-provide-todo-statistics))
12784 (or (member kwd org-provide-todo-statistics)
12785 (member kwd org-done-keywords)))
12786 (and (listp org-provide-todo-statistics)
12787 (listp (car org-provide-todo-statistics))
12788 (or (member kwd (car org-provide-todo-statistics))
12789 (and (member kwd org-done-keywords)
12790 (member kwd (cadr org-provide-todo-statistics))))))
12791 (setq cnt-all (1+ cnt-all))
12792 (and (eq org-provide-todo-statistics t)
12794 (setq cnt-all (1+ cnt-all))))
12795 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12796 (member kwd org-done-keywords))
12797 (and (listp org-provide-todo-statistics)
12798 (listp (car org-provide-todo-statistics))
12799 (member kwd org-done-keywords)
12800 (member kwd (cadr org-provide-todo-statistics)))
12801 (and (listp org-provide-todo-statistics)
12802 (stringp (car org-provide-todo-statistics))
12803 (member kwd org-done-keywords)))
12804 (setq cnt-done (1+ cnt-done)))
12805 (outline-next-heading)))
12806 (setq new
12807 (if is-percent
12808 (format "[%d%%]" (floor (* 100.0 cnt-done)
12809 (max 1 cnt-all)))
12810 (format "[%d/%d]" cnt-done cnt-all))
12811 ndel (- (match-end 0) checkbox-beg))
12812 (goto-char checkbox-beg)
12813 (insert new)
12814 (delete-region (point) (+ (point) ndel))
12815 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12816 (when cookie-present
12817 (run-hook-with-args 'org-after-todo-statistics-hook
12818 cnt-done (- cnt-all cnt-done))))))
12819 (run-hooks 'org-todo-statistics-hook)))
12821 (defvar org-after-todo-statistics-hook nil
12822 "Hook that is called after a TODO statistics cookie has been updated.
12823 Each function is called with two arguments: the number of not-done entries
12824 and the number of done entries.
12826 For example, the following function, when added to this hook, will switch
12827 an entry to DONE when all children are done, and back to TODO when new
12828 entries are set to a TODO status. Note that this hook is only called
12829 when there is a statistics cookie in the headline!
12831 (defun org-summary-todo (n-done n-not-done)
12832 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12833 (let (org-log-done org-log-states) ; turn off logging
12834 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12837 (defvar org-todo-statistics-hook nil
12838 "Hook that is run whenever Org thinks TODO statistics should be updated.
12839 This hook runs even if there is no statistics cookie present, in which case
12840 `org-after-todo-statistics-hook' would not run.")
12842 (defun org-todo-trigger-tag-changes (state)
12843 "Apply the changes defined in `org-todo-state-tags-triggers'."
12844 (let ((l org-todo-state-tags-triggers)
12845 changes)
12846 (when (or (not state) (equal state ""))
12847 (setq changes (append changes (cdr (assoc "" l)))))
12848 (when (and (stringp state) (> (length state) 0))
12849 (setq changes (append changes (cdr (assoc state l)))))
12850 (when (member state org-not-done-keywords)
12851 (setq changes (append changes (cdr (assq 'todo l)))))
12852 (when (member state org-done-keywords)
12853 (setq changes (append changes (cdr (assq 'done l)))))
12854 (dolist (c changes)
12855 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12857 (defun org-local-logging (value)
12858 "Get logging settings from a property VALUE."
12859 ;; Directly set the variables, they are already local.
12860 (setq org-log-done nil
12861 org-log-repeat nil
12862 org-todo-log-states nil)
12863 (dolist (w (split-string value))
12864 (let (a)
12865 (cond
12866 ((setq a (assoc w org-startup-options))
12867 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12868 (set (nth 1 a) (nth 2 a))))
12869 ((setq a (org-extract-log-state-settings w))
12870 (and (member (car a) org-todo-keywords-1)
12871 (push a org-todo-log-states)))))))
12873 (defun org-get-todo-sequence-head (kwd)
12874 "Return the head of the TODO sequence to which KWD belongs.
12875 If KWD is not set, check if there is a text property remembering the
12876 right sequence."
12877 (let (p)
12878 (cond
12879 ((not kwd)
12880 (or (get-text-property (point-at-bol) 'org-todo-head)
12881 (progn
12882 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12883 nil (point-at-eol)))
12884 (get-text-property p 'org-todo-head))))
12885 ((not (member kwd org-todo-keywords-1))
12886 (car org-todo-keywords-1))
12887 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12889 (defun org-fast-todo-selection ()
12890 "Fast TODO keyword selection with single keys.
12891 Returns the new TODO keyword, or nil if no state change should occur."
12892 (let* ((fulltable org-todo-key-alist)
12893 (done-keywords org-done-keywords) ;; needed for the faces.
12894 (maxlen (apply 'max (mapcar
12895 (lambda (x)
12896 (if (stringp (car x)) (string-width (car x)) 0))
12897 fulltable)))
12898 (expert nil)
12899 (fwidth (+ maxlen 3 1 3))
12900 (ncol (/ (- (window-width) 4) fwidth))
12901 tg cnt e c tbl
12902 groups ingroup)
12903 (save-excursion
12904 (save-window-excursion
12905 (if expert
12906 (set-buffer (get-buffer-create " *Org todo*"))
12907 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12908 (erase-buffer)
12909 (setq-local org-done-keywords done-keywords)
12910 (setq tbl fulltable cnt 0)
12911 (while (setq e (pop tbl))
12912 (cond
12913 ((equal e '(:startgroup))
12914 (push '() groups) (setq ingroup t)
12915 (unless (= cnt 0)
12916 (setq cnt 0)
12917 (insert "\n"))
12918 (insert "{ "))
12919 ((equal e '(:endgroup))
12920 (setq ingroup nil cnt 0)
12921 (insert "}\n"))
12922 ((equal e '(:newline))
12923 (unless (= cnt 0)
12924 (setq cnt 0)
12925 (insert "\n")
12926 (setq e (car tbl))
12927 (while (equal (car tbl) '(:newline))
12928 (insert "\n")
12929 (setq tbl (cdr tbl)))))
12931 (setq tg (car e) c (cdr e))
12932 (when ingroup (push tg (car groups)))
12933 (setq tg (org-add-props tg nil 'face
12934 (org-get-todo-face tg)))
12935 (when (and (= cnt 0) (not ingroup)) (insert " "))
12936 (insert "[" c "] " tg (make-string
12937 (- fwidth 4 (length tg)) ?\ ))
12938 (when (= (setq cnt (1+ cnt)) ncol)
12939 (insert "\n")
12940 (when ingroup (insert " "))
12941 (setq cnt 0)))))
12942 (insert "\n")
12943 (goto-char (point-min))
12944 (unless expert (org-fit-window-to-buffer))
12945 (message "[a-z..]:Set [SPC]:clear")
12946 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12947 (cond
12948 ((or (= c ?\C-g)
12949 (and (= c ?q) (not (rassoc c fulltable))))
12950 (setq quit-flag t))
12951 ((= c ?\ ) nil)
12952 ((setq e (rassoc c fulltable) tg (car e))
12954 (t (setq quit-flag t)))))))
12956 (defun org-entry-is-todo-p ()
12957 (member (org-get-todo-state) org-not-done-keywords))
12959 (defun org-entry-is-done-p ()
12960 (member (org-get-todo-state) org-done-keywords))
12962 (defun org-get-todo-state ()
12963 "Return the TODO keyword of the current subtree."
12964 (save-excursion
12965 (org-back-to-heading t)
12966 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12967 (match-end 2)
12968 (match-string 2))))
12970 (defun org-at-date-range-p (&optional inactive-ok)
12971 "Non-nil if point is inside a date range.
12973 When optional argument INACTIVE-OK is non-nil, also consider
12974 inactive time ranges.
12976 When this function returns a non-nil value, match data is set
12977 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12978 on INACTIVE-OK."
12979 (interactive)
12980 (save-excursion
12981 (catch 'exit
12982 (let ((pos (point)))
12983 (skip-chars-backward "^[<\r\n")
12984 (skip-chars-backward "<[")
12985 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12986 (>= (match-end 0) pos)
12987 (throw 'exit t))
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 nil)))
12995 (defun org-get-repeat (&optional timestamp)
12996 "Check if there is a time-stamp with repeater in this entry.
12998 Return the repeater, as a string, or nil. Also return nil when
12999 this function is called before first heading.
13001 When optional argument TIMESTAMP is a string, extract the
13002 repeater from there instead."
13003 (save-match-data
13004 (cond (timestamp
13005 (and (string-match org-repeat-re timestamp)
13006 (match-string-no-properties 1 timestamp)))
13007 ((org-before-first-heading-p) nil)
13009 (save-excursion
13010 (org-back-to-heading t)
13011 (let ((end (org-entry-end-position)))
13012 (catch :repeat
13013 (while (re-search-forward org-repeat-re end t)
13014 (when (save-match-data (org-at-timestamp-p 'agenda))
13015 (throw :repeat (match-string-no-properties 1)))))))))))
13017 (defvar org-last-changed-timestamp)
13018 (defvar org-last-inserted-timestamp)
13019 (defvar org-log-post-message)
13020 (defvar org-log-note-purpose)
13021 (defvar org-log-note-how nil)
13022 (defvar org-log-note-extra)
13023 (defun org-auto-repeat-maybe (done-word)
13024 "Check if the current headline contains a repeated time-stamp.
13026 If yes, set TODO state back to what it was and change the base date
13027 of repeating deadline/scheduled time stamps to new date.
13029 This function is run automatically after each state change to a DONE state."
13030 (let* ((repeat (org-get-repeat))
13031 (aa (assoc org-last-state org-todo-kwd-alist))
13032 (interpret (nth 1 aa))
13033 (head (nth 2 aa))
13034 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13035 (msg "Entry repeats: ")
13036 (org-log-done nil)
13037 (org-todo-log-states nil)
13038 (end (copy-marker (org-entry-end-position))))
13039 (unwind-protect
13040 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13041 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13042 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13043 org-todo-repeat-to-state)))
13044 (org-todo (cond
13045 ((and to-state (member to-state org-todo-keywords-1))
13046 to-state)
13047 ((eq interpret 'type) org-last-state)
13048 (head)
13049 (t 'none))))
13050 (org-back-to-heading t)
13051 (org-add-planning-info nil nil 'closed)
13052 ;; When `org-log-repeat' is non-nil or entry contains
13053 ;; a clock, set LAST_REPEAT property.
13054 (when (or org-log-repeat
13055 (catch :clock
13056 (save-excursion
13057 (while (re-search-forward org-clock-line-re end t)
13058 (when (org-at-clock-log-p) (throw :clock t))))))
13059 (org-entry-put nil "LAST_REPEAT" (format-time-string
13060 (org-time-stamp-format t t)
13061 (current-time))))
13062 (when org-log-repeat
13063 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13064 (memq 'org-add-log-note post-command-hook))
13065 ;; We are already setup for some record.
13066 (when (eq org-log-repeat 'note)
13067 ;; Make sure we take a note, not only a time stamp.
13068 (setq org-log-note-how 'note))
13069 ;; Set up for taking a record.
13070 (org-add-log-setup 'state
13071 (or done-word (car org-done-keywords))
13072 org-last-state
13073 org-log-repeat)))
13074 (let ((planning-re (regexp-opt
13075 (list org-scheduled-string org-deadline-string))))
13076 (while (re-search-forward org-ts-regexp end t)
13077 (let* ((ts (match-string 0))
13078 (planning? (org-at-planning-p))
13079 (type (if (not planning?) "Plain:"
13080 (save-excursion
13081 (re-search-backward
13082 planning-re (line-beginning-position) t)
13083 (match-string 0)))))
13084 (cond
13085 ;; Ignore fake time-stamps (e.g., within comments).
13086 ((not (org-at-timestamp-p 'agenda)))
13087 ;; Time-stamps without a repeater are usually
13088 ;; skipped. However, a SCHEDULED time-stamp without
13089 ;; one is removed, as they are no longer relevant.
13090 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13091 ts))
13092 (when (equal type org-scheduled-string)
13093 (org-remove-timestamp-with-keyword type)))
13095 (let ((n (string-to-number (match-string 2 ts)))
13096 (what (match-string 3 ts)))
13097 (when (equal what "w") (setq n (* n 7) what "d"))
13098 (when (and (equal what "h")
13099 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13100 ts)))
13101 (user-error
13102 "Cannot repeat in Repeat in %d hour(s) because no hour \
13103 has been set"
13105 ;; Preparation, see if we need to modify the start
13106 ;; date for the change.
13107 (when (match-end 1)
13108 (let ((time (save-match-data
13109 (org-time-string-to-time ts))))
13110 (cond
13111 ((equal (match-string 1 ts) ".")
13112 ;; Shift starting date to today
13113 (org-timestamp-change
13114 (- (org-today) (time-to-days time))
13115 'day))
13116 ((equal (match-string 1 ts) "+")
13117 (let ((nshiftmax 10)
13118 (nshift 0))
13119 (while (or (= nshift 0)
13120 (not (time-less-p (current-time) time)))
13121 (when (= (cl-incf nshift) nshiftmax)
13122 (or (y-or-n-p
13123 (format "%d repeater intervals were not \
13124 enough to shift date past today. Continue? "
13125 nshift))
13126 (user-error "Abort")))
13127 (org-timestamp-change n (cdr (assoc what whata)))
13128 (org-in-regexp org-ts-regexp3)
13129 (setq ts (match-string 1))
13130 (setq time
13131 (save-match-data
13132 (org-time-string-to-time ts)))))
13133 (org-timestamp-change (- n) (cdr (assoc what whata)))
13134 ;; Rematch, so that we have everything in place
13135 ;; for the real shift.
13136 (org-in-regexp org-ts-regexp3)
13137 (setq ts (match-string 1))
13138 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13139 ts)))))
13140 (save-excursion
13141 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13142 (setq msg
13143 (concat
13144 msg type " " org-last-changed-timestamp " "))))))))
13145 (setq org-log-post-message msg)
13146 (message "%s" msg))
13147 (set-marker end nil))))
13149 (defun org-show-todo-tree (arg)
13150 "Make a compact tree which shows all headlines marked with TODO.
13151 The tree will show the lines where the regexp matches, and all higher
13152 headlines above the match.
13153 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13154 With a numeric prefix N, construct a sparse tree for the Nth element
13155 of `org-todo-keywords-1'."
13156 (interactive "P")
13157 (let ((case-fold-search nil)
13158 (kwd-re
13159 (cond ((null arg) org-not-done-regexp)
13160 ((equal arg '(4))
13161 (let ((kwd
13162 (completing-read "Keyword (or KWD1|KWD2|...): "
13163 (mapcar #'list org-todo-keywords-1))))
13164 (concat "\\("
13165 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13166 "\\)\\>")))
13167 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13168 (regexp-quote (nth (1- (prefix-numeric-value arg))
13169 org-todo-keywords-1)))
13170 (t (user-error "Invalid prefix argument: %s" arg)))))
13171 (message "%d TODO entries found"
13172 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13174 (defun org--deadline-or-schedule (arg type time)
13175 "Insert DEADLINE or SCHEDULE information in current entry.
13176 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13177 `org-schedule' for information about ARG and TIME arguments."
13178 (let* ((deadline? (eq type 'deadline))
13179 (keyword (if deadline? org-deadline-string org-scheduled-string))
13180 (log (if deadline? org-log-redeadline org-log-reschedule))
13181 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13182 (old-date-time (and old-date (org-time-string-to-time old-date)))
13183 ;; Save repeater cookie from either TIME or current scheduled
13184 ;; time stamp. We are going to insert it back at the end of
13185 ;; the process.
13186 (repeater (or (and (org-string-nw-p time)
13187 ;; We use `org-repeat-re' because we need
13188 ;; to tell the difference between a real
13189 ;; repeater and a time delta, e.g. "+2d".
13190 (string-match org-repeat-re time)
13191 (match-string 1 time))
13192 (and (org-string-nw-p old-date)
13193 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13194 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13195 old-date)
13196 (match-string 1 old-date)))))
13197 (pcase arg
13198 (`(4)
13199 (when (and old-date log)
13200 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13201 nil old-date log))
13202 (org-remove-timestamp-with-keyword keyword)
13203 (message (if deadline? "Item no longer has a deadline."
13204 "Item is no longer scheduled.")))
13205 (`(16)
13206 (save-excursion
13207 (org-back-to-heading t)
13208 (let ((regexp (if deadline? org-deadline-time-regexp
13209 org-scheduled-time-regexp)))
13210 (if (not (re-search-forward regexp (line-end-position 2) t))
13211 (user-error (if deadline? "No deadline information to update"
13212 "No scheduled information to update"))
13213 (let* ((rpl0 (match-string 1))
13214 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13215 (msg (if deadline? "Warn starting from" "Delay until")))
13216 (replace-match
13217 (concat keyword
13218 " <" rpl
13219 (format " -%dd"
13220 (abs (- (time-to-days
13221 (save-match-data
13222 (org-read-date
13223 nil t nil msg old-date-time)))
13224 (time-to-days old-date-time))))
13225 ">") t t))))))
13227 (org-add-planning-info type time 'closed)
13228 (when (and old-date
13230 (not (equal old-date org-last-inserted-timestamp)))
13231 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13232 org-last-inserted-timestamp
13233 old-date
13234 log))
13235 (when repeater
13236 (save-excursion
13237 (org-back-to-heading t)
13238 (when (re-search-forward
13239 (concat keyword " " org-last-inserted-timestamp)
13240 (line-end-position 2)
13242 (goto-char (1- (match-end 0)))
13243 (insert " " repeater)
13244 (setq org-last-inserted-timestamp
13245 (concat (substring org-last-inserted-timestamp 0 -1)
13246 " " repeater
13247 (substring org-last-inserted-timestamp -1))))))
13248 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13249 org-last-inserted-timestamp)))))
13251 (defun org-deadline (arg &optional time)
13252 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13253 With one universal prefix argument, remove any deadline from the item.
13254 With two universal prefix arguments, prompt for a warning delay.
13255 With argument TIME, set the deadline at the corresponding date. TIME
13256 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13257 (interactive "P")
13258 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13259 (org-map-entries
13260 (lambda () (org--deadline-or-schedule arg 'deadline time))
13262 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13263 'region-start-level
13264 'region)
13265 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13266 (org--deadline-or-schedule arg 'deadline time)))
13268 (defun org-schedule (arg &optional time)
13269 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13270 With one universal prefix argument, remove any scheduling date from the item.
13271 With two universal prefix arguments, prompt for a delay cookie.
13272 With argument TIME, scheduled at the corresponding date. TIME can
13273 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13274 (interactive "P")
13275 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13276 (org-map-entries
13277 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13279 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13280 'region-start-level
13281 'region)
13282 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13283 (org--deadline-or-schedule arg 'scheduled time)))
13285 (defun org-get-scheduled-time (pom &optional inherit)
13286 "Get the scheduled time as a time tuple, of a format suitable
13287 for calling org-schedule with, or if there is no scheduling,
13288 returns nil."
13289 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13290 (when time
13291 (apply 'encode-time (org-parse-time-string time)))))
13293 (defun org-get-deadline-time (pom &optional inherit)
13294 "Get the deadline as a time tuple, of a format suitable for
13295 calling org-deadline with, or if there is no scheduling, returns
13296 nil."
13297 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13298 (when time
13299 (apply 'encode-time (org-parse-time-string time)))))
13301 (defun org-remove-timestamp-with-keyword (keyword)
13302 "Remove all time stamps with KEYWORD in the current entry."
13303 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13304 beg)
13305 (save-excursion
13306 (org-back-to-heading t)
13307 (setq beg (point))
13308 (outline-next-heading)
13309 (while (re-search-backward re beg t)
13310 (replace-match "")
13311 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13312 (equal (char-before) ?\ ))
13313 (backward-delete-char 1)
13314 (when (string-match "^[ \t]*$" (buffer-substring
13315 (point-at-bol) (point-at-eol)))
13316 (delete-region (point-at-bol)
13317 (min (point-max) (1+ (point-at-eol))))))))))
13319 (defvar org-time-was-given) ; dynamically scoped parameter
13320 (defvar org-end-time-was-given) ; dynamically scoped parameter
13322 (defun org-at-planning-p ()
13323 "Non-nil when point is on a planning info line."
13324 ;; This is as accurate and faster than `org-element-at-point' since
13325 ;; planning info location is fixed in the section.
13326 (org-with-wide-buffer
13327 (beginning-of-line)
13328 (and (looking-at-p org-planning-line-re)
13329 (eq (point)
13330 (ignore-errors
13331 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13332 (org-back-to-heading t)
13333 (org-with-limited-levels (org-back-to-heading t)))
13334 (line-beginning-position 2))))))
13336 (defun org-add-planning-info (what &optional time &rest remove)
13337 "Insert new timestamp with keyword in the planning line.
13338 WHAT indicates what kind of time stamp to add. It is a symbol
13339 among `closed', `deadline', `scheduled' and nil. TIME indicates
13340 the time to use. If none is given, the user is prompted for
13341 a date. REMOVE indicates what kind of entries to remove. An old
13342 WHAT entry will also be removed."
13343 (let (org-time-was-given org-end-time-was-given default-time default-input)
13344 (catch 'exit
13345 (when (and (memq what '(scheduled deadline))
13346 (or (not time)
13347 (and (stringp time)
13348 (string-match "^[-+]+[0-9]" time))))
13349 ;; Try to get a default date/time from existing timestamp
13350 (save-excursion
13351 (org-back-to-heading t)
13352 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13353 (when (re-search-forward (if (eq what 'scheduled)
13354 org-scheduled-time-regexp
13355 org-deadline-time-regexp)
13356 end t)
13357 (setq ts (match-string 1)
13358 default-time (apply 'encode-time (org-parse-time-string ts))
13359 default-input (and ts (org-get-compact-tod ts)))))))
13360 (when what
13361 (setq time
13362 (if (stringp time)
13363 ;; This is a string (relative or absolute), set
13364 ;; proper date.
13365 (apply #'encode-time
13366 (org-read-date-analyze
13367 time default-time (decode-time default-time)))
13368 ;; If necessary, get the time from the user
13369 (or time (org-read-date nil 'to-time nil nil
13370 default-time default-input)))))
13372 (org-with-wide-buffer
13373 (org-back-to-heading t)
13374 (forward-line)
13375 (unless (bolp) (insert "\n"))
13376 (cond ((looking-at-p org-planning-line-re)
13377 ;; Move to current indentation.
13378 (skip-chars-forward " \t")
13379 ;; Check if we have to remove something.
13380 (dolist (type (if what (cons what remove) remove))
13381 (save-excursion
13382 (when (re-search-forward
13383 (cl-case type
13384 (closed org-closed-time-regexp)
13385 (deadline org-deadline-time-regexp)
13386 (scheduled org-scheduled-time-regexp)
13387 (otherwise
13388 (error "Invalid planning type: %s" type)))
13389 (line-end-position) t)
13390 ;; Delete until next keyword or end of line.
13391 (delete-region
13392 (match-beginning 0)
13393 (if (re-search-forward org-keyword-time-not-clock-regexp
13394 (line-end-position)
13396 (match-beginning 0)
13397 (line-end-position))))))
13398 ;; If there is nothing more to add and no more keyword
13399 ;; is left, remove the line completely.
13400 (if (and (looking-at-p "[ \t]*$") (not what))
13401 (delete-region (line-beginning-position)
13402 (line-beginning-position 2))
13403 ;; If we removed last keyword, do not leave trailing
13404 ;; white space at the end of line.
13405 (let ((p (point)))
13406 (save-excursion
13407 (end-of-line)
13408 (unless (= (skip-chars-backward " \t" p) 0)
13409 (delete-region (point) (line-end-position)))))))
13410 ((not what) (throw 'exit nil)) ; Nothing to do.
13411 (t (insert-before-markers "\n")
13412 (backward-char 1)
13413 (when org-adapt-indentation
13414 (indent-to-column (1+ (org-outline-level))))))
13415 (when what
13416 ;; Insert planning keyword.
13417 (insert (cl-case what
13418 (closed org-closed-string)
13419 (deadline org-deadline-string)
13420 (scheduled org-scheduled-string)
13421 (otherwise (error "Invalid planning type: %s" what)))
13422 " ")
13423 ;; Insert associated timestamp.
13424 (let ((ts (org-insert-time-stamp
13425 time
13426 (or org-time-was-given
13427 (and (eq what 'closed) org-log-done-with-time))
13428 (eq what 'closed)
13429 nil nil (list org-end-time-was-given))))
13430 (unless (eolp) (insert " "))
13431 ts))))))
13433 (defvar org-log-note-marker (make-marker)
13434 "Marker pointing at the entry where the note is to be inserted.")
13435 (defvar org-log-note-purpose nil)
13436 (defvar org-log-note-state nil)
13437 (defvar org-log-note-previous-state nil)
13438 (defvar org-log-note-extra nil)
13439 (defvar org-log-note-window-configuration nil)
13440 (defvar org-log-note-return-to (make-marker))
13441 (defvar org-log-note-effective-time nil
13442 "Remembered current time so that dynamically scoped
13443 `org-extend-today-until' affects timestamps in state change log")
13445 (defvar org-log-post-message nil
13446 "Message to be displayed after a log note has been stored.
13447 The auto-repeater uses this.")
13449 (defun org-add-note ()
13450 "Add a note to the current entry.
13451 This is done in the same way as adding a state change note."
13452 (interactive)
13453 (org-add-log-setup 'note))
13455 (defun org-log-beginning (&optional create)
13456 "Return expected start of log notes in current entry.
13457 When optional argument CREATE is non-nil, the function creates
13458 a drawer to store notes, if necessary. Returned position ignores
13459 narrowing."
13460 (org-with-wide-buffer
13461 (let ((drawer (org-log-into-drawer)))
13462 (cond
13463 (drawer
13464 (org-end-of-meta-data)
13465 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13466 (end (if (org-at-heading-p) (point)
13467 (save-excursion (outline-next-heading) (point))))
13468 (case-fold-search t))
13469 (catch 'exit
13470 ;; Try to find existing drawer.
13471 (while (re-search-forward regexp end t)
13472 (let ((element (org-element-at-point)))
13473 (when (eq (org-element-type element) 'drawer)
13474 (let ((cend (org-element-property :contents-end element)))
13475 (when (and (not org-log-states-order-reversed) cend)
13476 (goto-char cend)))
13477 (throw 'exit nil))))
13478 ;; No drawer found. Create one, if permitted.
13479 (when create
13480 (unless (bolp) (insert "\n"))
13481 (let ((beg (point)))
13482 (insert ":" drawer ":\n:END:\n")
13483 (org-indent-region beg (point)))
13484 (end-of-line -1)))))
13486 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13487 (skip-chars-forward " \t\n")
13488 (beginning-of-line)
13489 (unless org-log-states-order-reversed
13490 (org-skip-over-state-notes)
13491 (skip-chars-backward " \t\n")
13492 (forward-line)))))
13493 (if (bolp) (point) (line-beginning-position 2))))
13495 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13496 "Set up the post command hook to take a note.
13497 If this is about to TODO state change, the new state is expected in STATE.
13498 HOW is an indicator what kind of note should be created.
13499 EXTRA is additional text that will be inserted into the notes buffer."
13500 (move-marker org-log-note-marker (point))
13501 (setq org-log-note-purpose purpose
13502 org-log-note-state state
13503 org-log-note-previous-state prev-state
13504 org-log-note-how how
13505 org-log-note-extra extra
13506 org-log-note-effective-time (org-current-effective-time))
13507 (add-hook 'post-command-hook 'org-add-log-note 'append))
13509 (defun org-skip-over-state-notes ()
13510 "Skip past the list of State notes in an entry."
13511 (when (ignore-errors (goto-char (org-in-item-p)))
13512 (let* ((struct (org-list-struct))
13513 (prevs (org-list-prevs-alist struct))
13514 (regexp
13515 (concat "[ \t]*- +"
13516 (replace-regexp-in-string
13517 " +" " +"
13518 (org-replace-escapes
13519 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13520 `(("%d" . ,org-ts-regexp-inactive)
13521 ("%D" . ,org-ts-regexp)
13522 ("%s" . "\"\\S-+\"")
13523 ("%S" . "\"\\S-+\"")
13524 ("%t" . ,org-ts-regexp-inactive)
13525 ("%T" . ,org-ts-regexp)
13526 ("%u" . ".*?")
13527 ("%U" . ".*?")))))))
13528 (while (looking-at-p regexp)
13529 (goto-char (or (org-list-get-next-item (point) struct prevs)
13530 (org-list-get-item-end (point) struct)))))))
13532 (defun org-add-log-note (&optional _purpose)
13533 "Pop up a window for taking a note, and add this note later."
13534 (remove-hook 'post-command-hook 'org-add-log-note)
13535 (setq org-log-note-window-configuration (current-window-configuration))
13536 (delete-other-windows)
13537 (move-marker org-log-note-return-to (point))
13538 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13539 (goto-char org-log-note-marker)
13540 (org-switch-to-buffer-other-window "*Org Note*")
13541 (erase-buffer)
13542 (if (memq org-log-note-how '(time state))
13543 (org-store-log-note)
13544 (let ((org-inhibit-startup t)) (org-mode))
13545 (insert (format "# Insert note for %s.
13546 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13547 (cond
13548 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13549 ((eq org-log-note-purpose 'done) "closed todo item")
13550 ((eq org-log-note-purpose 'state)
13551 (format "state change from \"%s\" to \"%s\""
13552 (or org-log-note-previous-state "")
13553 (or org-log-note-state "")))
13554 ((eq org-log-note-purpose 'reschedule)
13555 "rescheduling")
13556 ((eq org-log-note-purpose 'delschedule)
13557 "no longer scheduled")
13558 ((eq org-log-note-purpose 'redeadline)
13559 "changing deadline")
13560 ((eq org-log-note-purpose 'deldeadline)
13561 "removing deadline")
13562 ((eq org-log-note-purpose 'refile)
13563 "refiling")
13564 ((eq org-log-note-purpose 'note)
13565 "this entry")
13566 (t (error "This should not happen")))))
13567 (when org-log-note-extra (insert org-log-note-extra))
13568 (setq-local org-finish-function 'org-store-log-note)
13569 (run-hooks 'org-log-buffer-setup-hook)))
13571 (defvar org-note-abort nil) ; dynamically scoped
13572 (defun org-store-log-note ()
13573 "Finish taking a log note, and insert it to where it belongs."
13574 (let ((txt (prog1 (buffer-string)
13575 (kill-buffer)))
13576 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13577 lines)
13578 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13579 (setq txt (replace-match "" t t txt)))
13580 (when (string-match "\\s-+\\'" txt)
13581 (setq txt (replace-match "" t t txt)))
13582 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13583 (when (org-string-nw-p note)
13584 (setq note
13585 (org-replace-escapes
13586 note
13587 (list (cons "%u" (user-login-name))
13588 (cons "%U" user-full-name)
13589 (cons "%t" (format-time-string
13590 (org-time-stamp-format 'long 'inactive)
13591 org-log-note-effective-time))
13592 (cons "%T" (format-time-string
13593 (org-time-stamp-format 'long nil)
13594 org-log-note-effective-time))
13595 (cons "%d" (format-time-string
13596 (org-time-stamp-format nil 'inactive)
13597 org-log-note-effective-time))
13598 (cons "%D" (format-time-string
13599 (org-time-stamp-format nil nil)
13600 org-log-note-effective-time))
13601 (cons "%s" (cond
13602 ((not org-log-note-state) "")
13603 ((string-match-p org-ts-regexp
13604 org-log-note-state)
13605 (format "\"[%s]\""
13606 (substring org-log-note-state 1 -1)))
13607 (t (format "\"%s\"" org-log-note-state))))
13608 (cons "%S"
13609 (cond
13610 ((not org-log-note-previous-state) "")
13611 ((string-match-p org-ts-regexp
13612 org-log-note-previous-state)
13613 (format "\"[%s]\""
13614 (substring
13615 org-log-note-previous-state 1 -1)))
13616 (t (format "\"%s\""
13617 org-log-note-previous-state)))))))
13618 (when lines (setq note (concat note " \\\\")))
13619 (push note lines))
13620 (when (and lines (not org-note-abort))
13621 (with-current-buffer (marker-buffer org-log-note-marker)
13622 (org-with-wide-buffer
13623 ;; Find location for the new note.
13624 (goto-char org-log-note-marker)
13625 (set-marker org-log-note-marker nil)
13626 ;; Note associated to a clock is to be located right after
13627 ;; the clock. Do not move point.
13628 (unless (eq org-log-note-purpose 'clock-out)
13629 (goto-char (org-log-beginning t)))
13630 ;; Make sure point is at the beginning of an empty line.
13631 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13632 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13633 ;; In an existing list, add a new item at the top level.
13634 ;; Otherwise, indent line like a regular one.
13635 (let ((itemp (org-in-item-p)))
13636 (if itemp
13637 (indent-line-to
13638 (let ((struct (save-excursion
13639 (goto-char itemp) (org-list-struct))))
13640 (org-list-get-ind (org-list-get-top-point struct) struct)))
13641 (org-indent-line)))
13642 (insert (org-list-bullet-string "-") (pop lines))
13643 (let ((ind (org-list-item-body-column (line-beginning-position))))
13644 (dolist (line lines)
13645 (insert "\n")
13646 (indent-line-to ind)
13647 (insert line)))
13648 (message "Note stored")
13649 (org-back-to-heading t)
13650 (org-cycle-hide-drawers 'children))
13651 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13652 ;; from within `org-add-log-note' because `buffer-undo-list'
13653 ;; is then modified outside of `org-with-remote-undo'.
13654 (when (eq this-command 'org-agenda-todo)
13655 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13656 ;; Don't add undo information when called from `org-agenda-todo'.
13657 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13658 (set-window-configuration org-log-note-window-configuration)
13659 (with-current-buffer (marker-buffer org-log-note-return-to)
13660 (goto-char org-log-note-return-to))
13661 (move-marker org-log-note-return-to nil)
13662 (when org-log-post-message (message "%s" org-log-post-message))))
13664 (defun org-remove-empty-drawer-at (pos)
13665 "Remove an empty drawer at position POS.
13666 POS may also be a marker."
13667 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13668 (org-with-wide-buffer
13669 (goto-char pos)
13670 (let ((drawer (org-element-at-point)))
13671 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13672 (not (org-element-property :contents-begin drawer)))
13673 (delete-region (org-element-property :begin drawer)
13674 (progn (goto-char (org-element-property :end drawer))
13675 (skip-chars-backward " \r\t\n")
13676 (forward-line)
13677 (point))))))))
13679 (defvar org-ts-type nil)
13680 (defun org-sparse-tree (&optional arg type)
13681 "Create a sparse tree, prompt for the details.
13682 This command can create sparse trees. You first need to select the type
13683 of match used to create the tree:
13685 t Show all TODO entries.
13686 T Show entries with a specific TODO keyword.
13687 m Show entries selected by a tags/property match.
13688 p Enter a property name and its value (both with completion on existing
13689 names/values) and show entries with that property.
13690 r Show entries matching a regular expression (`/' can be used as well).
13691 b Show deadlines and scheduled items before a date.
13692 a Show deadlines and scheduled items after a date.
13693 d Show deadlines due within `org-deadline-warning-days'.
13694 D Show deadlines and scheduled items between a date range."
13695 (interactive "P")
13696 (setq type (or type org-sparse-tree-default-date-type))
13697 (setq org-ts-type type)
13698 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13699 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13700 \[c]ycle through date types: %s"
13701 (cl-case type
13702 (all "all timestamps")
13703 (scheduled "only scheduled")
13704 (deadline "only deadline")
13705 (active "only active timestamps")
13706 (inactive "only inactive timestamps")
13707 (closed "with a closed time-stamp")
13708 (otherwise "scheduled/deadline")))
13709 (let ((answer (read-char-exclusive)))
13710 (cl-case answer
13712 (org-sparse-tree
13714 (cadr
13715 (memq type '(nil all scheduled deadline active inactive closed)))))
13716 (?d (call-interactively 'org-check-deadlines))
13717 (?b (call-interactively 'org-check-before-date))
13718 (?a (call-interactively 'org-check-after-date))
13719 (?D (call-interactively 'org-check-dates-range))
13720 (?t (call-interactively 'org-show-todo-tree))
13721 (?T (org-show-todo-tree '(4)))
13722 (?m (call-interactively 'org-match-sparse-tree))
13723 ((?p ?P)
13724 (let* ((kwd (completing-read
13725 "Property: " (mapcar #'list (org-buffer-property-keys))))
13726 (value (completing-read
13727 "Value: " (mapcar #'list (org-property-values kwd)))))
13728 (unless (string-match "\\`{.*}\\'" value)
13729 (setq value (concat "\"" value "\"")))
13730 (org-match-sparse-tree arg (concat kwd "=" value))))
13731 ((?r ?R ?/) (call-interactively 'org-occur))
13732 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13734 (defvar-local org-occur-highlights nil
13735 "List of overlays used for occur matches.")
13736 (defvar-local org-occur-parameters nil
13737 "Parameters of the active org-occur calls.
13738 This is a list, each call to org-occur pushes as cons cell,
13739 containing the regular expression and the callback, onto the list.
13740 The list can contain several entries if `org-occur' has been called
13741 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13742 will only contain one set of parameters. When the highlights are
13743 removed (for example with `C-c C-c', or with the next edit (depending
13744 on `org-remove-highlights-with-change'), this variable is emptied
13745 as well.")
13747 (defun org-occur (regexp &optional keep-previous callback)
13748 "Make a compact tree which shows all matches of REGEXP.
13750 The tree will show the lines where the regexp matches, and any other context
13751 defined in `org-show-context-detail', which see.
13753 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13754 done by a previous call to `org-occur' will be kept, to allow stacking of
13755 calls to this command.
13757 Optional argument CALLBACK can be a function of no argument. In this case,
13758 it is called with point at the end of the match, match data being set
13759 accordingly. Current match is shown only if the return value is non-nil.
13760 The function must neither move point nor alter narrowing."
13761 (interactive "sRegexp: \nP")
13762 (when (equal regexp "")
13763 (user-error "Regexp cannot be empty"))
13764 (unless keep-previous
13765 (org-remove-occur-highlights nil nil t))
13766 (push (cons regexp callback) org-occur-parameters)
13767 (let ((cnt 0))
13768 (save-excursion
13769 (goto-char (point-min))
13770 (when (or (not keep-previous) ; do not want to keep
13771 (not org-occur-highlights)) ; no previous matches
13772 ;; hide everything
13773 (org-overview))
13774 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13775 (isearch-no-upper-case-p regexp t)
13776 org-occur-case-fold-search)))
13777 (while (re-search-forward regexp nil t)
13778 (when (or (not callback)
13779 (save-match-data (funcall callback)))
13780 (setq cnt (1+ cnt))
13781 (when org-highlight-sparse-tree-matches
13782 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13783 (org-show-context 'occur-tree)))))
13784 (when org-remove-highlights-with-change
13785 (add-hook 'before-change-functions 'org-remove-occur-highlights
13786 nil 'local))
13787 (unless org-sparse-tree-open-archived-trees
13788 (org-hide-archived-subtrees (point-min) (point-max)))
13789 (run-hooks 'org-occur-hook)
13790 (when (called-interactively-p 'interactive)
13791 (message "%d match(es) for regexp %s" cnt regexp))
13792 cnt))
13794 (defun org-occur-next-match (&optional n _reset)
13795 "Function for `next-error-function' to find sparse tree matches.
13796 N is the number of matches to move, when negative move backwards.
13797 This function always goes back to the starting point when no
13798 match is found."
13799 (let* ((limit (if (< n 0) (point-min) (point-max)))
13800 (search-func (if (< n 0)
13801 'previous-single-char-property-change
13802 'next-single-char-property-change))
13803 (n (abs n))
13804 (pos (point))
13806 (catch 'exit
13807 (while (setq p1 (funcall search-func (point) 'org-type))
13808 (when (equal p1 limit)
13809 (goto-char pos)
13810 (user-error "No more matches"))
13811 (when (equal (get-char-property p1 'org-type) 'org-occur)
13812 (setq n (1- n))
13813 (when (= n 0)
13814 (goto-char p1)
13815 (throw 'exit (point))))
13816 (goto-char p1))
13817 (goto-char p1)
13818 (user-error "No more matches"))))
13820 (defun org-show-context (&optional key)
13821 "Make sure point and context are visible.
13822 Optional argument KEY, when non-nil, is a symbol. See
13823 `org-show-context-detail' for allowed values and how much is to
13824 be shown."
13825 (org-show-set-visibility
13826 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13827 ((cdr (assq key org-show-context-detail)))
13828 (t (cdr (assq 'default org-show-context-detail))))))
13830 (defun org-show-set-visibility (detail)
13831 "Set visibility around point according to DETAIL.
13832 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13833 `tree', `canonical' or t. See `org-show-context-detail' for more
13834 information."
13835 ;; Show current heading and possibly its entry, following headline
13836 ;; or all children.
13837 (if (and (org-at-heading-p) (not (eq detail 'local)))
13838 (org-flag-heading nil)
13839 (org-show-entry)
13840 ;; If point is hidden within a drawer or a block, make sure to
13841 ;; expose it.
13842 (dolist (o (overlays-at (point)))
13843 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13844 (delete-overlay o)))
13845 (unless (org-before-first-heading-p)
13846 (org-with-limited-levels
13847 (cl-case detail
13848 ((tree canonical t) (org-show-children))
13849 ((nil minimal ancestors))
13850 (t (save-excursion
13851 (outline-next-heading)
13852 (org-flag-heading nil)))))))
13853 ;; Show all siblings.
13854 (when (eq detail 'lineage) (org-show-siblings))
13855 ;; Show ancestors, possibly with their children.
13856 (when (memq detail '(ancestors lineage tree canonical t))
13857 (save-excursion
13858 (while (org-up-heading-safe)
13859 (org-flag-heading nil)
13860 (when (memq detail '(canonical t)) (org-show-entry))
13861 (when (memq detail '(tree canonical t)) (org-show-children))))))
13863 (defvar org-reveal-start-hook nil
13864 "Hook run before revealing a location.")
13866 (defun org-reveal (&optional siblings)
13867 "Show current entry, hierarchy above it, and the following headline.
13869 This can be used to show a consistent set of context around
13870 locations exposed with `org-show-context'.
13872 With optional argument SIBLINGS, on each level of the hierarchy all
13873 siblings are shown. This repairs the tree structure to what it would
13874 look like when opened with hierarchical calls to `org-cycle'.
13876 With a \\[universal-argument] \\[universal-argument] prefix, \
13877 go to the parent and show the entire tree."
13878 (interactive "P")
13879 (run-hooks 'org-reveal-start-hook)
13880 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13881 ((equal siblings '(16))
13882 (save-excursion
13883 (when (org-up-heading-safe)
13884 (org-show-subtree)
13885 (run-hook-with-args 'org-cycle-hook 'subtree))))
13886 (t (org-show-set-visibility 'lineage))))
13888 (defun org-highlight-new-match (beg end)
13889 "Highlight from BEG to END and mark the highlight is an occur headline."
13890 (let ((ov (make-overlay beg end)))
13891 (overlay-put ov 'face 'secondary-selection)
13892 (overlay-put ov 'org-type 'org-occur)
13893 (push ov org-occur-highlights)))
13895 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13896 "Remove the occur highlights from the buffer.
13897 BEG and END are ignored. If NOREMOVE is nil, remove this function
13898 from the `before-change-functions' in the current buffer."
13899 (interactive)
13900 (unless org-inhibit-highlight-removal
13901 (mapc #'delete-overlay org-occur-highlights)
13902 (setq org-occur-highlights nil)
13903 (setq org-occur-parameters nil)
13904 (unless noremove
13905 (remove-hook 'before-change-functions
13906 'org-remove-occur-highlights 'local))))
13908 ;;;; Priorities
13910 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13911 "Regular expression matching the priority indicator.")
13913 (defvar org-remove-priority-next-time nil)
13915 (defun org-priority-up ()
13916 "Increase the priority of the current item."
13917 (interactive)
13918 (org-priority 'up))
13920 (defun org-priority-down ()
13921 "Decrease the priority of the current item."
13922 (interactive)
13923 (org-priority 'down))
13925 (defun org-priority (&optional action _show)
13926 "Change the priority of an item.
13927 ACTION can be `set', `up', `down', or a character."
13928 (interactive "P")
13929 (if (equal action '(4))
13930 (org-show-priority)
13931 (unless org-enable-priority-commands
13932 (user-error "Priority commands are disabled"))
13933 (setq action (or action 'set))
13934 (let (current new news have remove)
13935 (save-excursion
13936 (org-back-to-heading t)
13937 (when (looking-at org-priority-regexp)
13938 (setq current (string-to-char (match-string 2))
13939 have t))
13940 (cond
13941 ((eq action 'remove)
13942 (setq remove t new ?\ ))
13943 ((or (eq action 'set)
13944 (integerp action))
13945 (if (not (eq action 'set))
13946 (setq new action)
13947 (message "Priority %c-%c, SPC to remove: "
13948 org-highest-priority org-lowest-priority)
13949 (save-match-data
13950 (setq new (read-char-exclusive))))
13951 (when (and (= (upcase org-highest-priority) org-highest-priority)
13952 (= (upcase org-lowest-priority) org-lowest-priority))
13953 (setq new (upcase new)))
13954 (cond ((equal new ?\ ) (setq remove t))
13955 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13956 (user-error "Priority must be between `%c' and `%c'"
13957 org-highest-priority org-lowest-priority))))
13958 ((eq action 'up)
13959 (setq new (if have
13960 (1- current) ; normal cycling
13961 ;; last priority was empty
13962 (if (eq last-command this-command)
13963 org-lowest-priority ; wrap around empty to lowest
13964 ;; default
13965 (if org-priority-start-cycle-with-default
13966 org-default-priority
13967 (1- org-default-priority))))))
13968 ((eq action 'down)
13969 (setq new (if have
13970 (1+ current) ; normal cycling
13971 ;; last priority was empty
13972 (if (eq last-command this-command)
13973 org-highest-priority ; wrap around empty to highest
13974 ;; default
13975 (if org-priority-start-cycle-with-default
13976 org-default-priority
13977 (1+ org-default-priority))))))
13978 (t (user-error "Invalid action")))
13979 (when (or (< (upcase new) org-highest-priority)
13980 (> (upcase new) org-lowest-priority))
13981 (if (and (memq action '(up down))
13982 (not have) (not (eq last-command this-command)))
13983 ;; `new' is from default priority
13984 (error
13985 "The default can not be set, see `org-default-priority' why")
13986 ;; normal cycling: `new' is beyond highest/lowest priority
13987 ;; and is wrapped around to the empty priority
13988 (setq remove t)))
13989 (setq news (format "%c" new))
13990 (if have
13991 (if remove
13992 (replace-match "" t t nil 1)
13993 (replace-match news t t nil 2))
13994 (if remove
13995 (user-error "No priority cookie found in line")
13996 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13997 (if (match-end 2)
13998 (progn
13999 (goto-char (match-end 2))
14000 (insert " [#" news "]"))
14001 (goto-char (match-beginning 3))
14002 (insert "[#" news "] "))))
14003 (org-set-tags nil 'align))
14004 (if remove
14005 (message "Priority removed")
14006 (message "Priority of current item set to %s" news)))))
14008 (defun org-show-priority ()
14009 "Show the priority of the current item.
14010 This priority is composed of the main priority given with the [#A] cookies,
14011 and by additional input from the age of a schedules or deadline entry."
14012 (interactive)
14013 (let ((pri (if (eq major-mode 'org-agenda-mode)
14014 (org-get-at-bol 'priority)
14015 (save-excursion
14016 (save-match-data
14017 (beginning-of-line)
14018 (and (looking-at org-heading-regexp)
14019 (org-get-priority (match-string 0))))))))
14020 (message "Priority is %d" (if pri pri -1000))))
14022 (defun org-get-priority (s)
14023 "Find priority cookie and return priority."
14024 (save-match-data
14025 (if (functionp org-get-priority-function)
14026 (funcall org-get-priority-function)
14027 (if (not (string-match org-priority-regexp s))
14028 (* 1000 (- org-lowest-priority org-default-priority))
14029 (* 1000 (- org-lowest-priority
14030 (string-to-char (match-string 2 s))))))))
14032 ;;;; Tags
14034 (defvar org-agenda-archives-mode)
14035 (defvar org-map-continue-from nil
14036 "Position from where mapping should continue.
14037 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14039 (defvar org-scanner-tags nil
14040 "The current tag list while the tags scanner is running.")
14042 (defvar org-trust-scanner-tags nil
14043 "Should `org-get-tags-at' use the tags for the scanner.
14044 This is for internal dynamical scoping only.
14045 When this is non-nil, the function `org-get-tags-at' will return the value
14046 of `org-scanner-tags' instead of building the list by itself. This
14047 can lead to large speed-ups when the tags scanner is used in a file with
14048 many entries, and when the list of tags is retrieved, for example to
14049 obtain a list of properties. Building the tags list for each entry in such
14050 a file becomes an N^2 operation - but with this variable set, it scales
14051 as N.")
14053 (defvar org--matcher-tags-todo-only nil)
14055 (defun org-scan-tags (action matcher todo-only &optional start-level)
14056 "Scan headline tags with inheritance and produce output ACTION.
14058 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14059 or `agenda' to produce an entry list for an agenda view. It can also be
14060 a Lisp form or a function that should be called at each matched headline, in
14061 this case the return value is a list of all return values from these calls.
14063 MATCHER is a function accepting three arguments, returning
14064 a non-nil value whenever a given set of tags qualifies a headline
14065 for inclusion. See `org-make-tags-matcher' for more information.
14066 As a special case, it can also be set to t (respectively nil) in
14067 order to match all (respectively none) headline.
14069 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14070 included in the output.
14072 START-LEVEL can be a string with asterisks, reducing the scope to
14073 headlines matching this string."
14074 (require 'org-agenda)
14075 (let* ((re (concat "^"
14076 (if start-level
14077 ;; Get the correct level to match
14078 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14079 org-outline-regexp)
14080 " *\\(\\<\\("
14081 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14082 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14083 (props (list 'face 'default
14084 'done-face 'org-agenda-done
14085 'undone-face 'default
14086 'mouse-face 'highlight
14087 'org-not-done-regexp org-not-done-regexp
14088 'org-todo-regexp org-todo-regexp
14089 'org-complex-heading-regexp org-complex-heading-regexp
14090 'help-echo
14091 (format "mouse-2 or RET jump to org file %s"
14092 (abbreviate-file-name
14093 (or (buffer-file-name (buffer-base-buffer))
14094 (buffer-name (buffer-base-buffer)))))))
14095 (org-map-continue-from nil)
14096 lspos tags tags-list
14097 (tags-alist (list (cons 0 org-file-tags)))
14098 (llast 0) rtn rtn1 level category i txt
14099 todo marker entry priority
14100 ts-date ts-date-type ts-date-pair)
14101 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14102 (setq action (list 'lambda nil action)))
14103 (save-excursion
14104 (goto-char (point-min))
14105 (when (eq action 'sparse-tree)
14106 (org-overview)
14107 (org-remove-occur-highlights))
14108 (while (let (case-fold-search)
14109 (re-search-forward re nil t))
14110 (setq org-map-continue-from nil)
14111 (catch :skip
14112 (setq todo
14113 ;; TODO: is the 1-2 difference a bug?
14114 (when (match-end 1) (match-string-no-properties 2))
14115 tags (when (match-end 4) (match-string-no-properties 4)))
14116 (goto-char (setq lspos (match-beginning 0)))
14117 (setq level (org-reduced-level (org-outline-level))
14118 category (org-get-category))
14119 (when (eq action 'agenda)
14120 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14121 ts-date (car ts-date-pair)
14122 ts-date-type (cdr ts-date-pair)))
14123 (setq i llast llast level)
14124 ;; remove tag lists from same and sublevels
14125 (while (>= i level)
14126 (when (setq entry (assoc i tags-alist))
14127 (setq tags-alist (delete entry tags-alist)))
14128 (setq i (1- i)))
14129 ;; add the next tags
14130 (when tags
14131 (setq tags (org-split-string tags ":")
14132 tags-alist
14133 (cons (cons level tags) tags-alist)))
14134 ;; compile tags for current headline
14135 (setq tags-list
14136 (if org-use-tag-inheritance
14137 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14138 tags)
14139 org-scanner-tags tags-list)
14140 (when org-use-tag-inheritance
14141 (setcdr (car tags-alist)
14142 (mapcar (lambda (x)
14143 (setq x (copy-sequence x))
14144 (org-add-prop-inherited x))
14145 (cdar tags-alist))))
14146 (when (and tags org-use-tag-inheritance
14147 (or (not (eq t org-use-tag-inheritance))
14148 org-tags-exclude-from-inheritance))
14149 ;; Selective inheritance, remove uninherited ones.
14150 (setcdr (car tags-alist)
14151 (org-remove-uninherited-tags (cdar tags-alist))))
14152 (when (and
14154 ;; eval matcher only when the todo condition is OK
14155 (and (or (not todo-only) (member todo org-todo-keywords-1))
14156 (if (functionp matcher)
14157 (let ((case-fold-search t) (org-trust-scanner-tags t))
14158 (funcall matcher todo tags-list level))
14159 matcher))
14161 ;; Call the skipper, but return t if it does not
14162 ;; skip, so that the `and' form continues evaluating.
14163 (progn
14164 (unless (eq action 'sparse-tree) (org-agenda-skip))
14167 ;; Check if timestamps are deselecting this entry
14168 (or (not todo-only)
14169 (and (member todo org-todo-keywords-1)
14170 (or (not org-agenda-tags-todo-honor-ignore-options)
14171 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14173 ;; select this headline
14174 (cond
14175 ((eq action 'sparse-tree)
14176 (and org-highlight-sparse-tree-matches
14177 (org-get-heading) (match-end 0)
14178 (org-highlight-new-match
14179 (match-beginning 1) (match-end 1)))
14180 (org-show-context 'tags-tree))
14181 ((eq action 'agenda)
14182 (setq txt (org-agenda-format-item
14184 (concat
14185 (if (eq org-tags-match-list-sublevels 'indented)
14186 (make-string (1- level) ?.) "")
14187 (org-get-heading))
14188 (make-string level ?\s)
14189 category
14190 tags-list)
14191 priority (org-get-priority txt))
14192 (goto-char lspos)
14193 (setq marker (org-agenda-new-marker))
14194 (org-add-props txt props
14195 'org-marker marker 'org-hd-marker marker 'org-category category
14196 'todo-state todo
14197 'ts-date ts-date
14198 'priority priority
14199 'type (concat "tagsmatch" ts-date-type))
14200 (push txt rtn))
14201 ((functionp action)
14202 (setq org-map-continue-from nil)
14203 (save-excursion
14204 (setq rtn1 (funcall action))
14205 (push rtn1 rtn)))
14206 (t (user-error "Invalid action")))
14208 ;; if we are to skip sublevels, jump to end of subtree
14209 (unless org-tags-match-list-sublevels
14210 (org-end-of-subtree t)
14211 (backward-char 1))))
14212 ;; Get the correct position from where to continue
14213 (if org-map-continue-from
14214 (goto-char org-map-continue-from)
14215 (and (= (point) lspos) (end-of-line 1)))))
14216 (when (and (eq action 'sparse-tree)
14217 (not org-sparse-tree-open-archived-trees))
14218 (org-hide-archived-subtrees (point-min) (point-max)))
14219 (nreverse rtn)))
14221 (defun org-remove-uninherited-tags (tags)
14222 "Remove all tags that are not inherited from the list TAGS."
14223 (cond
14224 ((eq org-use-tag-inheritance t)
14225 (if org-tags-exclude-from-inheritance
14226 (org-delete-all org-tags-exclude-from-inheritance tags)
14227 tags))
14228 ((not org-use-tag-inheritance) nil)
14229 ((stringp org-use-tag-inheritance)
14230 (delq nil (mapcar
14231 (lambda (x)
14232 (if (and (string-match org-use-tag-inheritance x)
14233 (not (member x org-tags-exclude-from-inheritance)))
14234 x nil))
14235 tags)))
14236 ((listp org-use-tag-inheritance)
14237 (delq nil (mapcar
14238 (lambda (x)
14239 (if (member x org-use-tag-inheritance) x nil))
14240 tags)))))
14242 (defun org-match-sparse-tree (&optional todo-only match)
14243 "Create a sparse tree according to tags string MATCH.
14245 MATCH is a string with match syntax. It can contain a selection
14246 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14247 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14248 those. See the manual for details.
14250 If optional argument TODO-ONLY is non-nil, only select lines that
14251 are also TODO tasks."
14252 (interactive "P")
14253 (org-agenda-prepare-buffers (list (current-buffer)))
14254 (let ((org--matcher-tags-todo-only todo-only))
14255 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14256 org--matcher-tags-todo-only)))
14258 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14260 (defvar org-cached-props nil)
14261 (defun org-cached-entry-get (pom property)
14262 (if (or (eq t org-use-property-inheritance)
14263 (and (stringp org-use-property-inheritance)
14264 (let ((case-fold-search t))
14265 (string-match-p org-use-property-inheritance property)))
14266 (and (listp org-use-property-inheritance)
14267 (member-ignore-case property org-use-property-inheritance)))
14268 ;; Caching is not possible, check it directly.
14269 (org-entry-get pom property 'inherit)
14270 ;; Get all properties, so we can do complicated checks easily.
14271 (cdr (assoc-string property
14272 (or org-cached-props
14273 (setq org-cached-props (org-entry-properties pom)))
14274 t))))
14276 (defun org-global-tags-completion-table (&optional files)
14277 "Return the list of all tags in all agenda buffer/files.
14278 Optional FILES argument is a list of files which can be used
14279 instead of the agenda files."
14280 (save-excursion
14281 (org-uniquify
14282 (delq nil
14283 (apply #'append
14284 (mapcar
14285 (lambda (file)
14286 (set-buffer (find-file-noselect file))
14287 (mapcar (lambda (x)
14288 (and (stringp (car-safe x))
14289 (list (car-safe x))))
14290 (or org-current-tag-alist (org-get-buffer-tags))))
14291 (if (car-safe files) files
14292 (org-agenda-files))))))))
14294 (defun org-make-tags-matcher (match)
14295 "Create the TAGS/TODO matcher form for the selection string MATCH.
14297 Returns a cons of the selection string MATCH and a function
14298 implementing the matcher.
14300 The matcher is to be called at an Org entry, with point on the
14301 headline, and returns non-nil if the entry matches the selection
14302 string MATCH. It must be called with three arguments: the TODO
14303 keyword at the entry (or nil if none), the list of all tags at
14304 the entry including inherited ones and the reduced level of the
14305 headline. Additionally, the category of the entry, if any, must
14306 be specified as the text property `org-category' on the headline.
14308 This function sets the variable `org--matcher-tags-todo-only' to
14309 a non-nil value if the matcher restricts matching to TODO
14310 entries, otherwise it is not touched.
14312 See also `org-scan-tags'."
14313 (unless match
14314 ;; Get a new match request, with completion against the global
14315 ;; tags table and the local tags in current buffer.
14316 (let ((org-last-tags-completion-table
14317 (org-uniquify
14318 (delq nil (append (org-get-buffer-tags)
14319 (org-global-tags-completion-table))))))
14320 (setq match
14321 (completing-read
14322 "Match: "
14323 'org-tags-completion-function nil nil nil 'org-tags-history))))
14325 (let ((match0 match)
14326 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14327 (start 0)
14328 tagsmatch todomatch tagsmatcher todomatcher)
14330 ;; Expand group tags.
14331 (setq match (org-tags-expand match))
14333 ;; Check if there is a TODO part of this match, which would be the
14334 ;; part after a "/". To make sure that this slash is not part of
14335 ;; a property value to be matched against, we also check that
14336 ;; there is no / after that slash. First, find the last slash.
14337 (let ((s 0))
14338 (while (string-match "/+" match s)
14339 (setq start (match-beginning 0))
14340 (setq s (match-end 0))))
14341 (if (and (string-match "/+" match start)
14342 (not (string-match-p "\"" match start)))
14343 ;; Match contains also a TODO-matching request.
14344 (progn
14345 (setq tagsmatch (substring match 0 (match-beginning 0)))
14346 (setq todomatch (substring match (match-end 0)))
14347 (when (string-prefix-p "!" todomatch)
14348 (setq org--matcher-tags-todo-only t)
14349 (setq todomatch (substring todomatch 1)))
14350 (when (string-match "\\`\\s-*\\'" todomatch)
14351 (setq todomatch nil)))
14352 ;; Only matching tags.
14353 (setq tagsmatch match)
14354 (setq todomatch nil))
14356 ;; Make the tags matcher.
14357 (when (org-string-nw-p tagsmatch)
14358 (let ((orlist nil)
14359 (orterms (org-split-string tagsmatch "|"))
14360 term)
14361 (while (setq term (pop orterms))
14362 (while (and (equal (substring term -1) "\\") orterms)
14363 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14364 (while (string-match re term)
14365 (let* ((rest (substring term (match-end 0)))
14366 (minus (and (match-end 1)
14367 (equal (match-string 1 term) "-")))
14368 (tag (save-match-data
14369 (replace-regexp-in-string
14370 "\\\\-" "-" (match-string 2 term))))
14371 (regexp (eq (string-to-char tag) ?{))
14372 (levelp (match-end 4))
14373 (propp (match-end 5))
14375 (cond
14376 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14377 (levelp
14378 `(,(org-op-to-function (match-string 3 term))
14379 level
14380 ,(string-to-number (match-string 4 term))))
14381 (propp
14382 (let* ((gv (pcase (upcase (match-string 5 term))
14383 ("CATEGORY"
14384 '(get-text-property (point) 'org-category))
14385 ("TODO" 'todo)
14386 (p `(org-cached-entry-get nil ,p))))
14387 (pv (match-string 7 term))
14388 (regexp (eq (string-to-char pv) ?{))
14389 (strp (eq (string-to-char pv) ?\"))
14390 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14391 (po (org-op-to-function (match-string 6 term)
14392 (if timep 'time strp))))
14393 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14394 (when timep (setq pv (org-matcher-time pv)))
14395 (cond ((and regexp (eq po 'org<>))
14396 `(not (string-match ,pv (or ,gv ""))))
14397 (regexp `(string-match ,pv (or ,gv "")))
14398 (strp `(,po (or ,gv "") ,pv))
14400 `(,po
14401 (string-to-number (or ,gv ""))
14402 ,(string-to-number pv))))))
14403 (t `(member ,tag tags-list)))))
14404 (push (if minus `(not ,mm) mm) tagsmatcher)
14405 (setq term rest)))
14406 (push `(and ,@tagsmatcher) orlist)
14407 (setq tagsmatcher nil))
14408 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14410 ;; Make the TODO matcher.
14411 (when (org-string-nw-p todomatch)
14412 (let ((orlist nil))
14413 (dolist (term (org-split-string todomatch "|"))
14414 (while (string-match re term)
14415 (let* ((minus (and (match-end 1)
14416 (equal (match-string 1 term) "-")))
14417 (kwd (match-string 2 term))
14418 (regexp (eq (string-to-char kwd) ?{))
14419 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14420 `(equal todo ,kwd))))
14421 (push (if minus `(not ,mm) mm) todomatcher))
14422 (setq term (substring term (match-end 0))))
14423 (push (if (> (length todomatcher) 1)
14424 (cons 'and todomatcher)
14425 (car todomatcher))
14426 orlist)
14427 (setq todomatcher nil))
14428 (setq todomatcher (cons 'or orlist))))
14430 ;; Return the string and function of the matcher. If no
14431 ;; tags-specific or todo-specific matcher exists, match
14432 ;; everything.
14433 (let ((matcher (if (and tagsmatcher todomatcher)
14434 `(and ,tagsmatcher ,todomatcher)
14435 (or tagsmatcher todomatcher t))))
14436 (when org--matcher-tags-todo-only
14437 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14438 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14440 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14441 "Expand group tags in MATCH.
14443 This replaces every group tag in MATCH with a regexp tag search.
14444 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14445 will be replaced like this:
14447 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14448 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14449 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14451 Replacing by a regexp preserves the structure of the match.
14452 E.g., this expansion
14454 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14456 will match anything tagged with \"Lab\" and \"Home\", or tagged
14457 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14459 A group tag in MATCH can contain regular expressions of its own.
14460 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14461 will be replaced like this:
14463 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14465 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14466 assumed to be a single group tag, and the function will return
14467 the list of tags in this group.
14469 When DOWNCASE is non-nil, expand downcased TAGS."
14470 (if org-group-tags
14471 (let* ((case-fold-search t)
14472 (stable org-mode-syntax-table)
14473 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14474 (taggroups (if downcased
14475 (mapcar (lambda (tg) (mapcar #'downcase tg))
14476 taggroups)
14477 taggroups))
14478 (taggroups-keys (mapcar #'car taggroups))
14479 (return-match (if downcased (downcase match) match))
14480 (count 0)
14481 (work-already-expanded tags-already-expanded)
14482 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14483 ;; @ and _ are allowed as word-components in tags.
14484 (modify-syntax-entry ?@ "w" stable)
14485 (modify-syntax-entry ?_ "w" stable)
14486 ;; Temporarily replace regexp-expressions in the match-expression.
14487 (while (string-match "{.+?}" return-match)
14488 (cl-incf count)
14489 (push (match-string 0 return-match) regexps-in-match)
14490 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14491 (while (and taggroups-keys
14492 (with-syntax-table stable
14493 (string-match
14494 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14495 (regexp-opt taggroups-keys) "\\>\\)")
14496 return-match)))
14497 (let* ((dir (match-string 1 return-match))
14498 (tag (match-string 2 return-match))
14499 (tag (if downcased (downcase tag) tag)))
14500 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14501 (member tag work-already-expanded))
14502 (setq tags-in-group (assoc tag taggroups))
14503 (push tag work-already-expanded)
14504 ;; Recursively expand each tag in the group, if the tag hasn't
14505 ;; already been expanded. Restore the match-data after all recursive calls.
14506 (save-match-data
14507 (let (tags-expanded)
14508 (dolist (x (cdr tags-in-group))
14509 (if (and (member x taggroups-keys)
14510 (not (member x work-already-expanded)))
14511 (setq tags-expanded
14512 (delete-dups
14513 (append
14514 (org-tags-expand x t downcased
14515 work-already-expanded)
14516 tags-expanded)))
14517 (setq tags-expanded
14518 (append (list x) tags-expanded)))
14519 (setq work-already-expanded
14520 (delete-dups
14521 (append tags-expanded
14522 work-already-expanded))))
14523 (setq tags-in-group
14524 (delete-dups (cons (car tags-in-group)
14525 tags-expanded)))))
14526 ;; Filter tag-regexps from tags.
14527 (setq regexp-in-group-escaped
14528 (delq nil (mapcar (lambda (x)
14529 (if (stringp x)
14530 (and (equal "{" (substring x 0 1))
14531 (equal "}" (substring x -1))
14534 tags-in-group))
14535 regexp-in-group
14536 (mapcar (lambda (x)
14537 (substring x 1 -1))
14538 regexp-in-group-escaped)
14539 tags-in-group
14540 (delq nil (mapcar (lambda (x)
14541 (if (stringp x)
14542 (and (not (equal "{" (substring x 0 1)))
14543 (not (equal "}" (substring x -1)))
14546 tags-in-group)))
14547 ;; If single-as-list, do no more in the while-loop.
14548 (if (not single-as-list)
14549 (progn
14550 (when regexp-in-group
14551 (setq regexp-in-group
14552 (concat "\\|"
14553 (mapconcat 'identity regexp-in-group
14554 "\\|"))))
14555 (setq tags-in-group
14556 (concat dir
14557 "{\\<"
14558 (regexp-opt tags-in-group)
14559 "\\>"
14560 regexp-in-group
14561 "}"))
14562 (when (stringp tags-in-group)
14563 (org-add-props tags-in-group '(grouptag t)))
14564 (setq return-match
14565 (replace-match tags-in-group t t return-match)))
14566 (setq tags-in-group
14567 (append regexp-in-group-escaped tags-in-group))))
14568 (setq taggroups-keys (delete tag taggroups-keys))))
14569 ;; Add the regular expressions back into the match-expression again.
14570 (while regexps-in-match
14571 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14572 (pop regexps-in-match)
14573 return-match t t))
14574 (cl-decf count))
14575 (if single-as-list
14576 (if tags-in-group tags-in-group (list return-match))
14577 return-match))
14578 (if single-as-list
14579 (list (if downcased (downcase match) match))
14580 match)))
14582 (defun org-op-to-function (op &optional stringp)
14583 "Turn an operator into the appropriate function."
14584 (setq op
14585 (cond
14586 ((equal op "<" ) '(< string< org-time<))
14587 ((equal op ">" ) '(> org-string> org-time>))
14588 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14589 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14590 ((member op '("=" "==")) '(= string= org-time=))
14591 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14592 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14594 (defun org<> (a b) (not (= a b)))
14595 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14596 (defun org-string>= (a b) (not (string< a b)))
14597 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14598 (defun org-string<> (a b) (not (string= a b)))
14599 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14600 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14601 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14602 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
14605 (defun org-2ft (s)
14606 "Convert S to a floating point time.
14607 If S is already a number, just return it. If it is a string, parse
14608 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14609 (cond
14610 ((numberp s) s)
14611 ((stringp s)
14612 (condition-case nil
14613 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14614 (error 0.)))
14615 (t 0.)))
14617 (defun org-time-today ()
14618 "Time in seconds today at 0:00.
14619 Returns the float number of seconds since the beginning of the
14620 epoch to the beginning of today (00:00)."
14621 (float-time (apply 'encode-time
14622 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14624 (defun org-matcher-time (s)
14625 "Interpret a time comparison value."
14626 (save-match-data
14627 (cond
14628 ((string= s "<now>") (float-time))
14629 ((string= s "<today>") (org-time-today))
14630 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14631 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14632 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14633 (+ (org-time-today)
14634 (* (string-to-number (match-string 1 s))
14635 (cdr (assoc (match-string 2 s)
14636 '(("d" . 86400.0) ("w" . 604800.0)
14637 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14638 (t (org-2ft s)))))
14640 (defun org-match-any-p (re list)
14641 "Does re match any element of list?"
14642 (setq list (mapcar (lambda (x) (string-match re x)) list))
14643 (delq nil list))
14645 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14646 (defvar org-tags-overlay (make-overlay 1 1))
14647 (delete-overlay org-tags-overlay)
14649 (defun org-get-local-tags-at (&optional pos)
14650 "Get a list of tags defined in the current headline."
14651 (org-get-tags-at pos 'local))
14653 (defun org-get-local-tags ()
14654 "Get a list of tags defined in the current headline."
14655 (org-get-tags-at nil 'local))
14657 (defun org-get-tags-at (&optional pos local)
14658 "Get a list of all headline tags applicable at POS.
14659 POS defaults to point. If tags are inherited, the list contains
14660 the targets in the same sequence as the headlines appear, i.e.
14661 the tags of the current headline come last.
14662 When LOCAL is non-nil, only return tags from the current headline,
14663 ignore inherited ones."
14664 (interactive)
14665 (if (and org-trust-scanner-tags
14666 (or (not pos) (equal pos (point)))
14667 (not local))
14668 org-scanner-tags
14669 (let (tags ltags lastpos parent)
14670 (save-excursion
14671 (save-restriction
14672 (widen)
14673 (goto-char (or pos (point)))
14674 (save-match-data
14675 (catch 'done
14676 (condition-case nil
14677 (progn
14678 (org-back-to-heading t)
14679 (while (not (equal lastpos (point)))
14680 (setq lastpos (point))
14681 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14682 (setq ltags (org-split-string
14683 (match-string-no-properties 1) ":"))
14684 (when parent
14685 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14686 (setq tags (append
14687 (if parent
14688 (org-remove-uninherited-tags ltags)
14689 ltags)
14690 tags)))
14691 (or org-use-tag-inheritance (throw 'done t))
14692 (when local (throw 'done t))
14693 (or (org-up-heading-safe) (error nil))
14694 (setq parent t)))
14695 (error nil)))))
14696 (if local
14697 tags
14698 (reverse (delete-dups
14699 (reverse (append
14700 (org-remove-uninherited-tags
14701 org-file-tags)
14702 tags)))))))))
14704 (defun org-add-prop-inherited (s)
14705 (add-text-properties 0 (length s) '(inherited t) s)
14708 (defun org-toggle-tag (tag &optional onoff)
14709 "Toggle the tag TAG for the current line.
14710 If ONOFF is `on' or `off', don't toggle but set to this state."
14711 (save-excursion
14712 (org-back-to-heading t)
14713 (let ((current
14714 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14715 (line-end-position) t)
14716 (let ((tags (match-string 1)))
14717 ;; Clear current tags.
14718 (replace-match "")
14719 ;; Reverse the tags list so any new tag is appended to
14720 ;; the current list of tags.
14721 (nreverse (org-split-string tags ":")))))
14722 res)
14723 (pcase onoff
14724 (`off (setq current (delete tag current)))
14725 ((or `on (guard (not (member tag current))))
14726 (setq res t)
14727 (cl-pushnew tag current :test #'equal))
14728 (_ (setq current (delete tag current))))
14729 (end-of-line)
14730 (if current
14731 (progn
14732 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14733 (org-set-tags nil t))
14734 (delete-horizontal-space))
14735 (run-hooks 'org-after-tags-change-hook)
14736 res)))
14738 (defun org--align-tags-here (to-col)
14739 "Align tags on the current headline to TO-COL.
14740 Assume point is on a headline."
14741 (let ((pos (point)))
14742 (beginning-of-line)
14743 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14744 (>= pos (match-beginning 2)))
14745 ;; No tags or point within tags: do not align.
14746 (goto-char pos)
14747 (goto-char (match-beginning 1))
14748 (let ((shift (max (- (if (>= to-col 0) to-col
14749 (- (abs to-col) (string-width (match-string 2))))
14750 (current-column))
14751 1)))
14752 (replace-match (make-string shift ?\s) nil nil nil 1)
14753 ;; Preserve initial position, if possible. In any case, stop
14754 ;; before tags.
14755 (when (< pos (point)) (goto-char pos))))))
14757 (defun org-set-tags-command (&optional arg just-align)
14758 "Call the set-tags command for the current entry."
14759 (interactive "P")
14760 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14761 (org-set-tags arg just-align)
14762 (save-excursion
14763 (unless (and (org-region-active-p)
14764 org-loop-over-headlines-in-active-region)
14765 (org-back-to-heading t))
14766 (org-set-tags arg just-align))))
14768 (defun org-set-tags-to (data)
14769 "Set the tags of the current entry to DATA, replacing the current tags.
14770 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14771 If DATA is nil or the empty string, any tags will be removed."
14772 (interactive "sTags: ")
14773 (setq data
14774 (cond
14775 ((eq data nil) "")
14776 ((equal data "") "")
14777 ((stringp data)
14778 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14779 ":"))
14780 ((listp data)
14781 (concat ":" (mapconcat 'identity data ":") ":"))))
14782 (when data
14783 (save-excursion
14784 (org-back-to-heading t)
14785 (when (let ((case-fold-search nil))
14786 (looking-at org-complex-heading-regexp))
14787 (if (match-end 5)
14788 (progn
14789 (goto-char (match-beginning 5))
14790 (insert data)
14791 (delete-region (point) (point-at-eol))
14792 (org-set-tags nil 'align))
14793 (goto-char (point-at-eol))
14794 (insert " " data)
14795 (org-set-tags nil 'align)))
14796 (beginning-of-line 1)
14797 (when (looking-at ".*?\\([ \t]+\\)$")
14798 (delete-region (match-beginning 1) (match-end 1))))))
14800 (defun org-align-all-tags ()
14801 "Align the tags in all headings."
14802 (interactive)
14803 (save-excursion
14804 (or (ignore-errors (org-back-to-heading t))
14805 (outline-next-heading))
14806 (if (org-at-heading-p)
14807 (org-set-tags t)
14808 (message "No headings"))))
14810 (defvar org-indent-indentation-per-level)
14811 (defun org-set-tags (&optional arg just-align)
14812 "Set the tags for the current headline.
14813 With prefix ARG, realign all tags in headings in the current buffer.
14814 When JUST-ALIGN is non-nil, only align tags."
14815 (interactive "P")
14816 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14817 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14818 'region-start-level
14819 'region))
14820 org-loop-over-headlines-in-active-region)
14821 (org-map-entries
14822 ;; We don't use ARG and JUST-ALIGN here because these args
14823 ;; are not useful when looping over headlines.
14824 #'org-set-tags
14825 org-loop-over-headlines-in-active-region
14827 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14828 (let ((org-setting-tags t))
14829 (if arg
14830 (save-excursion
14831 (goto-char (point-min))
14832 (while (re-search-forward org-outline-regexp-bol nil t)
14833 (org-set-tags nil t)
14834 (end-of-line))
14835 (message "All tags realigned to column %d" org-tags-column))
14836 (let* ((current (org-get-tags-string))
14837 (tags
14838 (if just-align current
14839 ;; Get a new set of tags from the user.
14840 (save-excursion
14841 (let* ((seen)
14842 (table
14843 (setq
14844 org-last-tags-completion-table
14845 ;; Uniquify tags in alists, yet preserve
14846 ;; structure (i.e., keywords).
14847 (delq nil
14848 (mapcar
14849 (lambda (pair)
14850 (let ((head (car pair)))
14851 (cond ((symbolp head) pair)
14852 ((member head seen) nil)
14853 (t (push head seen)
14854 pair))))
14855 (append
14856 (or org-current-tag-alist
14857 (org-get-buffer-tags))
14858 (and
14859 org-complete-tags-always-offer-all-agenda-tags
14860 (org-global-tags-completion-table
14861 (org-agenda-files))))))))
14862 (current-tags (org-split-string current ":"))
14863 (inherited-tags
14864 (nreverse (nthcdr (length current-tags)
14865 (nreverse (org-get-tags-at))))))
14866 (replace-regexp-in-string
14867 "\\([-+&]+\\|,\\)"
14869 (if (or (eq t org-use-fast-tag-selection)
14870 (and org-use-fast-tag-selection
14871 (delq nil (mapcar #'cdr table))))
14872 (org-fast-tag-selection
14873 current-tags inherited-tags table
14874 (and org-fast-tag-selection-include-todo
14875 org-todo-key-alist))
14876 (let ((org-add-colon-after-tag-completion
14877 (< 1 (length table))))
14878 (org-trim
14879 (completing-read
14880 "Tags: "
14881 #'org-tags-completion-function
14882 nil nil current 'org-tags-history))))))))))
14884 (when org-tags-sort-function
14885 (setq tags
14886 (mapconcat
14887 #'identity
14888 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14889 org-tags-sort-function)
14890 ":")))
14892 (if (or (string= ":" tags)
14893 (string= "::" tags))
14894 (setq tags ""))
14895 (if (not (org-string-nw-p tags)) (setq tags "")
14896 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14897 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14899 ;; Insert new tags at the correct column.
14900 (unless (equal current tags)
14901 (save-excursion
14902 (beginning-of-line)
14903 (let ((case-fold-search nil))
14904 (looking-at org-complex-heading-regexp))
14905 ;; Remove current tags, if any.
14906 (when (match-end 5) (replace-match "" nil nil nil 5))
14907 ;; Insert new tags, if any. Otherwise, remove trailing
14908 ;; white spaces.
14909 (end-of-line)
14910 (if (not (equal tags ""))
14911 ;; When text is being inserted on an invisible
14912 ;; region boundary, it can be inadvertently sucked
14913 ;; into invisibility.
14914 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14915 (skip-chars-backward " \t")
14916 (delete-region (point) (line-end-position)))))
14917 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14918 ;; is on.
14919 (unless (equal tags "")
14920 (let* ((level (save-excursion
14921 (beginning-of-line)
14922 (skip-chars-forward "\\*")))
14923 (offset (if (bound-and-true-p org-indent-mode)
14924 (* (1- org-indent-indentation-per-level)
14925 (1- level))
14927 (tags-column
14928 (+ org-tags-column
14929 (if (> org-tags-column 0) (- offset) offset))))
14930 (org--align-tags-here tags-column))))
14931 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14933 (defun org-change-tag-in-region (beg end tag off)
14934 "Add or remove TAG for each entry in the region.
14935 This works in the agenda, and also in an Org buffer."
14936 (interactive
14937 (list (region-beginning) (region-end)
14938 (let ((org-last-tags-completion-table
14939 (if (derived-mode-p 'org-mode)
14940 (org-uniquify
14941 (delq nil (append (org-get-buffer-tags)
14942 (org-global-tags-completion-table))))
14943 (org-global-tags-completion-table))))
14944 (completing-read
14945 "Tag: " 'org-tags-completion-function nil nil nil
14946 'org-tags-history))
14947 (progn
14948 (message "[s]et or [r]emove? ")
14949 (equal (read-char-exclusive) ?r))))
14950 (when (fboundp 'deactivate-mark) (deactivate-mark))
14951 (let ((agendap (equal major-mode 'org-agenda-mode))
14952 l1 l2 m buf pos newhead (cnt 0))
14953 (goto-char end)
14954 (setq l2 (1- (org-current-line)))
14955 (goto-char beg)
14956 (setq l1 (org-current-line))
14957 (cl-loop for l from l1 to l2 do
14958 (org-goto-line l)
14959 (setq m (get-text-property (point) 'org-hd-marker))
14960 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14961 (and agendap m))
14962 (setq buf (if agendap (marker-buffer m) (current-buffer))
14963 pos (if agendap m (point)))
14964 (with-current-buffer buf
14965 (save-excursion
14966 (save-restriction
14967 (goto-char pos)
14968 (setq cnt (1+ cnt))
14969 (org-toggle-tag tag (if off 'off 'on))
14970 (setq newhead (org-get-heading)))))
14971 (and agendap (org-agenda-change-all-lines newhead m))))
14972 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14974 (defun org-tags-completion-function (string _predicate &optional flag)
14975 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14976 (confirm (lambda (x) (stringp (car x)))))
14977 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14978 (setq s1 (match-string 1 string)
14979 s2 (match-string 2 string))
14980 (setq s1 "" s2 string))
14981 (cond
14982 ((eq flag nil)
14983 ;; try completion
14984 (setq rtn (try-completion s2 ctable confirm))
14985 (when (stringp rtn)
14986 (setq rtn
14987 (concat s1 s2 (substring rtn (length s2))
14988 (if (and org-add-colon-after-tag-completion
14989 (assoc rtn ctable))
14990 ":" ""))))
14991 rtn)
14992 ((eq flag t)
14993 ;; all-completions
14994 (all-completions s2 ctable confirm))
14995 ((eq flag 'lambda)
14996 ;; exact match?
14997 (assoc s2 ctable)))))
14999 (defun org-fast-tag-insert (kwd tags face &optional end)
15000 "Insert KDW, and the TAGS, the latter with face FACE.
15001 Also insert END."
15002 (insert (format "%-12s" (concat kwd ":"))
15003 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15004 (or end "")))
15006 (defun org-fast-tag-show-exit (flag)
15007 (save-excursion
15008 (org-goto-line 3)
15009 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15010 (replace-match ""))
15011 (when flag
15012 (end-of-line 1)
15013 (org-move-to-column (- (window-width) 19) t)
15014 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15016 (defun org-set-current-tags-overlay (current prefix)
15017 "Add an overlay to CURRENT tag with PREFIX."
15018 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15019 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15020 (org-overlay-display org-tags-overlay (concat prefix s))))
15022 (defvar org-last-tag-selection-key nil)
15023 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15024 "Fast tag selection with single keys.
15025 CURRENT is the current list of tags in the headline, INHERITED is the
15026 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15027 possibly with grouping information. TODO-TABLE is a similar table with
15028 TODO keywords, should these have keys assigned to them.
15029 If the keys are nil, a-z are automatically assigned.
15030 Returns the new tags string, or nil to not change the current settings."
15031 (let* ((fulltable (append table todo-table))
15032 (maxlen (apply 'max (mapcar
15033 (lambda (x)
15034 (if (stringp (car x)) (string-width (car x)) 0))
15035 fulltable)))
15036 (buf (current-buffer))
15037 (expert (eq org-fast-tag-selection-single-key 'expert))
15038 (buffer-tags nil)
15039 (fwidth (+ maxlen 3 1 3))
15040 (ncol (/ (- (window-width) 4) fwidth))
15041 (i-face 'org-done)
15042 (c-face 'org-todo)
15043 tg cnt e c char c1 c2 ntable tbl rtn
15044 ov-start ov-end ov-prefix
15045 (exit-after-next org-fast-tag-selection-single-key)
15046 (done-keywords org-done-keywords)
15047 groups ingroup intaggroup)
15048 (save-excursion
15049 (beginning-of-line 1)
15050 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15051 (setq ov-start (match-beginning 1)
15052 ov-end (match-end 1)
15053 ov-prefix "")
15054 (setq ov-start (1- (point-at-eol))
15055 ov-end (1+ ov-start))
15056 (skip-chars-forward "^\n\r")
15057 (setq ov-prefix
15058 (concat
15059 (buffer-substring (1- (point)) (point))
15060 (if (> (current-column) org-tags-column)
15062 (make-string (- org-tags-column (current-column)) ?\ ))))))
15063 (move-overlay org-tags-overlay ov-start ov-end)
15064 (save-window-excursion
15065 (if expert
15066 (set-buffer (get-buffer-create " *Org tags*"))
15067 (delete-other-windows)
15068 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15069 (org-switch-to-buffer-other-window " *Org tags*"))
15070 (erase-buffer)
15071 (setq-local org-done-keywords done-keywords)
15072 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15073 (org-fast-tag-insert "Current" current c-face "\n\n")
15074 (org-fast-tag-show-exit exit-after-next)
15075 (org-set-current-tags-overlay current ov-prefix)
15076 (setq tbl fulltable char ?a cnt 0)
15077 (while (setq e (pop tbl))
15078 (cond
15079 ((eq (car e) :startgroup)
15080 (push '() groups) (setq ingroup t)
15081 (unless (zerop cnt)
15082 (setq cnt 0)
15083 (insert "\n"))
15084 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15085 ((eq (car e) :endgroup)
15086 (setq ingroup nil cnt 0)
15087 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15088 ((eq (car e) :startgrouptag)
15089 (setq intaggroup t)
15090 (unless (zerop cnt)
15091 (setq cnt 0)
15092 (insert "\n"))
15093 (insert "[ "))
15094 ((eq (car e) :endgrouptag)
15095 (setq intaggroup nil cnt 0)
15096 (insert "]\n"))
15097 ((equal e '(:newline))
15098 (unless (zerop cnt)
15099 (setq cnt 0)
15100 (insert "\n")
15101 (setq e (car tbl))
15102 (while (equal (car tbl) '(:newline))
15103 (insert "\n")
15104 (setq tbl (cdr tbl)))))
15105 ((equal e '(:grouptags)) (insert " : "))
15107 (setq tg (copy-sequence (car e)) c2 nil)
15108 (if (cdr e)
15109 (setq c (cdr e))
15110 ;; automatically assign a character.
15111 (setq c1 (string-to-char
15112 (downcase (substring
15113 tg (if (= (string-to-char tg) ?@) 1 0)))))
15114 (if (or (rassoc c1 ntable) (rassoc c1 table))
15115 (while (or (rassoc char ntable) (rassoc char table))
15116 (setq char (1+ char)))
15117 (setq c2 c1))
15118 (setq c (or c2 char)))
15119 (when ingroup (push tg (car groups)))
15120 (setq tg (org-add-props tg nil 'face
15121 (cond
15122 ((not (assoc tg table))
15123 (org-get-todo-face tg))
15124 ((member tg current) c-face)
15125 ((member tg inherited) i-face))))
15126 (when (equal (caar tbl) :grouptags)
15127 (org-add-props tg nil 'face 'org-tag-group))
15128 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15129 (insert "[" c "] " tg (make-string
15130 (- fwidth 4 (length tg)) ?\ ))
15131 (push (cons tg c) ntable)
15132 (when (= (cl-incf cnt) ncol)
15133 (insert "\n")
15134 (when (or ingroup intaggroup) (insert " "))
15135 (setq cnt 0)))))
15136 (setq ntable (nreverse ntable))
15137 (insert "\n")
15138 (goto-char (point-min))
15139 (unless expert (org-fit-window-to-buffer))
15140 (setq rtn
15141 (catch 'exit
15142 (while t
15143 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15144 (if (not groups) "no " "")
15145 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15146 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15147 (setq org-last-tag-selection-key c)
15148 (cond
15149 ((= c ?\r) (throw 'exit t))
15150 ((= c ?!)
15151 (setq groups (not groups))
15152 (goto-char (point-min))
15153 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15154 ((= c ?\C-c)
15155 (if (not expert)
15156 (org-fast-tag-show-exit
15157 (setq exit-after-next (not exit-after-next)))
15158 (setq expert nil)
15159 (delete-other-windows)
15160 (set-window-buffer (split-window-vertically) " *Org tags*")
15161 (org-switch-to-buffer-other-window " *Org tags*")
15162 (org-fit-window-to-buffer)))
15163 ((or (= c ?\C-g)
15164 (and (= c ?q) (not (rassoc c ntable))))
15165 (delete-overlay org-tags-overlay)
15166 (setq quit-flag t))
15167 ((= c ?\ )
15168 (setq current nil)
15169 (when exit-after-next (setq exit-after-next 'now)))
15170 ((= c ?\t)
15171 (condition-case nil
15172 (setq tg (completing-read
15173 "Tag: "
15174 (or buffer-tags
15175 (with-current-buffer buf
15176 (setq buffer-tags
15177 (org-get-buffer-tags))))))
15178 (quit (setq tg "")))
15179 (when (string-match "\\S-" tg)
15180 (cl-pushnew (list tg) buffer-tags :test #'equal)
15181 (if (member tg current)
15182 (setq current (delete tg current))
15183 (push tg current)))
15184 (when exit-after-next (setq exit-after-next 'now)))
15185 ((setq e (rassoc c todo-table) tg (car e))
15186 (with-current-buffer buf
15187 (save-excursion (org-todo tg)))
15188 (when exit-after-next (setq exit-after-next 'now)))
15189 ((setq e (rassoc c ntable) tg (car e))
15190 (if (member tg current)
15191 (setq current (delete tg current))
15192 (cl-loop for g in groups do
15193 (when (member tg g)
15194 (dolist (x g) (setq current (delete x current)))))
15195 (push tg current))
15196 (when exit-after-next (setq exit-after-next 'now))))
15198 ;; Create a sorted list
15199 (setq current
15200 (sort current
15201 (lambda (a b)
15202 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15203 (when (eq exit-after-next 'now) (throw 'exit t))
15204 (goto-char (point-min))
15205 (beginning-of-line 2)
15206 (delete-region (point) (point-at-eol))
15207 (org-fast-tag-insert "Current" current c-face)
15208 (org-set-current-tags-overlay current ov-prefix)
15209 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15210 (setq tg (match-string 1))
15211 (add-text-properties
15212 (match-beginning 1) (match-end 1)
15213 (list 'face
15214 (cond
15215 ((member tg current) c-face)
15216 ((member tg inherited) i-face)
15217 (t (get-text-property (match-beginning 1) 'face))))))
15218 (goto-char (point-min)))))
15219 (delete-overlay org-tags-overlay)
15220 (if rtn
15221 (mapconcat 'identity current ":")
15222 nil))))
15224 (defun org-get-tags-string ()
15225 "Get the TAGS string in the current headline."
15226 (unless (org-at-heading-p t)
15227 (user-error "Not on a heading"))
15228 (save-excursion
15229 (beginning-of-line 1)
15230 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15231 (match-string-no-properties 1)
15232 "")))
15234 (defun org-get-tags ()
15235 "Get the list of tags specified in the current headline."
15236 (org-split-string (org-get-tags-string) ":"))
15238 (defun org-get-buffer-tags ()
15239 "Get a table of all tags used in the buffer, for completion."
15240 (org-with-wide-buffer
15241 (goto-char (point-min))
15242 (let ((tag-re (concat org-outline-regexp-bol
15243 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15244 tags)
15245 (while (re-search-forward tag-re nil t)
15246 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15247 (push tag tags)))
15248 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15250 ;;;; The mapping API
15252 (defvar org-agenda-skip-comment-trees)
15253 (defvar org-agenda-skip-function)
15254 (defun org-map-entries (func &optional match scope &rest skip)
15255 "Call FUNC at each headline selected by MATCH in SCOPE.
15257 FUNC is a function or a lisp form. The function will be called without
15258 arguments, with the cursor positioned at the beginning of the headline.
15259 The return values of all calls to the function will be collected and
15260 returned as a list.
15262 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15263 does not need to preserve point. After evaluation, the cursor will be
15264 moved to the end of the line (presumably of the headline of the
15265 processed entry) and search continues from there. Under some
15266 circumstances, this may not produce the wanted results. For example,
15267 if you have removed (e.g. archived) the current (sub)tree it could
15268 mean that the next entry will be skipped entirely. In such cases, you
15269 can specify the position from where search should continue by making
15270 FUNC set the variable `org-map-continue-from' to the desired buffer
15271 position.
15273 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15274 Only headlines that are matched by this query will be considered during
15275 the iteration. When MATCH is nil or t, all headlines will be
15276 visited by the iteration.
15278 SCOPE determines the scope of this command. It can be any of:
15280 nil The current buffer, respecting the restriction if any
15281 tree The subtree started with the entry at point
15282 region The entries within the active region, if any
15283 region-start-level
15284 The entries within the active region, but only those at
15285 the same level than the first one.
15286 file The current buffer, without restriction
15287 file-with-archives
15288 The current buffer, and any archives associated with it
15289 agenda All agenda files
15290 agenda-with-archives
15291 All agenda files with any archive files associated with them
15292 \(file1 file2 ...)
15293 If this is a list, all files in the list will be scanned
15295 The remaining args are treated as settings for the skipping facilities of
15296 the scanner. The following items can be given here:
15298 archive skip trees with the archive tag
15299 comment skip trees with the COMMENT keyword
15300 function or Emacs Lisp form:
15301 will be used as value for `org-agenda-skip-function', so
15302 whenever the function returns a position, FUNC will not be
15303 called for that entry and search will continue from the
15304 position returned
15306 If your function needs to retrieve the tags including inherited tags
15307 at the *current* entry, you can use the value of the variable
15308 `org-scanner-tags' which will be much faster than getting the value
15309 with `org-get-tags-at'. If your function gets properties with
15310 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15311 to t around the call to `org-entry-properties' to get the same speedup.
15312 Note that if your function moves around to retrieve tags and properties at
15313 a *different* entry, you cannot use these techniques."
15314 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15315 (not (org-region-active-p)))
15316 (let* ((org-agenda-archives-mode nil) ; just to make sure
15317 (org-agenda-skip-archived-trees (memq 'archive skip))
15318 (org-agenda-skip-comment-trees (memq 'comment skip))
15319 (org-agenda-skip-function
15320 (car (org-delete-all '(comment archive) skip)))
15321 (org-tags-match-list-sublevels t)
15322 (start-level (eq scope 'region-start-level))
15323 matcher res
15324 org-todo-keywords-for-agenda
15325 org-done-keywords-for-agenda
15326 org-todo-keyword-alist-for-agenda
15327 org-tag-alist-for-agenda
15328 org--matcher-tags-todo-only)
15330 (cond
15331 ((eq match t) (setq matcher t))
15332 ((eq match nil) (setq matcher t))
15333 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15335 (save-excursion
15336 (save-restriction
15337 (cond ((eq scope 'tree)
15338 (org-back-to-heading t)
15339 (org-narrow-to-subtree)
15340 (setq scope nil))
15341 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15342 (org-region-active-p))
15343 ;; If needed, set start-level to a string like "2"
15344 (when start-level
15345 (save-excursion
15346 (goto-char (region-beginning))
15347 (unless (org-at-heading-p) (outline-next-heading))
15348 (setq start-level (org-current-level))))
15349 (narrow-to-region (region-beginning)
15350 (save-excursion
15351 (goto-char (region-end))
15352 (unless (and (bolp) (org-at-heading-p))
15353 (outline-next-heading))
15354 (point)))
15355 (setq scope nil)))
15357 (if (not scope)
15358 (progn
15359 (org-agenda-prepare-buffers
15360 (and buffer-file-name (list buffer-file-name)))
15361 (setq res
15362 (org-scan-tags
15363 func matcher org--matcher-tags-todo-only start-level)))
15364 ;; Get the right scope
15365 (cond
15366 ((and scope (listp scope) (symbolp (car scope)))
15367 (setq scope (eval scope)))
15368 ((eq scope 'agenda)
15369 (setq scope (org-agenda-files t)))
15370 ((eq scope 'agenda-with-archives)
15371 (setq scope (org-agenda-files t))
15372 (setq scope (org-add-archive-files scope)))
15373 ((eq scope 'file)
15374 (setq scope (and buffer-file-name (list buffer-file-name))))
15375 ((eq scope 'file-with-archives)
15376 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15377 (org-agenda-prepare-buffers scope)
15378 (dolist (file scope)
15379 (with-current-buffer (org-find-base-buffer-visiting file)
15380 (org-with-wide-buffer
15381 (goto-char (point-min))
15382 (setq res
15383 (append
15385 (org-scan-tags
15386 func matcher org--matcher-tags-todo-only)))))))))
15387 res)))
15389 ;;; Properties API
15391 (defconst org-special-properties
15392 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15393 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15394 "The special properties valid in Org mode.
15395 These are properties that are not defined in the property drawer,
15396 but in some other way.")
15398 (defconst org-default-properties
15399 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15400 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15401 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15402 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15403 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15404 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15405 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15406 "Some properties that are used by Org mode for various purposes.
15407 Being in this list makes sure that they are offered for completion.")
15409 (defun org--valid-property-p (property)
15410 "Non nil when string PROPERTY is a valid property name."
15411 (not
15412 (or (equal property "")
15413 (string-match-p "\\s-" property))))
15415 (defun org--update-property-plist (key val props)
15416 "Associate KEY to VAL in alist PROPS.
15417 Modifications are made by side-effect. Return new alist."
15418 (let* ((appending (string= (substring key -1) "+"))
15419 (key (if appending (substring key 0 -1) key))
15420 (old (assoc-string key props t)))
15421 (if (not old) (cons (cons key val) props)
15422 (setcdr old (if appending (concat (cdr old) " " val) val))
15423 props)))
15425 (defun org-get-property-block (&optional beg force)
15426 "Return the (beg . end) range of the body of the property drawer.
15427 BEG is the beginning of the current subtree, or of the part
15428 before the first headline. If it is not given, it will be found.
15429 If the drawer does not exist, create it if FORCE is non-nil, or
15430 return nil."
15431 (org-with-wide-buffer
15432 (when beg (goto-char beg))
15433 (unless (org-before-first-heading-p)
15434 (let ((beg (cond (beg)
15435 ((or (not (featurep 'org-inlinetask))
15436 (org-inlinetask-in-task-p))
15437 (org-back-to-heading t))
15438 (t (org-with-limited-levels (org-back-to-heading t))))))
15439 (forward-line)
15440 (when (looking-at-p org-planning-line-re) (forward-line))
15441 (cond ((looking-at org-property-drawer-re)
15442 (forward-line)
15443 (cons (point) (progn (goto-char (match-end 0))
15444 (line-beginning-position))))
15445 (force
15446 (goto-char beg)
15447 (org-insert-property-drawer)
15448 (let ((pos (save-excursion (search-forward ":END:")
15449 (line-beginning-position))))
15450 (cons pos pos))))))))
15452 (defun org-at-property-p ()
15453 "Non-nil when point is inside a property drawer.
15454 See `org-property-re' for match data, if applicable."
15455 (save-excursion
15456 (beginning-of-line)
15457 (and (looking-at org-property-re)
15458 (let ((property-drawer (save-match-data (org-get-property-block))))
15459 (and property-drawer
15460 (>= (point) (car property-drawer))
15461 (< (point) (cdr property-drawer)))))))
15463 (defun org-property-action ()
15464 "Do an action on properties."
15465 (interactive)
15466 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15467 (let ((c (read-char-exclusive)))
15468 (cl-case c
15469 (?s (call-interactively #'org-set-property))
15470 (?d (call-interactively #'org-delete-property))
15471 (?D (call-interactively #'org-delete-property-globally))
15472 (?c (call-interactively #'org-compute-property-at-point))
15473 (otherwise (user-error "No such property action %c" c)))))
15475 (defun org-inc-effort ()
15476 "Increment the value of the effort property in the current entry."
15477 (interactive)
15478 (org-set-effort nil t))
15480 (defvar org-clock-effort) ; Defined in org-clock.el.
15481 (defvar org-clock-current-task) ; Defined in org-clock.el.
15482 (defun org-set-effort (&optional value increment)
15483 "Set the effort property of the current entry.
15484 With numerical prefix arg, use the nth allowed value, 0 stands for the
15485 10th allowed value.
15487 When INCREMENT is non-nil, set the property to the next allowed value."
15488 (interactive "P")
15489 (when (equal value 0) (setq value 10))
15490 (let* ((completion-ignore-case t)
15491 (prop org-effort-property)
15492 (cur (org-entry-get nil prop))
15493 (allowed (org-property-get-allowed-values nil prop 'table))
15494 (existing (mapcar 'list (org-property-values prop)))
15495 (heading (nth 4 (org-heading-components)))
15497 (val (cond
15498 ((stringp value) value)
15499 ((and allowed (integerp value))
15500 (or (car (nth (1- value) allowed))
15501 (car (org-last allowed))))
15502 ((and allowed increment)
15503 (or (cl-caadr (member (list cur) allowed))
15504 (user-error "Allowed effort values are not set")))
15505 (allowed
15506 (message "Select 1-9,0, [RET%s]: %s"
15507 (if cur (concat "=" cur) "")
15508 (mapconcat 'car allowed " "))
15509 (setq rpl (read-char-exclusive))
15510 (if (equal rpl ?\r)
15512 (setq rpl (- rpl ?0))
15513 (when (equal rpl 0) (setq rpl 10))
15514 (if (and (> rpl 0) (<= rpl (length allowed)))
15515 (car (nth (1- rpl) allowed))
15516 (org-completing-read "Effort: " allowed nil))))
15518 (org-completing-read
15519 (concat "Effort" (and cur (string-match "\\S-" cur)
15520 (concat " [" cur "]"))
15521 ": ")
15522 existing nil nil "" nil cur)))))
15523 (unless (equal (org-entry-get nil prop) val)
15524 (org-entry-put nil prop val))
15525 (org-refresh-property
15526 '((effort . identity)
15527 (effort-minutes . org-duration-to-minutes))
15528 val)
15529 (when (equal heading (bound-and-true-p org-clock-current-task))
15530 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15531 (org-clock-update-mode-line))
15532 (message "%s is now %s" prop val)))
15534 (defun org-entry-properties (&optional pom which)
15535 "Get all properties of the current entry.
15537 When POM is a buffer position, get all properties from the entry
15538 there instead.
15540 This includes the TODO keyword, the tags, time strings for
15541 deadline, scheduled, and clocking, and any additional properties
15542 defined in the entry.
15544 If WHICH is nil or `all', get all properties. If WHICH is
15545 `special' or `standard', only get that subclass. If WHICH is
15546 a string, only get that property.
15548 Return value is an alist. Keys are properties, as upcased
15549 strings."
15550 (org-with-point-at pom
15551 (when (and (derived-mode-p 'org-mode)
15552 (ignore-errors (org-back-to-heading t)))
15553 (catch 'exit
15554 (let* ((beg (point))
15555 (specific (and (stringp which) (upcase which)))
15556 (which (cond ((not specific) which)
15557 ((member specific org-special-properties) 'special)
15558 (t 'standard)))
15559 props)
15560 ;; Get the special properties, like TODO and TAGS.
15561 (when (memq which '(nil all special))
15562 (when (or (not specific) (string= specific "CLOCKSUM"))
15563 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15564 (when clocksum
15565 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15566 props)))
15567 (when specific (throw 'exit props)))
15568 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15569 (let ((clocksumt (get-text-property (point)
15570 :org-clock-minutes-today)))
15571 (when clocksumt
15572 (push (cons "CLOCKSUM_T"
15573 (org-duration-from-minutes clocksumt))
15574 props)))
15575 (when specific (throw 'exit props)))
15576 (when (or (not specific) (string= specific "ITEM"))
15577 (let ((case-fold-search nil))
15578 (when (looking-at org-complex-heading-regexp)
15579 (push (cons "ITEM"
15580 (let ((title (match-string-no-properties 4)))
15581 (if (org-string-nw-p title)
15582 (org-remove-tabs title)
15583 "")))
15584 props)))
15585 (when specific (throw 'exit props)))
15586 (when (or (not specific) (string= specific "TODO"))
15587 (let ((case-fold-search nil))
15588 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15589 (push (cons "TODO" (match-string-no-properties 2)) props)))
15590 (when specific (throw 'exit props)))
15591 (when (or (not specific) (string= specific "PRIORITY"))
15592 (push (cons "PRIORITY"
15593 (if (looking-at org-priority-regexp)
15594 (match-string-no-properties 2)
15595 (char-to-string org-default-priority)))
15596 props)
15597 (when specific (throw 'exit props)))
15598 (when (or (not specific) (string= specific "FILE"))
15599 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15600 props)
15601 (when specific (throw 'exit props)))
15602 (when (or (not specific) (string= specific "TAGS"))
15603 (let ((value (org-string-nw-p (org-get-tags-string))))
15604 (when value (push (cons "TAGS" value) props)))
15605 (when specific (throw 'exit props)))
15606 (when (or (not specific) (string= specific "ALLTAGS"))
15607 (let ((value (org-get-tags-at)))
15608 (when value
15609 (push (cons "ALLTAGS"
15610 (format ":%s:" (mapconcat #'identity value ":")))
15611 props)))
15612 (when specific (throw 'exit props)))
15613 (when (or (not specific) (string= specific "BLOCKED"))
15614 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15615 (when specific (throw 'exit props)))
15616 (when (or (not specific)
15617 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15618 (forward-line)
15619 (when (looking-at-p org-planning-line-re)
15620 (end-of-line)
15621 (let ((bol (line-beginning-position))
15622 ;; Backward compatibility: time keywords used to
15623 ;; be configurable (before 8.3). Make sure we
15624 ;; get the correct keyword.
15625 (key-assoc `(("CLOSED" . ,org-closed-string)
15626 ("DEADLINE" . ,org-deadline-string)
15627 ("SCHEDULED" . ,org-scheduled-string))))
15628 (dolist (pair (if specific (list (assoc specific key-assoc))
15629 key-assoc))
15630 (save-excursion
15631 (when (search-backward (cdr pair) bol t)
15632 (goto-char (match-end 0))
15633 (skip-chars-forward " \t")
15634 (and (looking-at org-ts-regexp-both)
15635 (push (cons (car pair)
15636 (match-string-no-properties 0))
15637 props)))))))
15638 (when specific (throw 'exit props)))
15639 (when (or (not specific)
15640 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15641 (let ((find-ts
15642 (lambda (end ts)
15643 ;; Fix next time-stamp before END. TS is the
15644 ;; list of time-stamps found so far.
15645 (let ((ts ts)
15646 (regexp (cond
15647 ((string= specific "TIMESTAMP")
15648 org-ts-regexp)
15649 ((string= specific "TIMESTAMP_IA")
15650 org-ts-regexp-inactive)
15651 ((assoc "TIMESTAMP_IA" ts)
15652 org-ts-regexp)
15653 ((assoc "TIMESTAMP" ts)
15654 org-ts-regexp-inactive)
15655 (t org-ts-regexp-both))))
15656 (catch 'next
15657 (while (re-search-forward regexp end t)
15658 (backward-char)
15659 (let ((object (org-element-context)))
15660 ;; Accept to match timestamps in node
15661 ;; properties, too.
15662 (when (memq (org-element-type object)
15663 '(node-property timestamp))
15664 (let ((type
15665 (org-element-property :type object)))
15666 (cond
15667 ((and (memq type '(active active-range))
15668 (not (equal specific "TIMESTAMP_IA")))
15669 (unless (assoc "TIMESTAMP" ts)
15670 (push (cons "TIMESTAMP"
15671 (org-element-property
15672 :raw-value object))
15674 (when specific (throw 'exit ts))))
15675 ((and (memq type '(inactive inactive-range))
15676 (not (string= specific "TIMESTAMP")))
15677 (unless (assoc "TIMESTAMP_IA" ts)
15678 (push (cons "TIMESTAMP_IA"
15679 (org-element-property
15680 :raw-value object))
15682 (when specific (throw 'exit ts))))))
15683 ;; Both timestamp types are found,
15684 ;; move to next part.
15685 (when (= (length ts) 2) (throw 'next ts)))))
15686 ts)))))
15687 (goto-char beg)
15688 ;; First look for timestamps within headline.
15689 (let ((ts (funcall find-ts (line-end-position) nil)))
15690 (if (= (length ts) 2) (setq props (nconc ts props))
15691 ;; Then find timestamps in the section, skipping
15692 ;; planning line.
15693 (let ((end (save-excursion (outline-next-heading))))
15694 (forward-line)
15695 (when (looking-at-p org-planning-line-re) (forward-line))
15696 (setq props (nconc (funcall find-ts end ts) props))))))))
15697 ;; Get the standard properties, like :PROP:.
15698 (when (memq which '(nil all standard))
15699 ;; If we are looking after a specific property, delegate
15700 ;; to `org-entry-get', which is faster. However, make an
15701 ;; exception for "CATEGORY", since it can be also set
15702 ;; through keywords (i.e. #+CATEGORY).
15703 (if (and specific (not (equal specific "CATEGORY")))
15704 (let ((value (org-entry-get beg specific nil t)))
15705 (throw 'exit (and value (list (cons specific value)))))
15706 (let ((range (org-get-property-block beg)))
15707 (when range
15708 (let ((end (cdr range)) seen-base)
15709 (goto-char (car range))
15710 ;; Unlike to `org--update-property-plist', we
15711 ;; handle the case where base values is found
15712 ;; after its extension. We also forbid standard
15713 ;; properties to be named as special properties.
15714 (while (re-search-forward org-property-re end t)
15715 (let* ((key (upcase (match-string-no-properties 2)))
15716 (extendp (string-match-p "\\+\\'" key))
15717 (key-base (if extendp (substring key 0 -1) key))
15718 (value (match-string-no-properties 3)))
15719 (cond
15720 ((member-ignore-case key-base org-special-properties))
15721 (extendp
15722 (setq props
15723 (org--update-property-plist key value props)))
15724 ((member key seen-base))
15725 (t (push key seen-base)
15726 (let ((p (assoc-string key props t)))
15727 (if p (setcdr p (concat value " " (cdr p)))
15728 (push (cons key value) props))))))))))))
15729 (unless (assoc "CATEGORY" props)
15730 (push (cons "CATEGORY" (org-get-category beg)) props)
15731 (when (string= specific "CATEGORY") (throw 'exit props)))
15732 ;; Return value.
15733 props)))))
15735 (defun org--property-local-values (property literal-nil)
15736 "Return value for PROPERTY in current entry.
15737 Value is a list whose car is the base value for PROPERTY and cdr
15738 a list of accumulated values. Return nil if neither is found in
15739 the entry. Also return nil when PROPERTY is set to \"nil\",
15740 unless LITERAL-NIL is non-nil."
15741 (let ((range (org-get-property-block)))
15742 (when range
15743 (goto-char (car range))
15744 (let* ((case-fold-search t)
15745 (end (cdr range))
15746 (value
15747 ;; Base value.
15748 (save-excursion
15749 (let ((v (and (re-search-forward
15750 (org-re-property property nil t) end t)
15751 (match-string-no-properties 3))))
15752 (list (if literal-nil v (org-not-nil v)))))))
15753 ;; Find additional values.
15754 (let* ((property+ (org-re-property (concat property "+") nil t)))
15755 (while (re-search-forward property+ end t)
15756 (push (match-string-no-properties 3) value)))
15757 ;; Return final values.
15758 (and (not (equal value '(nil))) (nreverse value))))))
15760 (defun org--property-global-value (property literal-nil)
15761 "Return value for PROPERTY in current buffer.
15762 Return value is a string. Return nil if property is not set
15763 globally. Also return nil when PROPERTY is set to \"nil\",
15764 unless LITERAL-NIL is non-nil."
15765 (let ((global
15766 (cdr (or (assoc-string property org-file-properties t)
15767 (assoc-string property org-global-properties t)
15768 (assoc-string property org-global-properties-fixed t)))))
15769 (if literal-nil global (org-not-nil global))))
15771 (defun org-entry-get (pom property &optional inherit literal-nil)
15772 "Get value of PROPERTY for entry or content at point-or-marker POM.
15774 If INHERIT is non-nil and the entry does not have the property,
15775 then also check higher levels of the hierarchy. If INHERIT is
15776 the symbol `selective', use inheritance only if the setting in
15777 `org-use-property-inheritance' selects PROPERTY for inheritance.
15779 If the property is present but empty, the return value is the
15780 empty string. If the property is not present at all, nil is
15781 returned. In any other case, return the value as a string.
15782 Search is case-insensitive.
15784 If LITERAL-NIL is set, return the string value \"nil\" as
15785 a string, do not interpret it as the list atom nil. This is used
15786 for inheritance when a \"nil\" value can supersede a non-nil
15787 value higher up the hierarchy."
15788 (org-with-point-at pom
15789 (cond
15790 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15791 ;; We need a special property. Use `org-entry-properties' to
15792 ;; retrieve it, but specify the wanted property.
15793 (cdr (assoc-string property (org-entry-properties nil property))))
15794 ((and inherit
15795 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15796 (org-entry-get-with-inheritance property literal-nil))
15798 (let* ((local (org--property-local-values property literal-nil))
15799 (value (and local (mapconcat #'identity (delq nil local) " "))))
15800 (if literal-nil value (org-not-nil value)))))))
15802 (defun org-property-or-variable-value (var &optional inherit)
15803 "Check if there is a property fixing the value of VAR.
15804 If yes, return this value. If not, return the current value of the variable."
15805 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15806 (if (and prop (stringp prop) (string-match "\\S-" prop))
15807 (read prop)
15808 (symbol-value var))))
15810 (defun org-entry-delete (pom property)
15811 "Delete PROPERTY from entry at point-or-marker POM.
15812 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15813 non-nil when a property was removed."
15814 (org-with-point-at pom
15815 (pcase (org-get-property-block)
15816 (`(,begin . ,origin)
15817 (let* ((end (copy-marker origin))
15818 (re (org-re-property
15819 (concat (regexp-quote property) "\\+?") t t)))
15820 (goto-char begin)
15821 (while (re-search-forward re end t)
15822 (delete-region (match-beginning 0) (line-beginning-position 2)))
15823 ;; If drawer is empty, remove it altogether.
15824 (when (= begin end)
15825 (delete-region (line-beginning-position 0)
15826 (line-beginning-position 2)))
15827 ;; Return non-nil if some property was removed.
15828 (prog1 (/= end origin) (set-marker end nil))))
15829 (_ nil))))
15831 ;; Multi-values properties are properties that contain multiple values
15832 ;; These values are assumed to be single words, separated by whitespace.
15833 (defun org-entry-add-to-multivalued-property (pom property value)
15834 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15835 (let* ((old (org-entry-get pom property))
15836 (values (and old (split-string old))))
15837 (setq value (org-entry-protect-space value))
15838 (unless (member value values)
15839 (setq values (append values (list value)))
15840 (org-entry-put pom property (mapconcat #'identity values " ")))))
15842 (defun org-entry-remove-from-multivalued-property (pom property value)
15843 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15844 (let* ((old (org-entry-get pom property))
15845 (values (and old (split-string old))))
15846 (setq value (org-entry-protect-space value))
15847 (when (member value values)
15848 (setq values (delete value values))
15849 (org-entry-put pom property (mapconcat #'identity values " ")))))
15851 (defun org-entry-member-in-multivalued-property (pom property value)
15852 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15853 (let* ((old (org-entry-get pom property))
15854 (values (and old (split-string old))))
15855 (setq value (org-entry-protect-space value))
15856 (member value values)))
15858 (defun org-entry-get-multivalued-property (pom property)
15859 "Return a list of values in a multivalued property."
15860 (let* ((value (org-entry-get pom property))
15861 (values (and value (split-string value))))
15862 (mapcar #'org-entry-restore-space values)))
15864 (defun org-entry-put-multivalued-property (pom property &rest values)
15865 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15866 VALUES should be a list of strings. Spaces will be protected."
15867 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15868 (let* ((value (org-entry-get pom property))
15869 (values (and value (split-string value))))
15870 (mapcar #'org-entry-restore-space values)))
15872 (defun org-entry-protect-space (s)
15873 "Protect spaces and newline in string S."
15874 (while (string-match " " s)
15875 (setq s (replace-match "%20" t t s)))
15876 (while (string-match "\n" s)
15877 (setq s (replace-match "%0A" t t s)))
15880 (defun org-entry-restore-space (s)
15881 "Restore spaces and newline in string S."
15882 (while (string-match "%20" s)
15883 (setq s (replace-match " " t t s)))
15884 (while (string-match "%0A" s)
15885 (setq s (replace-match "\n" t t s)))
15888 (defvar org-entry-property-inherited-from (make-marker)
15889 "Marker pointing to the entry from where a property was inherited.
15890 Each call to `org-entry-get-with-inheritance' will set this marker to the
15891 location of the entry where the inheritance search matched. If there was
15892 no match, the marker will point nowhere.
15893 Note that also `org-entry-get' calls this function, if the INHERIT flag
15894 is set.")
15896 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15897 "Get PROPERTY of entry or content at point, search higher levels if needed.
15898 The search will stop at the first ancestor which has the property defined.
15899 If the value found is \"nil\", return nil to show that the property
15900 should be considered as undefined (this is the meaning of nil here).
15901 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15902 (move-marker org-entry-property-inherited-from nil)
15903 (org-with-wide-buffer
15904 (let (value)
15905 (catch 'exit
15906 (while t
15907 (let ((v (org--property-local-values property literal-nil)))
15908 (when v
15909 (setq value
15910 (concat (mapconcat #'identity (delq nil v) " ")
15911 (and value " ")
15912 value)))
15913 (cond
15914 ((car v)
15915 (org-back-to-heading t)
15916 (move-marker org-entry-property-inherited-from (point))
15917 (throw 'exit nil))
15918 ((org-up-heading-safe))
15920 (let ((global (org--property-global-value property literal-nil)))
15921 (cond ((not global))
15922 (value (setq value (concat global " " value)))
15923 (t (setq value global))))
15924 (throw 'exit nil))))))
15925 (if literal-nil value (org-not-nil value)))))
15927 (defvar org-property-changed-functions nil
15928 "Hook called when the value of a property has changed.
15929 Each hook function should accept two arguments, the name of the property
15930 and the new value.")
15932 (defun org-entry-put (pom property value)
15933 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15935 If the value is nil, it is converted to the empty string. If it
15936 is not a string, an error is raised. Also raise an error on
15937 invalid property names.
15939 PROPERTY can be any regular property (see
15940 `org-special-properties'). It can also be \"TODO\",
15941 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15943 For the last two properties, VALUE may have any of the special
15944 values \"earlier\" and \"later\". The function then increases or
15945 decreases scheduled or deadline date by one day."
15946 (cond ((null value) (setq value ""))
15947 ((not (stringp value)) (error "Properties values should be strings"))
15948 ((not (org--valid-property-p property))
15949 (user-error "Invalid property name: \"%s\"" property)))
15950 (org-with-point-at pom
15951 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15952 (org-back-to-heading t)
15953 (org-with-limited-levels (org-back-to-heading t)))
15954 (let ((beg (point)))
15955 (cond
15956 ((equal property "TODO")
15957 (cond ((not (org-string-nw-p value)) (setq value 'none))
15958 ((not (member value org-todo-keywords-1))
15959 (user-error "\"%s\" is not a valid TODO state" value)))
15960 (org-todo value)
15961 (org-set-tags nil 'align))
15962 ((equal property "PRIORITY")
15963 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15964 (org-set-tags nil 'align))
15965 ((equal property "SCHEDULED")
15966 (forward-line)
15967 (if (and (looking-at-p org-planning-line-re)
15968 (re-search-forward
15969 org-scheduled-time-regexp (line-end-position) t))
15970 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15971 ((string= value "later") (org-timestamp-change 1 'day))
15972 ((string= value "") (org-schedule '(4)))
15973 (t (org-schedule nil value)))
15974 (if (member value '("earlier" "later" ""))
15975 (call-interactively #'org-schedule)
15976 (org-schedule nil value))))
15977 ((equal property "DEADLINE")
15978 (forward-line)
15979 (if (and (looking-at-p org-planning-line-re)
15980 (re-search-forward
15981 org-deadline-time-regexp (line-end-position) t))
15982 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15983 ((string= value "later") (org-timestamp-change 1 'day))
15984 ((string= value "") (org-deadline '(4)))
15985 (t (org-deadline nil value)))
15986 (if (member value '("earlier" "later" ""))
15987 (call-interactively #'org-deadline)
15988 (org-deadline nil value))))
15989 ((member property org-special-properties)
15990 (error "The %s property cannot be set with `org-entry-put'" property))
15992 (let* ((range (org-get-property-block beg 'force))
15993 (end (cdr range))
15994 (case-fold-search t))
15995 (goto-char (car range))
15996 (if (re-search-forward (org-re-property property nil t) end t)
15997 (progn (delete-region (match-beginning 0) (match-end 0))
15998 (goto-char (match-beginning 0)))
15999 (goto-char end)
16000 (insert "\n")
16001 (backward-char))
16002 (insert ":" property ":")
16003 (when value (insert " " value))
16004 (org-indent-line)))))
16005 (run-hook-with-args 'org-property-changed-functions property value)))
16007 (defun org-buffer-property-keys
16008 (&optional specials defaults columns ignore-malformed)
16009 "Get all property keys in the current buffer.
16011 When SPECIALS is non-nil, also list the special properties that
16012 reflect things like tags and TODO state.
16014 When DEFAULTS is non-nil, also include properties that has
16015 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16016 DESCRIPTION, LOCATION, and LOGGING and others.
16018 When COLUMNS in non-nil, also include property names given in
16019 COLUMN formats in the current buffer.
16021 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16022 automatically performed, such drawers will be silently ignored."
16023 (let ((case-fold-search t)
16024 (props (append
16025 (and specials org-special-properties)
16026 (and defaults (cons org-effort-property org-default-properties))
16027 nil)))
16028 (org-with-wide-buffer
16029 (goto-char (point-min))
16030 (while (re-search-forward org-property-start-re nil t)
16031 (let ((range (org-get-property-block)))
16032 (catch 'skip
16033 (unless range
16034 (when (and (not ignore-malformed)
16035 (not (org-before-first-heading-p))
16036 (y-or-n-p (format "Malformed drawer at %d, repair?"
16037 (line-beginning-position))))
16038 (org-get-property-block nil t))
16039 (throw 'skip nil))
16040 (goto-char (car range))
16041 (let ((begin (car range))
16042 (end (cdr range)))
16043 ;; Make sure that found property block is not located
16044 ;; before current point, as it would generate an infloop.
16045 ;; It can happen, for example, in the following
16046 ;; situation:
16048 ;; * Headline
16049 ;; :PROPERTIES:
16050 ;; ...
16051 ;; :END:
16052 ;; *************** Inlinetask
16053 ;; #+BEGIN_EXAMPLE
16054 ;; :PROPERTIES:
16055 ;; #+END_EXAMPLE
16057 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16058 (while (< (point) end)
16059 (let ((p (progn (looking-at org-property-re)
16060 (match-string-no-properties 2))))
16061 ;; Only add true property name, not extension symbol.
16062 (push (if (not (string-match-p "\\+\\'" p)) p
16063 (substring p 0 -1))
16064 props))
16065 (forward-line))))
16066 (outline-next-heading)))
16067 (when columns
16068 (goto-char (point-min))
16069 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16070 (let ((element (org-element-at-point)))
16071 (when (memq (org-element-type element) '(keyword node-property))
16072 (let ((value (org-element-property :value element))
16073 (start 0))
16074 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16075 \\(?:{[^}]+}\\)?"
16076 value start)
16077 (setq start (match-end 0))
16078 (let ((p (match-string-no-properties 1 value)))
16079 (unless (member-ignore-case p org-special-properties)
16080 (push p props))))))))))
16081 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16083 (defun org-property-values (key)
16084 "List all non-nil values of property KEY in current buffer."
16085 (org-with-wide-buffer
16086 (goto-char (point-min))
16087 (let ((case-fold-search t)
16088 (re (org-re-property key))
16089 values)
16090 (while (re-search-forward re nil t)
16091 (push (org-entry-get (point) key) values))
16092 (delete-dups values))))
16094 (defun org-insert-property-drawer ()
16095 "Insert a property drawer into the current entry."
16096 (org-with-wide-buffer
16097 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16098 (org-back-to-heading t)
16099 (org-with-limited-levels (org-back-to-heading t)))
16100 (forward-line)
16101 (when (looking-at-p org-planning-line-re) (forward-line))
16102 (unless (looking-at-p org-property-drawer-re)
16103 ;; Make sure we start editing a line from current entry, not from
16104 ;; next one. It prevents extending text properties or overlays
16105 ;; belonging to the latter.
16106 (when (bolp) (backward-char))
16107 (let ((begin (1+ (point)))
16108 (inhibit-read-only t))
16109 (insert "\n:PROPERTIES:\n:END:")
16110 (when (eobp) (insert "\n"))
16111 (org-indent-region begin (point))))))
16113 (defun org-insert-drawer (&optional arg drawer)
16114 "Insert a drawer at point.
16116 When optional argument ARG is non-nil, insert a property drawer.
16118 Optional argument DRAWER, when non-nil, is a string representing
16119 drawer's name. Otherwise, the user is prompted for a name.
16121 If a region is active, insert the drawer around that region
16122 instead.
16124 Point is left between drawer's boundaries."
16125 (interactive "P")
16126 (let* ((drawer (if arg "PROPERTIES"
16127 (or drawer (read-from-minibuffer "Drawer: ")))))
16128 (cond
16129 ;; With C-u, fall back on `org-insert-property-drawer'
16130 (arg (org-insert-property-drawer))
16131 ;; Check validity of suggested drawer's name.
16132 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16133 (user-error "Invalid drawer name"))
16134 ;; With an active region, insert a drawer at point.
16135 ((not (org-region-active-p))
16136 (progn
16137 (unless (bolp) (insert "\n"))
16138 (insert (format ":%s:\n\n:END:\n" drawer))
16139 (forward-line -2)))
16140 ;; Otherwise, insert the drawer at point
16142 (let ((rbeg (region-beginning))
16143 (rend (copy-marker (region-end))))
16144 (unwind-protect
16145 (progn
16146 (goto-char rbeg)
16147 (beginning-of-line)
16148 (when (save-excursion
16149 (re-search-forward org-outline-regexp-bol rend t))
16150 (user-error "Drawers cannot contain headlines"))
16151 ;; Position point at the beginning of the first
16152 ;; non-blank line in region. Insert drawer's opening
16153 ;; there, then indent it.
16154 (org-skip-whitespace)
16155 (beginning-of-line)
16156 (insert ":" drawer ":\n")
16157 (forward-line -1)
16158 (indent-for-tab-command)
16159 ;; Move point to the beginning of the first blank line
16160 ;; after the last non-blank line in region. Insert
16161 ;; drawer's closing, then indent it.
16162 (goto-char rend)
16163 (skip-chars-backward " \r\t\n")
16164 (insert "\n:END:")
16165 (deactivate-mark t)
16166 (indent-for-tab-command)
16167 (unless (eolp) (insert "\n")))
16168 ;; Clear marker, whatever the outcome of insertion is.
16169 (set-marker rend nil)))))))
16171 (defvar org-property-set-functions-alist nil
16172 "Property set function alist.
16173 Each entry should have the following format:
16175 (PROPERTY . READ-FUNCTION)
16177 The read function will be called with the same argument as
16178 `org-completing-read'.")
16180 (defun org-set-property-function (property)
16181 "Get the function that should be used to set PROPERTY.
16182 This is computed according to `org-property-set-functions-alist'."
16183 (or (cdr (assoc property org-property-set-functions-alist))
16184 'org-completing-read))
16186 (defun org-read-property-value (property)
16187 "Read PROPERTY value from user."
16188 (let* ((completion-ignore-case t)
16189 (allowed (org-property-get-allowed-values nil property 'table))
16190 (cur (org-entry-get nil property))
16191 (prompt (concat property " value"
16192 (if (and cur (string-match "\\S-" cur))
16193 (concat " [" cur "]") "") ": "))
16194 (set-function (org-set-property-function property))
16195 (val (if allowed
16196 (funcall set-function prompt allowed nil
16197 (not (get-text-property 0 'org-unrestricted
16198 (caar allowed))))
16199 (funcall set-function prompt
16200 (mapcar 'list (org-property-values property))
16201 nil nil "" nil cur))))
16202 (org-trim val)))
16204 (defvar org-last-set-property nil)
16205 (defvar org-last-set-property-value nil)
16206 (defun org-read-property-name ()
16207 "Read a property name."
16208 (let ((completion-ignore-case t)
16209 (default-prop (or (and (org-at-property-p)
16210 (match-string-no-properties 2))
16211 org-last-set-property)))
16212 (org-completing-read
16213 (concat "Property"
16214 (if default-prop (concat " [" default-prop "]") "")
16215 ": ")
16216 (mapcar #'list (org-buffer-property-keys nil t t))
16217 nil nil nil nil default-prop)))
16219 (defun org-set-property-and-value (use-last)
16220 "Allow to set [PROPERTY]: [value] direction from prompt.
16221 When use-default, don't even ask, just use the last
16222 \"[PROPERTY]: [value]\" string from the history."
16223 (interactive "P")
16224 (let* ((completion-ignore-case t)
16225 (pv (or (and use-last org-last-set-property-value)
16226 (org-completing-read
16227 "Enter a \"[Property]: [value]\" pair: "
16228 nil nil nil nil nil
16229 org-last-set-property-value)))
16230 prop val)
16231 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16232 (setq prop (match-string 1 pv)
16233 val (match-string 2 pv))
16234 (org-set-property prop val))))
16236 (defun org-set-property (property value)
16237 "In the current entry, set PROPERTY to VALUE.
16239 When called interactively, this will prompt for a property name, offering
16240 completion on existing and default properties. And then it will prompt
16241 for a value, offering completion either on allowed values (via an inherited
16242 xxx_ALL property) or on existing values in other instances of this property
16243 in the current file.
16245 Throw an error when trying to set a property with an invalid name."
16246 (interactive (list nil nil))
16247 (let ((property (or property (org-read-property-name))))
16248 ;; `org-entry-put' also makes the following check, but this one
16249 ;; avoids polluting `org-last-set-property' and
16250 ;; `org-last-set-property-value' needlessly.
16251 (unless (org--valid-property-p property)
16252 (user-error "Invalid property name: \"%s\"" property))
16253 (let ((value (or value (org-read-property-value property)))
16254 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16255 (setq org-last-set-property property)
16256 (setq org-last-set-property-value (concat property ": " value))
16257 ;; Possibly postprocess the inserted value:
16258 (when fn (setq value (funcall fn value)))
16259 (unless (equal (org-entry-get nil property) value)
16260 (org-entry-put nil property value)))))
16262 (defun org-find-property (property &optional value)
16263 "Find first entry in buffer that sets PROPERTY.
16265 When optional argument VALUE is non-nil, only consider an entry
16266 if it contains PROPERTY set to this value. If PROPERTY should be
16267 explicitly set to nil, use string \"nil\" for VALUE.
16269 Return position where the entry begins, or nil if there is no
16270 such entry. If narrowing is in effect, only search the visible
16271 part of the buffer."
16272 (save-excursion
16273 (goto-char (point-min))
16274 (let ((case-fold-search t)
16275 (re (org-re-property property nil (not value) value)))
16276 (catch 'exit
16277 (while (re-search-forward re nil t)
16278 (when (if value (org-at-property-p)
16279 (org-entry-get (point) property nil t))
16280 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16282 (defun org-delete-property (property)
16283 "In the current entry, delete PROPERTY."
16284 (interactive
16285 (let* ((completion-ignore-case t)
16286 (cat (org-entry-get (point) "CATEGORY"))
16287 (props0 (org-entry-properties nil 'standard))
16288 (props (if cat props0
16289 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16290 (prop (if (< 1 (length props))
16291 (completing-read "Property: " props nil t)
16292 (caar props))))
16293 (list prop)))
16294 (if (not property)
16295 (message "No property to delete in this entry")
16296 (org-entry-delete nil property)
16297 (message "Property \"%s\" deleted" property)))
16299 (defun org-delete-property-globally (property)
16300 "Remove PROPERTY globally, from all entries.
16301 This function ignores narrowing, if any."
16302 (interactive
16303 (let* ((completion-ignore-case t)
16304 (prop (completing-read
16305 "Globally remove property: "
16306 (mapcar #'list (org-buffer-property-keys)))))
16307 (list prop)))
16308 (org-with-wide-buffer
16309 (goto-char (point-min))
16310 (let ((count 0)
16311 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16312 (while (re-search-forward re nil t)
16313 (when (org-entry-delete (point) property) (cl-incf count)))
16314 (message "Property \"%s\" removed from %d entries" property count))))
16316 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16318 (defun org-compute-property-at-point ()
16319 "Compute the property at point.
16320 This looks for an enclosing column format, extracts the operator and
16321 then applies it to the property in the column format's scope."
16322 (interactive)
16323 (unless (org-at-property-p)
16324 (user-error "Not at a property"))
16325 (let ((prop (match-string-no-properties 2)))
16326 (org-columns-get-format-and-top-level)
16327 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16328 (user-error "No operator defined for property %s" prop))
16329 (org-columns-compute prop)))
16331 (defvar org-property-allowed-value-functions nil
16332 "Hook for functions supplying allowed values for a specific property.
16333 The functions must take a single argument, the name of the property, and
16334 return a flat list of allowed values. If \":ETC\" is one of
16335 the values, this means that these values are intended as defaults for
16336 completion, but that other values should be allowed too.
16337 The functions must return nil if they are not responsible for this
16338 property.")
16340 (defun org-property-get-allowed-values (pom property &optional table)
16341 "Get allowed values for the property PROPERTY.
16342 When TABLE is non-nil, return an alist that can directly be used for
16343 completion."
16344 (let (vals)
16345 (cond
16346 ((equal property "TODO")
16347 (setq vals (org-with-point-at pom
16348 (append org-todo-keywords-1 '("")))))
16349 ((equal property "PRIORITY")
16350 (let ((n org-lowest-priority))
16351 (while (>= n org-highest-priority)
16352 (push (char-to-string n) vals)
16353 (setq n (1- n)))))
16354 ((equal property "CATEGORY"))
16355 ((member property org-special-properties))
16356 ((setq vals (run-hook-with-args-until-success
16357 'org-property-allowed-value-functions property)))
16359 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16360 (when (and vals (string-match "\\S-" vals))
16361 (setq vals (car (read-from-string (concat "(" vals ")"))))
16362 (setq vals (mapcar (lambda (x)
16363 (cond ((stringp x) x)
16364 ((numberp x) (number-to-string x))
16365 ((symbolp x) (symbol-name x))
16366 (t "???")))
16367 vals)))))
16368 (when (member ":ETC" vals)
16369 (setq vals (remove ":ETC" vals))
16370 (org-add-props (car vals) '(org-unrestricted t)))
16371 (if table (mapcar 'list vals) vals)))
16373 (defun org-property-previous-allowed-value (&optional _previous)
16374 "Switch to the next allowed value for this property."
16375 (interactive)
16376 (org-property-next-allowed-value t))
16378 (defun org-property-next-allowed-value (&optional previous)
16379 "Switch to the next allowed value for this property."
16380 (interactive)
16381 (unless (org-at-property-p)
16382 (user-error "Not at a property"))
16383 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16384 (key (match-string 2))
16385 (value (match-string 3))
16386 (allowed (or (org-property-get-allowed-values (point) key)
16387 (and (member value '("[ ]" "[-]" "[X]"))
16388 '("[ ]" "[X]"))))
16389 (heading (save-match-data (nth 4 (org-heading-components))))
16390 nval)
16391 (unless allowed
16392 (user-error "Allowed values for this property have not been defined"))
16393 (when previous (setq allowed (reverse allowed)))
16394 (when (member value allowed)
16395 (setq nval (car (cdr (member value allowed)))))
16396 (setq nval (or nval (car allowed)))
16397 (when (equal nval value)
16398 (user-error "Only one allowed value for this property"))
16399 (org-at-property-p)
16400 (replace-match (concat " :" key ": " nval) t t)
16401 (org-indent-line)
16402 (beginning-of-line 1)
16403 (skip-chars-forward " \t")
16404 (when (equal prop org-effort-property)
16405 (org-refresh-property
16406 '((effort . identity)
16407 (effort-minutes . org-duration-to-minutes))
16408 nval)
16409 (when (string= org-clock-current-task heading)
16410 (setq org-clock-effort nval)
16411 (org-clock-update-mode-line)))
16412 (run-hook-with-args 'org-property-changed-functions key nval)))
16414 (defun org-find-olp (path &optional this-buffer)
16415 "Return a marker pointing to the entry at outline path OLP.
16416 If anything goes wrong, throw an error.
16417 You can wrap this call to catch the error like this:
16419 (condition-case msg
16420 (org-mobile-locate-entry (match-string 4))
16421 (error (nth 1 msg)))
16423 The return value will then be either a string with the error message,
16424 or a marker if everything is OK.
16426 If THIS-BUFFER is set, the outline path does not contain a file,
16427 only headings."
16428 (let* ((file (if this-buffer buffer-file-name (pop path)))
16429 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16430 (level 1)
16431 (lmin 1)
16432 (lmax 1)
16433 end found flevel)
16434 (unless buffer (error "File not found :%s" file))
16435 (with-current-buffer buffer
16436 (unless (derived-mode-p 'org-mode)
16437 (error "Buffer %s needs to be in Org mode" buffer))
16438 (org-with-wide-buffer
16439 (goto-char (point-min))
16440 (dolist (heading path)
16441 (let ((re (format org-complex-heading-regexp-format
16442 (regexp-quote heading)))
16443 (cnt 0))
16444 (while (re-search-forward re end t)
16445 (setq level (- (match-end 1) (match-beginning 1)))
16446 (when (and (>= level lmin) (<= level lmax))
16447 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16448 (when (= cnt 0)
16449 (error "Heading not found on level %d: %s" lmax heading))
16450 (when (> cnt 1)
16451 (error "Heading not unique on level %d: %s" lmax heading))
16452 (goto-char found)
16453 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16454 (setq end (save-excursion (org-end-of-subtree t t)))))
16455 (when (org-at-heading-p)
16456 (point-marker))))))
16458 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16459 "Find node HEADING in BUFFER.
16460 Return a marker to the heading if it was found, or nil if not.
16461 If POS-ONLY is set, return just the position instead of a marker.
16463 The heading text must match exact, but it may have a TODO keyword,
16464 a priority cookie and tags in the standard locations."
16465 (with-current-buffer (or buffer (current-buffer))
16466 (org-with-wide-buffer
16467 (goto-char (point-min))
16468 (let (case-fold-search)
16469 (when (re-search-forward
16470 (format org-complex-heading-regexp-format
16471 (regexp-quote heading)) nil t)
16472 (if pos-only
16473 (match-beginning 0)
16474 (move-marker (make-marker) (match-beginning 0))))))))
16476 (defun org-find-exact-heading-in-directory (heading &optional dir)
16477 "Find Org node headline HEADING in all .org files in directory DIR.
16478 When the target headline is found, return a marker to this location."
16479 (let ((files (directory-files (or dir default-directory)
16480 t "\\`[^.#].*\\.org\\'"))
16481 visiting m buffer)
16482 (catch 'found
16483 (dolist (file files)
16484 (message "trying %s" file)
16485 (setq visiting (org-find-base-buffer-visiting file))
16486 (setq buffer (or visiting (find-file-noselect file)))
16487 (setq m (org-find-exact-headline-in-buffer
16488 heading buffer))
16489 (when (and (not m) (not visiting)) (kill-buffer buffer))
16490 (and m (throw 'found m))))))
16492 (defun org-find-entry-with-id (ident)
16493 "Locate the entry that contains the ID property with exact value IDENT.
16494 IDENT can be a string, a symbol or a number, this function will search for
16495 the string representation of it.
16496 Return the position where this entry starts, or nil if there is no such entry."
16497 (interactive "sID: ")
16498 (let ((id (cond
16499 ((stringp ident) ident)
16500 ((symbolp ident) (symbol-name ident))
16501 ((numberp ident) (number-to-string ident))
16502 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16503 (org-with-wide-buffer (org-find-property "ID" id))))
16505 ;;;; Timestamps
16507 (defvar org-last-changed-timestamp nil)
16508 (defvar org-last-inserted-timestamp nil
16509 "The last time stamp inserted with `org-insert-time-stamp'.")
16511 (defun org-time-stamp (arg &optional inactive)
16512 "Prompt for a date/time and insert a time stamp.
16514 If the user specifies a time like HH:MM or if this command is
16515 called with at least one prefix argument, the time stamp contains
16516 the date and the time. Otherwise, only the date is included.
16518 All parts of a date not specified by the user are filled in from
16519 the timestamp at point, if any, or the current date/time
16520 otherwise.
16522 If there is already a timestamp at the cursor, it is replaced.
16524 With two universal prefix arguments, insert an active timestamp
16525 with the current time without prompting the user.
16527 When called from lisp, the timestamp is inactive if INACTIVE is
16528 non-nil."
16529 (interactive "P")
16530 (let* ((ts (cond
16531 ((org-at-date-range-p t)
16532 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16533 ((org-at-timestamp-p 'lax) (match-string 0))))
16534 ;; Default time is either the timestamp at point or today.
16535 ;; When entering a range, only the range start is considered.
16536 (default-time (if (not ts) (current-time)
16537 (apply #'encode-time (org-parse-time-string ts))))
16538 (default-input (and ts (org-get-compact-tod ts)))
16539 (repeater (and ts
16540 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16541 (match-string 0 ts)))
16542 org-time-was-given
16543 org-end-time-was-given
16544 (time
16545 (and (if (equal arg '(16)) (current-time)
16546 ;; Preserve `this-command' and `last-command'.
16547 (let ((this-command this-command)
16548 (last-command last-command))
16549 (org-read-date
16550 arg 'totime nil nil default-time default-input
16551 inactive))))))
16552 (cond
16553 ((and ts
16554 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16555 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16556 (insert "--")
16557 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16559 ;; Make sure we're on a timestamp. When in the middle of a date
16560 ;; range, move arbitrarily to range end.
16561 (unless (org-at-timestamp-p 'lax)
16562 (skip-chars-forward "-")
16563 (org-at-timestamp-p 'lax))
16564 (replace-match "")
16565 (setq org-last-changed-timestamp
16566 (org-insert-time-stamp
16567 time (or org-time-was-given arg)
16568 inactive nil nil (list org-end-time-was-given)))
16569 (when repeater
16570 (backward-char)
16571 (insert " " repeater)
16572 (setq org-last-changed-timestamp
16573 (concat (substring org-last-inserted-timestamp 0 -1)
16574 " " repeater ">")))
16575 (message "Timestamp updated"))
16576 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16577 (t (org-insert-time-stamp
16578 time (or org-time-was-given arg) inactive nil nil
16579 (list org-end-time-was-given))))))
16581 ;; FIXME: can we use this for something else, like computing time differences?
16582 (defun org-get-compact-tod (s)
16583 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16584 (let* ((t1 (match-string 1 s))
16585 (h1 (string-to-number (match-string 2 s)))
16586 (m1 (string-to-number (match-string 3 s)))
16587 (t2 (and (match-end 4) (match-string 5 s)))
16588 (h2 (and t2 (string-to-number (match-string 6 s))))
16589 (m2 (and t2 (string-to-number (match-string 7 s))))
16590 dh dm)
16591 (if (not t2)
16593 (setq dh (- h2 h1) dm (- m2 m1))
16594 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16595 (concat t1 "+" (number-to-string dh)
16596 (and (/= 0 dm) (format ":%02d" dm)))))))
16598 (defun org-time-stamp-inactive (&optional arg)
16599 "Insert an inactive time stamp.
16600 An inactive time stamp is enclosed in square brackets instead of angle
16601 brackets. It is inactive in the sense that it does not trigger agenda entries,
16602 does not link to the calendar and cannot be changed with the S-cursor keys.
16603 So these are more for recording a certain time/date."
16604 (interactive "P")
16605 (org-time-stamp arg 'inactive))
16607 (defvar org-date-ovl (make-overlay 1 1))
16608 (overlay-put org-date-ovl 'face 'org-date-selected)
16609 (delete-overlay org-date-ovl)
16611 (defvar org-ans1) ; dynamically scoped parameter
16612 (defvar org-ans2) ; dynamically scoped parameter
16614 (defvar org-plain-time-of-day-regexp) ; defined below
16616 (defvar org-overriding-default-time nil) ; dynamically scoped
16617 (defvar org-read-date-overlay nil)
16618 (defvar org-dcst nil) ; dynamically scoped
16619 (defvar org-read-date-history nil)
16620 (defvar org-read-date-final-answer nil)
16621 (defvar org-read-date-analyze-futurep nil)
16622 (defvar org-read-date-analyze-forced-year nil)
16623 (defvar org-read-date-inactive)
16625 (defvar org-read-date-minibuffer-local-map
16626 (let* ((map (make-sparse-keymap)))
16627 (set-keymap-parent map minibuffer-local-map)
16628 (org-defkey map (kbd ".")
16629 (lambda () (interactive)
16630 ;; Are we at the beginning of the prompt?
16631 (if (looking-back "^[^:]+: "
16632 (let ((inhibit-field-text-motion t))
16633 (line-beginning-position)))
16634 (org-eval-in-calendar '(calendar-goto-today))
16635 (insert "."))))
16636 (org-defkey map (kbd "C-.")
16637 (lambda () (interactive)
16638 (org-eval-in-calendar '(calendar-goto-today))))
16639 (org-defkey map [(meta shift left)]
16640 (lambda () (interactive)
16641 (org-eval-in-calendar '(calendar-backward-month 1))))
16642 (org-defkey map [(meta shift right)]
16643 (lambda () (interactive)
16644 (org-eval-in-calendar '(calendar-forward-month 1))))
16645 (org-defkey map [(meta shift up)]
16646 (lambda () (interactive)
16647 (org-eval-in-calendar '(calendar-backward-year 1))))
16648 (org-defkey map [(meta shift down)]
16649 (lambda () (interactive)
16650 (org-eval-in-calendar '(calendar-forward-year 1))))
16651 (org-defkey map [?\e (shift left)]
16652 (lambda () (interactive)
16653 (org-eval-in-calendar '(calendar-backward-month 1))))
16654 (org-defkey map [?\e (shift right)]
16655 (lambda () (interactive)
16656 (org-eval-in-calendar '(calendar-forward-month 1))))
16657 (org-defkey map [?\e (shift up)]
16658 (lambda () (interactive)
16659 (org-eval-in-calendar '(calendar-backward-year 1))))
16660 (org-defkey map [?\e (shift down)]
16661 (lambda () (interactive)
16662 (org-eval-in-calendar '(calendar-forward-year 1))))
16663 (org-defkey map [(shift up)]
16664 (lambda () (interactive)
16665 (org-eval-in-calendar '(calendar-backward-week 1))))
16666 (org-defkey map [(shift down)]
16667 (lambda () (interactive)
16668 (org-eval-in-calendar '(calendar-forward-week 1))))
16669 (org-defkey map [(shift left)]
16670 (lambda () (interactive)
16671 (org-eval-in-calendar '(calendar-backward-day 1))))
16672 (org-defkey map [(shift right)]
16673 (lambda () (interactive)
16674 (org-eval-in-calendar '(calendar-forward-day 1))))
16675 (org-defkey map "!"
16676 (lambda () (interactive)
16677 (org-eval-in-calendar '(diary-view-entries))
16678 (message "")))
16679 (org-defkey map ">"
16680 (lambda () (interactive)
16681 (org-eval-in-calendar '(calendar-scroll-left 1))))
16682 (org-defkey map "<"
16683 (lambda () (interactive)
16684 (org-eval-in-calendar '(calendar-scroll-right 1))))
16685 (org-defkey map "\C-v"
16686 (lambda () (interactive)
16687 (org-eval-in-calendar
16688 '(calendar-scroll-left-three-months 1))))
16689 (org-defkey map "\M-v"
16690 (lambda () (interactive)
16691 (org-eval-in-calendar
16692 '(calendar-scroll-right-three-months 1))))
16693 map)
16694 "Keymap for minibuffer commands when using `org-read-date'.")
16696 (defvar org-def)
16697 (defvar org-defdecode)
16698 (defvar org-with-time)
16700 (defvar calendar-setup) ; Dynamically scoped.
16701 (defun org-read-date (&optional with-time to-time from-string prompt
16702 default-time default-input inactive)
16703 "Read a date, possibly a time, and make things smooth for the user.
16704 The prompt will suggest to enter an ISO date, but you can also enter anything
16705 which will at least partially be understood by `parse-time-string'.
16706 Unrecognized parts of the date will default to the current day, month, year,
16707 hour and minute. If this command is called to replace a timestamp at point,
16708 or to enter the second timestamp of a range, the default time is taken
16709 from the existing stamp. Furthermore, the command prefers the future,
16710 so if you are giving a date where the year is not given, and the day-month
16711 combination is already past in the current year, it will assume you
16712 mean next year. For details, see the manual. A few examples:
16714 3-2-5 --> 2003-02-05
16715 feb 15 --> currentyear-02-15
16716 2/15 --> currentyear-02-15
16717 sep 12 9 --> 2009-09-12
16718 12:45 --> today 12:45
16719 22 sept 0:34 --> currentyear-09-22 0:34
16720 12 --> currentyear-currentmonth-12
16721 Fri --> nearest Friday after today
16722 -Tue --> last Tuesday
16723 etc.
16725 Furthermore you can specify a relative date by giving, as the *first* thing
16726 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16727 change in days weeks, months, years.
16728 With a single plus or minus, the date is relative to today. With a double
16729 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16730 +4d --> four days from today
16731 +4 --> same as above
16732 +2w --> two weeks from today
16733 ++5 --> five days from default date
16735 The function understands only English month and weekday abbreviations.
16737 While prompting, a calendar is popped up - you can also select the
16738 date with the mouse (button 1). The calendar shows a period of three
16739 months. To scroll it to other months, use the keys `>' and `<'.
16740 If you don't like the calendar, turn it off with
16741 (setq org-read-date-popup-calendar nil)
16743 With optional argument TO-TIME, the date will immediately be converted
16744 to an internal time.
16745 With an optional argument WITH-TIME, the prompt will suggest to
16746 also insert a time. Note that when WITH-TIME is not set, you can
16747 still enter a time, and this function will inform the calling routine
16748 about this change. The calling routine may then choose to change the
16749 format used to insert the time stamp into the buffer to include the time.
16750 With optional argument FROM-STRING, read from this string instead from
16751 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16752 the time/date that is used for everything that is not specified by the
16753 user."
16754 (require 'parse-time)
16755 (let* ((org-with-time with-time)
16756 (org-time-stamp-rounding-minutes
16757 (if (equal org-with-time '(16))
16758 '(0 0)
16759 org-time-stamp-rounding-minutes))
16760 (org-dcst org-display-custom-times)
16761 (ct (org-current-time))
16762 (org-def (or org-overriding-default-time default-time ct))
16763 (org-defdecode (decode-time org-def))
16764 (cur-frame (selected-frame))
16765 (mouse-autoselect-window nil) ; Don't let the mouse jump
16766 (calendar-setup
16767 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16768 (calendar-move-hook nil)
16769 (calendar-view-diary-initially-flag nil)
16770 (calendar-view-holidays-initially-flag nil)
16771 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16772 ;; Rationalize `org-def' and `org-defdecode', if required.
16773 (when (< (nth 2 org-defdecode) org-extend-today-until)
16774 (setf (nth 2 org-defdecode) -1)
16775 (setf (nth 1 org-defdecode) 59)
16776 (setq org-def (apply #'encode-time org-defdecode))
16777 (setq org-defdecode (decode-time org-def)))
16778 (let* ((timestr (format-time-string
16779 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16780 org-def))
16781 (prompt (concat (if prompt (concat prompt " ") "")
16782 (format "Date+time [%s]: " timestr))))
16783 (cond
16784 (from-string (setq ans from-string))
16785 (org-read-date-popup-calendar
16786 (save-excursion
16787 (save-window-excursion
16788 (calendar)
16789 (when (eq calendar-setup 'calendar-only)
16790 (setq cal-frame
16791 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16792 (select-frame cal-frame))
16793 (org-eval-in-calendar '(setq cursor-type nil) t)
16794 (unwind-protect
16795 (progn
16796 (calendar-forward-day (- (time-to-days org-def)
16797 (calendar-absolute-from-gregorian
16798 (calendar-current-date))))
16799 (org-eval-in-calendar nil t)
16800 (let* ((old-map (current-local-map))
16801 (map (copy-keymap calendar-mode-map))
16802 (minibuffer-local-map
16803 (copy-keymap org-read-date-minibuffer-local-map)))
16804 (org-defkey map (kbd "RET") 'org-calendar-select)
16805 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16806 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16807 (unwind-protect
16808 (progn
16809 (use-local-map map)
16810 (setq org-read-date-inactive inactive)
16811 (add-hook 'post-command-hook 'org-read-date-display)
16812 (setq org-ans0
16813 (read-string prompt
16814 default-input
16815 'org-read-date-history
16816 nil))
16817 ;; org-ans0: from prompt
16818 ;; org-ans1: from mouse click
16819 ;; org-ans2: from calendar motion
16820 (setq ans
16821 (concat org-ans0 " " (or org-ans1 org-ans2))))
16822 (remove-hook 'post-command-hook 'org-read-date-display)
16823 (use-local-map old-map)
16824 (when org-read-date-overlay
16825 (delete-overlay org-read-date-overlay)
16826 (setq org-read-date-overlay nil)))))
16827 (bury-buffer "*Calendar*")
16828 (when cal-frame
16829 (delete-frame cal-frame)
16830 (select-frame-set-input-focus cur-frame))))))
16832 (t ; Naked prompt only
16833 (unwind-protect
16834 (setq ans (read-string prompt default-input
16835 'org-read-date-history timestr))
16836 (when org-read-date-overlay
16837 (delete-overlay org-read-date-overlay)
16838 (setq org-read-date-overlay nil))))))
16840 (setq final (org-read-date-analyze ans org-def org-defdecode))
16842 (when org-read-date-analyze-forced-year
16843 (message "Year was forced into %s"
16844 (if org-read-date-force-compatible-dates
16845 "compatible range (1970-2037)"
16846 "range representable on this machine"))
16847 (ding))
16849 ;; One round trip to get rid of 34th of August and stuff like that....
16850 (setq final (decode-time (apply 'encode-time final)))
16852 (setq org-read-date-final-answer ans)
16854 (if to-time
16855 (apply 'encode-time final)
16856 (if (and (boundp 'org-time-was-given) org-time-was-given)
16857 (format "%04d-%02d-%02d %02d:%02d"
16858 (nth 5 final) (nth 4 final) (nth 3 final)
16859 (nth 2 final) (nth 1 final))
16860 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16862 (defun org-read-date-display ()
16863 "Display the current date prompt interpretation in the minibuffer."
16864 (when org-read-date-display-live
16865 (when org-read-date-overlay
16866 (delete-overlay org-read-date-overlay))
16867 (when (minibufferp (current-buffer))
16868 (save-excursion
16869 (end-of-line 1)
16870 (while (not (equal (buffer-substring
16871 (max (point-min) (- (point) 4)) (point))
16872 " "))
16873 (insert " ")))
16874 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16875 " " (or org-ans1 org-ans2)))
16876 (org-end-time-was-given nil)
16877 (f (org-read-date-analyze ans org-def org-defdecode))
16878 (fmts (if org-dcst
16879 org-time-stamp-custom-formats
16880 org-time-stamp-formats))
16881 (fmt (if (or org-with-time
16882 (and (boundp 'org-time-was-given) org-time-was-given))
16883 (cdr fmts)
16884 (car fmts)))
16885 (txt (format-time-string fmt (apply 'encode-time f)))
16886 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16887 (txt (concat "=> " txt)))
16888 (when (and org-end-time-was-given
16889 (string-match org-plain-time-of-day-regexp txt))
16890 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16891 org-end-time-was-given
16892 (substring txt (match-end 0)))))
16893 (when org-read-date-analyze-futurep
16894 (setq txt (concat txt " (=>F)")))
16895 (setq org-read-date-overlay
16896 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16897 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16899 (defun org-read-date-analyze (ans def defdecode)
16900 "Analyze the combined answer of the date prompt."
16901 ;; FIXME: cleanup and comment
16902 ;; Pass `current-time' result to `decode-time' (instead of calling
16903 ;; without arguments) so that only `current-time' has to be
16904 ;; overridden in tests.
16905 (let ((org-def def)
16906 (org-defdecode defdecode)
16907 (nowdecode (decode-time (current-time)))
16908 delta deltan deltaw deltadef year month day
16909 hour minute second wday pm h2 m2 tl wday1
16910 iso-year iso-weekday iso-week iso-date futurep kill-year)
16911 (setq org-read-date-analyze-futurep nil
16912 org-read-date-analyze-forced-year nil)
16913 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16914 (setq ans "+0"))
16916 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16917 (setq ans (replace-match "" t t ans)
16918 deltan (car delta)
16919 deltaw (nth 1 delta)
16920 deltadef (nth 2 delta)))
16922 ;; Check if there is an iso week date in there. If yes, store the
16923 ;; info and postpone interpreting it until the rest of the parsing
16924 ;; is done.
16925 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16926 (setq iso-year (when (match-end 1)
16927 (org-small-year-to-year
16928 (string-to-number (match-string 1 ans))))
16929 iso-weekday (when (match-end 3)
16930 (string-to-number (match-string 3 ans)))
16931 iso-week (string-to-number (match-string 2 ans)))
16932 (setq ans (replace-match "" t t ans)))
16934 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16935 (when (string-match
16936 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16937 (setq year (if (match-end 2)
16938 (string-to-number (match-string 2 ans))
16939 (progn (setq kill-year t)
16940 (string-to-number (format-time-string "%Y"))))
16941 month (string-to-number (match-string 3 ans))
16942 day (string-to-number (match-string 4 ans)))
16943 (setq year (org-small-year-to-year year))
16944 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16945 t nil ans)))
16947 ;; Help matching dotted european dates
16948 (when (string-match
16949 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16950 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16951 (setq kill-year t)
16952 (string-to-number (format-time-string "%Y")))
16953 day (string-to-number (match-string 1 ans))
16954 month (string-to-number (match-string 2 ans))
16955 ans (replace-match (format "%04d-%02d-%02d" year month day)
16956 t nil ans)))
16958 ;; Help matching american dates, like 5/30 or 5/30/7
16959 (when (string-match
16960 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16961 (setq year (if (match-end 4)
16962 (string-to-number (match-string 4 ans))
16963 (progn (setq kill-year t)
16964 (string-to-number (format-time-string "%Y"))))
16965 month (string-to-number (match-string 1 ans))
16966 day (string-to-number (match-string 2 ans)))
16967 (setq year (org-small-year-to-year year))
16968 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16969 t nil ans)))
16970 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16971 ;; If there is a time with am/pm, and *no* time without it, we convert
16972 ;; so that matching will be successful.
16973 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16974 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16975 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16976 (setq hour (string-to-number (match-string 1 ans))
16977 minute (if (match-end 3)
16978 (string-to-number (match-string 3 ans))
16980 pm (equal ?p
16981 (string-to-char (downcase (match-string 4 ans)))))
16982 (if (and (= hour 12) (not pm))
16983 (setq hour 0)
16984 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16985 (setq ans (replace-match (format "%02d:%02d" hour minute)
16986 t t ans))))
16988 ;; Check if a time range is given as a duration
16989 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16990 (setq hour (string-to-number (match-string 1 ans))
16991 h2 (+ hour (string-to-number (match-string 3 ans)))
16992 minute (string-to-number (match-string 2 ans))
16993 m2 (+ minute (if (match-end 5) (string-to-number
16994 (match-string 5 ans))0)))
16995 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16996 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16997 t t ans)))
16999 ;; Check if there is a time range
17000 (when (boundp 'org-end-time-was-given)
17001 (setq org-time-was-given nil)
17002 (when (and (string-match org-plain-time-of-day-regexp ans)
17003 (match-end 8))
17004 (setq org-end-time-was-given (match-string 8 ans))
17005 (setq ans (concat (substring ans 0 (match-beginning 7))
17006 (substring ans (match-end 7))))))
17008 (setq tl (parse-time-string ans)
17009 day (or (nth 3 tl) (nth 3 org-defdecode))
17010 month
17011 (cond ((nth 4 tl))
17012 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17013 ;; Day was specified. Make sure DAY+MONTH
17014 ;; combination happens in the future.
17015 ((nth 3 tl)
17016 (setq futurep t)
17017 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17018 (nth 4 nowdecode)))
17019 (t (nth 4 org-defdecode)))
17020 year
17021 (cond ((and (not kill-year) (nth 5 tl)))
17022 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17023 ;; Month was guessed in the future and is at least
17024 ;; equal to NOWDECODE's. Fix year accordingly.
17025 (futurep
17026 (if (or (> month (nth 4 nowdecode))
17027 (>= day (nth 3 nowdecode)))
17028 (nth 5 nowdecode)
17029 (1+ (nth 5 nowdecode))))
17030 ;; Month was specified. Make sure MONTH+YEAR
17031 ;; combination happens in the future.
17032 ((nth 4 tl)
17033 (setq futurep t)
17034 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17035 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17036 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17037 (t (nth 5 nowdecode))))
17038 (t (nth 5 org-defdecode)))
17039 hour (or (nth 2 tl) (nth 2 org-defdecode))
17040 minute (or (nth 1 tl) (nth 1 org-defdecode))
17041 second (or (nth 0 tl) 0)
17042 wday (nth 6 tl))
17044 (when (and (eq org-read-date-prefer-future 'time)
17045 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17046 (equal day (nth 3 nowdecode))
17047 (equal month (nth 4 nowdecode))
17048 (equal year (nth 5 nowdecode))
17049 (nth 2 tl)
17050 (or (< (nth 2 tl) (nth 2 nowdecode))
17051 (and (= (nth 2 tl) (nth 2 nowdecode))
17052 (nth 1 tl)
17053 (< (nth 1 tl) (nth 1 nowdecode)))))
17054 (setq day (1+ day)
17055 futurep t))
17057 ;; Special date definitions below
17058 (cond
17059 (iso-week
17060 ;; There was an iso week
17061 (require 'cal-iso)
17062 (setq futurep nil)
17063 (setq year (or iso-year year)
17064 day (or iso-weekday wday 1)
17065 wday nil ; to make sure that the trigger below does not match
17066 iso-date (calendar-gregorian-from-absolute
17067 (calendar-iso-to-absolute
17068 (list iso-week day year))))
17069 ; FIXME: Should we also push ISO weeks into the future?
17070 ; (when (and org-read-date-prefer-future
17071 ; (not iso-year)
17072 ; (< (calendar-absolute-from-gregorian iso-date)
17073 ; (time-to-days (current-time))))
17074 ; (setq year (1+ year)
17075 ; iso-date (calendar-gregorian-from-absolute
17076 ; (calendar-iso-to-absolute
17077 ; (list iso-week day year)))))
17078 (setq month (car iso-date)
17079 year (nth 2 iso-date)
17080 day (nth 1 iso-date)))
17081 (deltan
17082 (setq futurep nil)
17083 (unless deltadef
17084 ;; Pass `current-time' result to `decode-time' (instead of
17085 ;; calling without arguments) so that only `current-time' has
17086 ;; to be overridden in tests.
17087 (let ((now (decode-time (current-time))))
17088 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17089 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17090 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17091 ((equal deltaw "m") (setq month (+ month deltan)))
17092 ((equal deltaw "y") (setq year (+ year deltan)))))
17093 ((and wday (not (nth 3 tl)))
17094 ;; Weekday was given, but no day, so pick that day in the week
17095 ;; on or after the derived date.
17096 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17097 (unless (equal wday wday1)
17098 (setq day (+ day (% (- wday wday1 -7) 7))))))
17099 (when (and (boundp 'org-time-was-given)
17100 (nth 2 tl))
17101 (setq org-time-was-given t))
17102 (when (< year 100) (setq year (+ 2000 year)))
17103 ;; Check of the date is representable
17104 (if org-read-date-force-compatible-dates
17105 (progn
17106 (when (< year 1970)
17107 (setq year 1970 org-read-date-analyze-forced-year t))
17108 (when (> year 2037)
17109 (setq year 2037 org-read-date-analyze-forced-year t)))
17110 (condition-case nil
17111 (ignore (encode-time second minute hour day month year))
17112 (error
17113 (setq year (nth 5 org-defdecode))
17114 (setq org-read-date-analyze-forced-year t))))
17115 (setq org-read-date-analyze-futurep futurep)
17116 (list second minute hour day month year)))
17118 (defvar parse-time-weekdays)
17119 (defun org-read-date-get-relative (s today default)
17120 "Check string S for special relative date string.
17121 TODAY and DEFAULT are internal times, for today and for a default.
17122 Return shift list (N what def-flag)
17123 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17124 N is the number of WHATs to shift.
17125 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17126 the DEFAULT date rather than TODAY."
17127 (require 'parse-time)
17128 (when (and
17129 (string-match
17130 (concat
17131 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17132 "\\([0-9]+\\)?"
17133 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17134 "\\([ \t]\\|$\\)") s)
17135 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17136 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17137 (string-to-char (substring (match-string 1 s) -1))
17138 ?+))
17139 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17140 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17141 (what (if (match-end 3) (match-string 3 s) "d"))
17142 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17143 (date (if rel default today))
17144 (wday (nth 6 (decode-time date)))
17145 delta)
17146 (if wday1
17147 (progn
17148 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17149 (when (= delta 0) (setq delta 7))
17150 (when (= dir ?-)
17151 (setq delta (- delta 7))
17152 (when (= delta 0) (setq delta -7)))
17153 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17154 (list delta "d" rel))
17155 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17157 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17158 "Turn a user-specified date into the internal representation.
17159 The internal representation needed by the calendar is (month day year).
17160 This is a wrapper to handle the brain-dead convention in calendar that
17161 user function argument order change dependent on argument order."
17162 (pcase calendar-date-style
17163 (`american (list arg1 arg2 arg3))
17164 (`european (list arg2 arg1 arg3))
17165 (`iso (list arg2 arg3 arg1))))
17167 (defun org-eval-in-calendar (form &optional keepdate)
17168 "Eval FORM in the calendar window and return to current window.
17169 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17170 (let ((sf (selected-frame))
17171 (sw (selected-window)))
17172 (select-window (get-buffer-window "*Calendar*" t))
17173 (eval form)
17174 (when (and (not keepdate) (calendar-cursor-to-date))
17175 (let* ((date (calendar-cursor-to-date))
17176 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17177 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17178 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17179 (select-window sw)
17180 (select-frame-set-input-focus sf)))
17182 (defun org-calendar-select ()
17183 "Return to `org-read-date' with the date currently selected.
17184 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17185 (interactive)
17186 (when (calendar-cursor-to-date)
17187 (let* ((date (calendar-cursor-to-date))
17188 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17189 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17190 (when (active-minibuffer-window) (exit-minibuffer))))
17192 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17193 "Insert a date stamp for the date given by the internal TIME.
17194 See `format-time-string' for the format of TIME.
17195 WITH-HM means use the stamp format that includes the time of the day.
17196 INACTIVE means use square brackets instead of angular ones, so that the
17197 stamp will not contribute to the agenda.
17198 PRE and POST are optional strings to be inserted before and after the
17199 stamp.
17200 The command returns the inserted time stamp."
17201 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17202 stamp)
17203 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17204 (insert-before-markers (or pre ""))
17205 (when (listp extra)
17206 (setq extra (car extra))
17207 (if (and (stringp extra)
17208 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17209 (setq extra (format "-%02d:%02d"
17210 (string-to-number (match-string 1 extra))
17211 (string-to-number (match-string 2 extra))))
17212 (setq extra nil)))
17213 (when extra
17214 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17215 (insert-before-markers (setq stamp (format-time-string fmt time)))
17216 (insert-before-markers (or post ""))
17217 (setq org-last-inserted-timestamp stamp)))
17219 (defun org-toggle-time-stamp-overlays ()
17220 "Toggle the use of custom time stamp formats."
17221 (interactive)
17222 (setq org-display-custom-times (not org-display-custom-times))
17223 (unless org-display-custom-times
17224 (let ((p (point-min)) (bmp (buffer-modified-p)))
17225 (while (setq p (next-single-property-change p 'display))
17226 (when (and (get-text-property p 'display)
17227 (eq (get-text-property p 'face) 'org-date))
17228 (remove-text-properties
17229 p (setq p (next-single-property-change p 'display))
17230 '(display t))))
17231 (set-buffer-modified-p bmp)))
17232 (org-restart-font-lock)
17233 (setq org-table-may-need-update t)
17234 (if org-display-custom-times
17235 (message "Time stamps are overlaid with custom format")
17236 (message "Time stamp overlays removed")))
17238 (defun org-display-custom-time (beg end)
17239 "Overlay modified time stamp format over timestamp between BEG and END."
17240 (let* ((ts (buffer-substring beg end))
17241 t1 with-hm tf time str (off 0))
17242 (save-match-data
17243 (setq t1 (org-parse-time-string ts t))
17244 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17245 (setq off (- (match-end 0) (match-beginning 0)))))
17246 (setq end (- end off))
17247 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17248 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17249 time (org-fix-decoded-time t1)
17250 str (org-add-props
17251 (format-time-string
17252 (substring tf 1 -1) (apply 'encode-time time))
17253 nil 'mouse-face 'highlight))
17254 (put-text-property beg end 'display str)))
17256 (defun org-fix-decoded-time (time)
17257 "Set 0 instead of nil for the first 6 elements of time.
17258 Don't touch the rest."
17259 (let ((n 0))
17260 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17262 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17263 "Difference between TIMESTAMP-STRING and now in days.
17264 If SECONDS is non-nil, return the difference in seconds."
17265 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17266 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17267 (funcall fdiff (current-time)))))
17269 (defun org-deadline-close-p (timestamp-string &optional ndays)
17270 "Is the time in TIMESTAMP-STRING close to the current date?"
17271 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17272 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17273 (not (org-entry-is-done-p))))
17275 (defun org-get-wdays (ts &optional delay zero-delay)
17276 "Get the deadline lead time appropriate for timestring TS.
17277 When DELAY is non-nil, get the delay time for scheduled items
17278 instead of the deadline lead time. When ZERO-DELAY is non-nil
17279 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17280 don't try to find the delay cookie in the scheduled timestamp."
17281 (let ((tv (if delay org-scheduled-delay-days
17282 org-deadline-warning-days)))
17283 (cond
17284 ((or (and delay (< tv 0))
17285 (and delay zero-delay (<= tv 0))
17286 (and (not delay) (<= tv 0)))
17287 ;; Enforce this value no matter what
17288 (- tv))
17289 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17290 ;; lead time is specified.
17291 (floor (* (string-to-number (match-string 1 ts))
17292 (cdr (assoc (match-string 2 ts)
17293 '(("d" . 1) ("w" . 7)
17294 ("m" . 30.4) ("y" . 365.25)
17295 ("h" . 0.041667)))))))
17296 ;; go for the default.
17297 (t tv))))
17299 (defun org-calendar-select-mouse (ev)
17300 "Return to `org-read-date' with the date currently selected.
17301 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17302 (interactive "e")
17303 (mouse-set-point ev)
17304 (when (calendar-cursor-to-date)
17305 (let* ((date (calendar-cursor-to-date))
17306 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17307 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17308 (when (active-minibuffer-window) (exit-minibuffer))))
17310 (defun org-check-deadlines (ndays)
17311 "Check if there are any deadlines due or past due.
17312 A deadline is considered due if it happens within `org-deadline-warning-days'
17313 days from today's date. If the deadline appears in an entry marked DONE,
17314 it is not shown. A numeric prefix argument NDAYS can be used to test that
17315 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17316 are shown."
17317 (interactive "P")
17318 (let* ((org-warn-days
17319 (cond
17320 ((equal ndays '(4)) 100000)
17321 (ndays (prefix-numeric-value ndays))
17322 (t (abs org-deadline-warning-days))))
17323 (case-fold-search nil)
17324 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17325 (callback
17326 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17327 (message "%d deadlines past-due or due within %d days"
17328 (org-occur regexp nil callback)
17329 org-warn-days)))
17331 (defsubst org-re-timestamp (type)
17332 "Return a regexp for timestamp TYPE.
17333 Allowed values for TYPE are:
17335 all: all timestamps
17336 active: only active timestamps (<...>)
17337 inactive: only inactive timestamps ([...])
17338 scheduled: only scheduled timestamps
17339 deadline: only deadline timestamps
17340 closed: only closed time-stamps
17342 When TYPE is nil, fall back on returning a regexp that matches
17343 both scheduled and deadline timestamps."
17344 (cl-case type
17345 (all org-ts-regexp-both)
17346 (active org-ts-regexp)
17347 (inactive org-ts-regexp-inactive)
17348 (scheduled org-scheduled-time-regexp)
17349 (deadline org-deadline-time-regexp)
17350 (closed org-closed-time-regexp)
17351 (otherwise
17352 (concat "\\<"
17353 (regexp-opt (list org-deadline-string org-scheduled-string))
17354 " *<\\([^>]+\\)>"))))
17356 (defun org-check-before-date (d)
17357 "Check if there are deadlines or scheduled entries before date D."
17358 (interactive (list (org-read-date)))
17359 (let* ((case-fold-search nil)
17360 (regexp (org-re-timestamp org-ts-type))
17361 (ts-type org-ts-type)
17362 (callback
17363 (lambda ()
17364 (let ((match (match-string 1)))
17365 (and (if (memq ts-type '(active inactive all))
17366 (eq (org-element-type (save-excursion
17367 (backward-char)
17368 (org-element-context)))
17369 'timestamp)
17370 (org-at-planning-p))
17371 (time-less-p
17372 (org-time-string-to-time match t)
17373 (org-time-string-to-time d t)))))))
17374 (message "%d entries before %s"
17375 (org-occur regexp nil callback)
17376 d)))
17378 (defun org-check-after-date (d)
17379 "Check if there are deadlines or scheduled entries after date D."
17380 (interactive (list (org-read-date)))
17381 (let* ((case-fold-search nil)
17382 (regexp (org-re-timestamp org-ts-type))
17383 (ts-type org-ts-type)
17384 (callback
17385 (lambda ()
17386 (let ((match (match-string 1)))
17387 (and (if (memq ts-type '(active inactive all))
17388 (eq (org-element-type (save-excursion
17389 (backward-char)
17390 (org-element-context)))
17391 'timestamp)
17392 (org-at-planning-p))
17393 (not (time-less-p
17394 (org-time-string-to-time match t)
17395 (org-time-string-to-time d t))))))))
17396 (message "%d entries after %s"
17397 (org-occur regexp nil callback)
17398 d)))
17400 (defun org-check-dates-range (start-date end-date)
17401 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17402 (interactive (list (org-read-date nil nil nil "Range starts")
17403 (org-read-date nil nil nil "Range end")))
17404 (let ((case-fold-search nil)
17405 (regexp (org-re-timestamp org-ts-type))
17406 (callback
17407 (let ((type org-ts-type))
17408 (lambda ()
17409 (let ((match (match-string 1)))
17410 (and
17411 (if (memq type '(active inactive all))
17412 (eq (org-element-type (save-excursion
17413 (backward-char)
17414 (org-element-context)))
17415 'timestamp)
17416 (org-at-planning-p))
17417 (not (time-less-p
17418 (org-time-string-to-time match t)
17419 (org-time-string-to-time start-date t)))
17420 (time-less-p
17421 (org-time-string-to-time match t)
17422 (org-time-string-to-time end-date t))))))))
17423 (message "%d entries between %s and %s"
17424 (org-occur regexp nil callback) start-date end-date)))
17426 (defun org-evaluate-time-range (&optional to-buffer)
17427 "Evaluate a time range by computing the difference between start and end.
17428 Normally the result is just printed in the echo area, but with prefix arg
17429 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17430 If the time range is actually in a table, the result is inserted into the
17431 next column.
17432 For time difference computation, a year is assumed to be exactly 365
17433 days in order to avoid rounding problems."
17434 (interactive "P")
17436 (org-clock-update-time-maybe)
17437 (save-excursion
17438 (unless (org-at-date-range-p t)
17439 (goto-char (point-at-bol))
17440 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17441 (unless (org-at-date-range-p t)
17442 (user-error "Not at a time-stamp range, and none found in current line")))
17443 (let* ((ts1 (match-string 1))
17444 (ts2 (match-string 2))
17445 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17446 (match-end (match-end 0))
17447 (time1 (org-time-string-to-time ts1))
17448 (time2 (org-time-string-to-time ts2))
17449 (t1 (float-time time1))
17450 (t2 (float-time time2))
17451 (diff (abs (- t2 t1)))
17452 (negative (< (- t2 t1) 0))
17453 ;; (ys (floor (* 365 24 60 60)))
17454 (ds (* 24 60 60))
17455 (hs (* 60 60))
17456 (fy "%dy %dd %02d:%02d")
17457 (fy1 "%dy %dd")
17458 (fd "%dd %02d:%02d")
17459 (fd1 "%dd")
17460 (fh "%02d:%02d")
17461 y d h m align)
17462 (if havetime
17463 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17465 d (floor (/ diff ds)) diff (mod diff ds)
17466 h (floor (/ diff hs)) diff (mod diff hs)
17467 m (floor (/ diff 60)))
17468 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17470 d (floor (+ (/ diff ds) 0.5))
17471 h 0 m 0))
17472 (if (not to-buffer)
17473 (message "%s" (org-make-tdiff-string y d h m))
17474 (if (org-at-table-p)
17475 (progn
17476 (goto-char match-end)
17477 (setq align t)
17478 (and (looking-at " *|") (goto-char (match-end 0))))
17479 (goto-char match-end))
17480 (when (looking-at
17481 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17482 (replace-match ""))
17483 (when negative (insert " -"))
17484 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17485 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17486 (insert " " (format fh h m))))
17487 (when align (org-table-align))
17488 (message "Time difference inserted")))))
17490 (defun org-make-tdiff-string (y d h m)
17491 (let ((fmt "")
17492 (l nil))
17493 (when (> y 0)
17494 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17495 (push y l))
17496 (when (> d 0)
17497 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17498 (push d l))
17499 (when (> h 0)
17500 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17501 (push h l))
17502 (when (> m 0)
17503 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17504 (push m l))
17505 (apply 'format fmt (nreverse l))))
17507 (defun org-time-string-to-time (s &optional zone)
17508 "Convert timestamp string S into internal time.
17509 The optional ZONE is omitted or nil for Emacs local time, t for
17510 Universal Time, ‘wall’ for system wall clock time, or a string as
17511 in the TZ environment variable."
17512 (apply #'encode-time (org-parse-time-string s nil zone)))
17514 (defun org-time-string-to-seconds (s &optional zone)
17515 "Convert a timestamp string S into a number of seconds.
17516 The optional ZONE is omitted or nil for Emacs local time, t for
17517 Universal Time, ‘wall’ for system wall clock time, or a string as
17518 in the TZ environment variable."
17519 (float-time (org-time-string-to-time s zone)))
17521 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17523 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17524 "Convert time stamp S to an absolute day number.
17526 If DAYNR in non-nil, and there is a specifier for a cyclic time
17527 stamp, get the closest date to DAYNR. If PREFER is
17528 `past' (respectively `future') return a date past (respectively
17529 after) or equal to DAYNR.
17531 POS is the location of time stamp S, as a buffer position in
17532 BUFFER.
17534 Diary sexp timestamps are matched against DAYNR, when non-nil.
17535 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17536 signaled."
17537 (cond
17538 ((string-match "\\`%%\\((.*)\\)" s)
17539 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17540 ;; only able to match individual dates. If it fails, raise an
17541 ;; error.
17542 (if (and daynr
17543 (org-diary-sexp-entry
17544 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17545 daynr
17546 (signal 'org-diary-sexp-no-match (list s))))
17547 (daynr (org-closest-date s daynr prefer))
17548 (t (time-to-days
17549 (condition-case errdata
17550 (apply #'encode-time (org-parse-time-string s))
17551 (error (error "Bad timestamp `%s'%s\nError was: %s"
17553 (if (not (and buffer pos)) ""
17554 (format-message " at %d in buffer `%s'" pos buffer))
17555 (cdr errdata))))))))
17557 (defun org-days-to-iso-week (days)
17558 "Return the iso week number."
17559 (require 'cal-iso)
17560 (car (calendar-iso-from-absolute days)))
17562 (defun org-small-year-to-year (year)
17563 "Convert 2-digit years into 4-digit years.
17564 YEAR is expanded into one of the 30 next years, if possible, or
17565 into a past one. Any year larger than 99 is returned unchanged."
17566 (if (>= year 100) year
17567 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17568 (century (/ current 100))
17569 (offset (- year (% current 100))))
17570 (cond ((> offset 30) (+ (* (1- century) 100) year))
17571 ((> offset -70) (+ (* century 100) year))
17572 (t (+ (* (1+ century) 100) year))))))
17574 (defun org-time-from-absolute (d)
17575 "Return the time corresponding to date D.
17576 D may be an absolute day number, or a calendar-type list (month day year)."
17577 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17578 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17580 (defvar org-agenda-current-date)
17581 (defun org-calendar-holiday ()
17582 "List of holidays, for Diary display in Org mode."
17583 (require 'holidays)
17584 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17585 (and hl (mapconcat #'identity hl "; "))))
17587 (defun org-diary-sexp-entry (sexp entry d)
17588 "Process a SEXP diary ENTRY for date D."
17589 (require 'diary-lib)
17590 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17591 ;; dynamically.
17592 (let* ((sexp `(let ((entry ,entry)
17593 (date ',d))
17594 ,(car (read-from-string sexp))))
17595 (result (if calendar-debug-sexp (eval sexp)
17596 (condition-case nil
17597 (eval sexp)
17598 (error
17599 (beep)
17600 (message "Bad sexp at line %d in %s: %s"
17601 (org-current-line)
17602 (buffer-file-name) sexp)
17603 (sleep-for 2))))))
17604 (cond ((stringp result) (split-string result "; "))
17605 ((and (consp result)
17606 (not (consp (cdr result)))
17607 (stringp (cdr result))) (cdr result))
17608 ((and (consp result)
17609 (stringp (car result))) result)
17610 (result entry))))
17612 (defun org-diary-to-ical-string (frombuf)
17613 "Get iCalendar entries from diary entries in buffer FROMBUF.
17614 This uses the icalendar.el library."
17615 (let* ((tmpdir temporary-file-directory)
17616 (tmpfile (make-temp-name
17617 (expand-file-name "orgics" tmpdir)))
17618 buf rtn b e)
17619 (with-current-buffer frombuf
17620 (icalendar-export-region (point-min) (point-max) tmpfile)
17621 (setq buf (find-buffer-visiting tmpfile))
17622 (set-buffer buf)
17623 (goto-char (point-min))
17624 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17625 (setq b (match-beginning 0)))
17626 (goto-char (point-max))
17627 (when (re-search-backward "^END:VEVENT" nil t)
17628 (setq e (match-end 0)))
17629 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17630 (kill-buffer buf)
17631 (delete-file tmpfile)
17632 rtn))
17634 (defun org-closest-date (start current prefer)
17635 "Return closest date to CURRENT starting from START.
17637 CURRENT and START are both time stamps.
17639 When PREFER is `past', return a date that is either CURRENT or
17640 past. When PREFER is `future', return a date that is either
17641 CURRENT or future.
17643 Only time stamps with a repeater are modified. Any other time
17644 stamp stay unchanged. In any case, return value is an absolute
17645 day number."
17646 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17647 ;; No repeater. Do not shift time stamp.
17648 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17649 (let ((value (string-to-number (match-string 1 start)))
17650 (type (match-string 2 start)))
17651 (if (= 0 value)
17652 ;; Repeater with a 0-value is considered as void.
17653 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17654 (let* ((base (org-date-to-gregorian start))
17655 (target (org-date-to-gregorian current))
17656 (sday (calendar-absolute-from-gregorian base))
17657 (cday (calendar-absolute-from-gregorian target))
17658 n1 n2)
17659 ;; If START is already past CURRENT, just return START.
17660 (if (<= cday sday) sday
17661 ;; Compute closest date before (N1) and closest date past
17662 ;; (N2) CURRENT.
17663 (pcase type
17664 ("h"
17665 (let ((missing-hours
17666 (mod (+ (- (* 24 (- cday sday))
17667 (nth 2 (org-parse-time-string start)))
17668 org-extend-today-until)
17669 value)))
17670 (setf n1 (if (= missing-hours 0) cday
17671 (- cday (1+ (/ missing-hours 24)))))
17672 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17673 ((or "d" "w")
17674 (let ((value (if (equal type "w") (* 7 value) value)))
17675 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17676 (setf n2 (+ n1 value))))
17677 ("m"
17678 (let* ((add-months
17679 (lambda (d n)
17680 ;; Add N months to gregorian date D, i.e.,
17681 ;; a list (MONTH DAY YEAR). Return a valid
17682 ;; gregorian date.
17683 (let ((m (+ (nth 0 d) n)))
17684 (list (mod m 12)
17685 (nth 1 d)
17686 (+ (/ m 12) (nth 2 d))))))
17687 (months ; Complete months to TARGET.
17688 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17689 (- (nth 0 target) (nth 0 base))
17690 ;; If START's day is greater than
17691 ;; TARGET's, remove incomplete month.
17692 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17693 value)
17694 value))
17695 (before (funcall add-months base months)))
17696 (setf n1 (calendar-absolute-from-gregorian before))
17697 (setf n2
17698 (calendar-absolute-from-gregorian
17699 (funcall add-months before value)))))
17701 (let* ((d (nth 1 base))
17702 (m (nth 0 base))
17703 (y (nth 2 base))
17704 (years ; Complete years to TARGET.
17705 (* (/ (- (nth 2 target)
17707 ;; If START's month and day are
17708 ;; greater than TARGET's, remove
17709 ;; incomplete year.
17710 (if (or (> (nth 0 target) m)
17711 (and (= (nth 0 target) m)
17712 (> (nth 1 target) d)))
17715 value)
17716 value))
17717 (before (list m d (+ y years))))
17718 (setf n1 (calendar-absolute-from-gregorian before))
17719 (setf n2 (calendar-absolute-from-gregorian
17720 (list m d (+ (nth 2 before) value)))))))
17721 ;; Handle PREFER parameter, if any.
17722 (cond
17723 ((eq prefer 'past) (if (= cday n2) n2 n1))
17724 ((eq prefer 'future) (if (= cday n1) n1 n2))
17725 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17727 (defun org-date-to-gregorian (d)
17728 "Turn any specification of date D into a Gregorian date for the calendar."
17729 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17730 ((and (listp d) (= (length d) 3)) d)
17731 ((stringp d)
17732 (let ((d (org-parse-time-string d)))
17733 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17734 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17736 (defun org-parse-time-string (s &optional nodefault zone)
17737 "Parse the standard Org time string.
17739 This should be a lot faster than the normal `parse-time-string'.
17741 If time is not given, defaults to 0:00. However, with optional
17742 NODEFAULT, hour and minute fields will be nil if not given.
17744 The optional ZONE is omitted or nil for Emacs local time, t for
17745 Universal Time, ‘wall’ for system wall clock time, or a string as
17746 in the TZ environment variable."
17747 (cond ((string-match org-ts-regexp0 s)
17748 (list 0
17749 (when (or (match-beginning 8) (not nodefault))
17750 (string-to-number (or (match-string 8 s) "0")))
17751 (when (or (match-beginning 7) (not nodefault))
17752 (string-to-number (or (match-string 7 s) "0")))
17753 (string-to-number (match-string 4 s))
17754 (string-to-number (match-string 3 s))
17755 (string-to-number (match-string 2 s))
17756 nil nil zone))
17757 ((string-match "^<[^>]+>$" s)
17758 ;; FIXME: `decode-time' needs to be called with ZONE as its
17759 ;; second argument. However, this requires at least Emacs
17760 ;; 25.1. We can do it when we switch to this version as our
17761 ;; minimal requirement.
17762 (decode-time (seconds-to-time (org-matcher-time s))))
17763 (t (error "Not a standard Org time string: %s" s))))
17765 (defun org-timestamp-up (&optional arg)
17766 "Increase the date item at the cursor by one.
17767 If the cursor is on the year, change the year. If it is on the month,
17768 the day or the time, change that.
17769 With prefix ARG, change by that many units."
17770 (interactive "p")
17771 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17773 (defun org-timestamp-down (&optional arg)
17774 "Decrease the date item at the cursor by one.
17775 If the cursor is on the year, change the year. If it is on the month,
17776 the day or the time, change that.
17777 With prefix ARG, change by that many units."
17778 (interactive "p")
17779 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17781 (defun org-timestamp-up-day (&optional arg)
17782 "Increase the date in the time stamp by one day.
17783 With prefix ARG, change that many days."
17784 (interactive "p")
17785 (if (and (not (org-at-timestamp-p 'lax))
17786 (org-at-heading-p))
17787 (org-todo 'up)
17788 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17790 (defun org-timestamp-down-day (&optional arg)
17791 "Decrease the date in the time stamp by one day.
17792 With prefix ARG, change that many days."
17793 (interactive "p")
17794 (if (and (not (org-at-timestamp-p 'lax))
17795 (org-at-heading-p))
17796 (org-todo 'down)
17797 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17799 (defun org-at-timestamp-p (&optional extended)
17800 "Non-nil if point is inside a timestamp.
17802 By default, the function only consider syntactically valid active
17803 timestamps. However, the caller may have a broader definition
17804 for timestamps. As a consequence, optional argument EXTENDED can
17805 be set to the following values
17807 `inactive'
17809 Include also syntactically valid inactive timestamps.
17811 `agenda'
17813 Include timestamps allowed in Agenda, i.e., those in
17814 properties drawers, planning lines and clock lines.
17816 `lax'
17818 Ignore context. The function matches any part of the
17819 document looking like a timestamp. This includes comments,
17820 example blocks...
17822 For backward-compatibility with Org 9.0, every other non-nil
17823 value is equivalent to `inactive'.
17825 When at a timestamp, return the position of the point as a symbol
17826 among `bracket', `after', `year', `month', `hour', `minute',
17827 `day' or a number of character from the last know part of the
17828 time stamp.
17830 When matching, the match groups are the following:
17831 group 1: year
17832 group 2: month
17833 group 3: day number
17834 group 4: day name
17835 group 5: hours, if any
17836 group 6: minutes, if any"
17837 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17838 (pos (point))
17839 (match?
17840 (let ((boundaries (org-in-regexp regexp)))
17841 (save-match-data
17842 (cond ((null boundaries) nil)
17843 ((eq extended 'lax) t)
17845 (or (and (eq extended 'agenda)
17846 (or (org-at-planning-p)
17847 (org-at-property-p)
17848 (and (bound-and-true-p
17849 org-agenda-include-inactive-timestamps)
17850 (org-at-clock-log-p))))
17851 (eq 'timestamp
17852 (save-excursion
17853 (when (= pos (cdr boundaries)) (forward-char -1))
17854 (org-element-type (org-element-context)))))))))))
17855 (cond
17856 ((not match?) nil)
17857 ((= pos (match-beginning 0)) 'bracket)
17858 ;; Distinguish location right before the closing bracket from
17859 ;; right after it.
17860 ((= pos (1- (match-end 0))) 'bracket)
17861 ((= pos (match-end 0)) 'after)
17862 ((org-pos-in-match-range pos 2) 'year)
17863 ((org-pos-in-match-range pos 3) 'month)
17864 ((org-pos-in-match-range pos 7) 'hour)
17865 ((org-pos-in-match-range pos 8) 'minute)
17866 ((or (org-pos-in-match-range pos 4)
17867 (org-pos-in-match-range pos 5)) 'day)
17868 ((and (> pos (or (match-end 8) (match-end 5)))
17869 (< pos (match-end 0)))
17870 (- pos (or (match-end 8) (match-end 5))))
17871 (t 'day))))
17873 (defun org-toggle-timestamp-type ()
17874 "Toggle the type (<active> or [inactive]) of a time stamp."
17875 (interactive)
17876 (when (org-at-timestamp-p 'lax)
17877 (let ((beg (match-beginning 0)) (end (match-end 0))
17878 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17879 (save-excursion
17880 (goto-char beg)
17881 (while (re-search-forward "[][<>]" end t)
17882 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17883 t t)))
17884 (message "Timestamp is now %sactive"
17885 (if (equal (char-after beg) ?<) "" "in")))))
17887 (defun org-at-clock-log-p ()
17888 "Non-nil if point is on a clock log line."
17889 (and (org-match-line org-clock-line-re)
17890 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17892 (defvar org-clock-history) ; defined in org-clock.el
17893 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17894 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17895 "Change the date in the time stamp at point.
17896 The date will be changed by N times WHAT. WHAT can be `day', `month',
17897 `year', `minute', `second'. If WHAT is not given, the cursor position
17898 in the timestamp determines what will be changed.
17899 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17900 (let ((origin (point))
17901 (timestamp? (org-at-timestamp-p 'lax))
17902 origin-cat
17903 with-hm inactive
17904 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17905 extra rem
17906 ts time time0 fixnext clrgx)
17907 (unless timestamp? (user-error "Not at a timestamp"))
17908 (if (and (not what) (eq timestamp? 'bracket))
17909 (org-toggle-timestamp-type)
17910 ;; Point isn't on brackets. Remember the part of the time-stamp
17911 ;; the point was in. Indeed, size of time-stamps may change,
17912 ;; but point must be kept in the same category nonetheless.
17913 (setq origin-cat timestamp?)
17914 (when (and (not what) (not (eq timestamp? 'day))
17915 org-display-custom-times
17916 (get-text-property (point) 'display)
17917 (not (get-text-property (1- (point)) 'display)))
17918 (setq timestamp? 'day))
17919 (setq timestamp? (or what timestamp?)
17920 inactive (= (char-after (match-beginning 0)) ?\[)
17921 ts (match-string 0))
17922 (replace-match "")
17923 (when (string-match
17924 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17926 (setq extra (match-string 1 ts))
17927 (when suppress-tmp-delay
17928 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17929 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17930 (setq with-hm t))
17931 (setq time0 (org-parse-time-string ts))
17932 (when (and updown
17933 (eq timestamp? 'minute)
17934 (not current-prefix-arg))
17935 ;; This looks like s-up and s-down. Change by one rounding step.
17936 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17937 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17938 (setcar (cdr time0) (+ (nth 1 time0)
17939 (if (> n 0) (- rem) (- dm rem))))))
17940 (setq time
17941 (apply #'encode-time
17942 (or (car time0) 0)
17943 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17944 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17945 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17946 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17947 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17948 (nthcdr 6 time0)))
17949 (when (and (memq timestamp? '(hour minute))
17950 extra
17951 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17952 (setq extra (org-modify-ts-extra
17953 extra
17954 (if (eq timestamp? 'hour) 2 5)
17955 n dm)))
17956 (when (integerp timestamp?)
17957 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17958 (when (eq what 'calendar)
17959 (let ((cal-date (org-get-date-from-calendar)))
17960 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17961 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17962 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17963 (setcar time0 (or (car time0) 0))
17964 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17965 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17966 (setq time (apply 'encode-time time0))))
17967 ;; Insert the new time-stamp, and ensure point stays in the same
17968 ;; category as before (i.e. not after the last position in that
17969 ;; category).
17970 (let ((pos (point)))
17971 ;; Stay before inserted string. `save-excursion' is of no use.
17972 (setq org-last-changed-timestamp
17973 (org-insert-time-stamp time with-hm inactive nil nil extra))
17974 (goto-char pos))
17975 (save-match-data
17976 (looking-at org-ts-regexp3)
17977 (goto-char
17978 (pcase origin-cat
17979 ;; `day' category ends before `hour' if any, or at the end
17980 ;; of the day name.
17981 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17982 (`hour (min (match-end 7) origin))
17983 (`minute (min (1- (match-end 8)) origin))
17984 ((pred integerp) (min (1- (match-end 0)) origin))
17985 ;; Point was right after the time-stamp. However, the
17986 ;; time-stamp length might have changed, so refer to
17987 ;; (match-end 0) instead.
17988 (`after (match-end 0))
17989 ;; `year' and `month' have both fixed size: point couldn't
17990 ;; have moved into another part.
17991 (_ origin))))
17992 ;; Update clock if on a CLOCK line.
17993 (org-clock-update-time-maybe)
17994 ;; Maybe adjust the closest clock in `org-clock-history'
17995 (when org-clock-adjust-closest
17996 (if (not (and (org-at-clock-log-p)
17997 (< 1 (length (delq nil (mapcar 'marker-position
17998 org-clock-history))))))
17999 (message "No clock to adjust")
18000 (cond ((save-excursion ; fix previous clock?
18001 (re-search-backward org-ts-regexp0 nil t)
18002 (looking-back (concat org-clock-string " \\[")
18003 (line-beginning-position)))
18004 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18005 ((save-excursion ; fix next clock?
18006 (re-search-backward org-ts-regexp0 nil t)
18007 (looking-at (concat org-ts-regexp0 "\\] =>")))
18008 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18009 (save-window-excursion
18010 ;; Find closest clock to point, adjust the previous/next one in history
18011 (let* ((p (save-excursion (org-back-to-heading t)))
18012 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18013 (clfixnth
18014 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18015 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18016 (if (not clfixpos)
18017 (message "No clock to adjust")
18018 (save-excursion
18019 (org-goto-marker-or-bmk clfixpos)
18020 (org-show-subtree)
18021 (when (re-search-forward clrgx nil t)
18022 (goto-char (match-beginning 1))
18023 (let (org-clock-adjust-closest)
18024 (org-timestamp-change n timestamp? updown))
18025 (message "Clock adjusted in %s for heading: %s"
18026 (file-name-nondirectory (buffer-file-name))
18027 (org-get-heading t t)))))))))
18028 ;; Try to recenter the calendar window, if any.
18029 (when (and org-calendar-follow-timestamp-change
18030 (get-buffer-window "*Calendar*" t)
18031 (memq timestamp? '(day month year)))
18032 (org-recenter-calendar (time-to-days time))))))
18034 (defun org-modify-ts-extra (s pos n dm)
18035 "Change the different parts of the lead-time and repeat fields in timestamp."
18036 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18037 ng h m new rem)
18038 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18039 (cond
18040 ((or (org-pos-in-match-range pos 2)
18041 (org-pos-in-match-range pos 3))
18042 (setq m (string-to-number (match-string 3 s))
18043 h (string-to-number (match-string 2 s)))
18044 (if (org-pos-in-match-range pos 2)
18045 (setq h (+ h n))
18046 (setq n (* dm (with-no-warnings (signum n))))
18047 (unless (= 0 (setq rem (% m dm)))
18048 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18049 (setq m (+ m n)))
18050 (when (< m 0) (setq m (+ m 60) h (1- h)))
18051 (when (> m 59) (setq m (- m 60) h (1+ h)))
18052 (setq h (mod h 24))
18053 (setq ng 1 new (format "-%02d:%02d" h m)))
18054 ((org-pos-in-match-range pos 6)
18055 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18056 ((org-pos-in-match-range pos 5)
18057 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18059 ((org-pos-in-match-range pos 9)
18060 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18061 ((org-pos-in-match-range pos 8)
18062 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18064 (when ng
18065 (setq s (concat
18066 (substring s 0 (match-beginning ng))
18068 (substring s (match-end ng))))))
18071 (defun org-recenter-calendar (d)
18072 "If the calendar is visible, recenter it to date D."
18073 (let ((cwin (get-buffer-window "*Calendar*" t)))
18074 (when cwin
18075 (let ((calendar-move-hook nil))
18076 (with-selected-window cwin
18077 (calendar-goto-date
18078 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18080 (defun org-goto-calendar (&optional arg)
18081 "Go to the Emacs calendar at the current date.
18082 If there is a time stamp in the current line, go to that date.
18083 A prefix ARG can be used to force the current date."
18084 (interactive "P")
18085 (let ((calendar-move-hook nil)
18086 (calendar-view-holidays-initially-flag nil)
18087 (calendar-view-diary-initially-flag nil)
18088 diff)
18089 (when (or (org-at-timestamp-p 'lax)
18090 (org-match-line (concat ".*" org-ts-regexp)))
18091 (let ((d1 (time-to-days (current-time)))
18092 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18093 (setq diff (- d2 d1))))
18094 (calendar)
18095 (calendar-goto-today)
18096 (when (and diff (not arg)) (calendar-forward-day diff))))
18098 (defun org-get-date-from-calendar ()
18099 "Return a list (month day year) of date at point in calendar."
18100 (with-current-buffer "*Calendar*"
18101 (save-match-data
18102 (calendar-cursor-to-date))))
18104 (defun org-date-from-calendar ()
18105 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18106 If there is already a time stamp at the cursor position, update it."
18107 (interactive)
18108 (if (org-at-timestamp-p 'lax)
18109 (org-timestamp-change 0 'calendar)
18110 (let ((cal-date (org-get-date-from-calendar)))
18111 (org-insert-time-stamp
18112 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18114 (defcustom org-effort-durations
18115 `(("min" . 1)
18116 ("h" . 60)
18117 ("d" . ,(* 60 8))
18118 ("w" . ,(* 60 8 5))
18119 ("m" . ,(* 60 8 5 4))
18120 ("y" . ,(* 60 8 5 40)))
18121 "Conversion factor to minutes for an effort modifier.
18123 Each entry has the form (MODIFIER . MINUTES).
18125 In an effort string, a number followed by MODIFIER is multiplied
18126 by the specified number of MINUTES to obtain an effort in
18127 minutes.
18129 For example, if the value of this variable is ((\"hours\" . 60)), then an
18130 effort string \"2hours\" is equivalent to 120 minutes."
18131 :group 'org-agenda
18132 :version "26.1"
18133 :package-version '(Org . "8.3")
18134 :type '(alist :key-type (string :tag "Modifier")
18135 :value-type (number :tag "Minutes")))
18137 (defcustom org-image-actual-width t
18138 "Should we use the actual width of images when inlining them?
18140 When set to t, always use the image width.
18142 When set to a number, use imagemagick (when available) to set
18143 the image's width to this value.
18145 When set to a number in a list, try to get the width from any
18146 #+ATTR.* keyword if it matches a width specification like
18148 #+ATTR_HTML: :width 300px
18150 and fall back on that number if none is found.
18152 When set to nil, try to get the width from an #+ATTR.* keyword
18153 and fall back on the original width if none is found.
18155 This requires Emacs >= 24.1, build with imagemagick support."
18156 :group 'org-appearance
18157 :version "24.4"
18158 :package-version '(Org . "8.0")
18159 :type '(choice
18160 (const :tag "Use the image width" t)
18161 (integer :tag "Use a number of pixels")
18162 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18163 (const :tag "Use #+ATTR* or don't resize" nil)))
18165 (defcustom org-agenda-inhibit-startup nil
18166 "Inhibit startup when preparing agenda buffers.
18167 When this variable is t, the initialization of the Org agenda
18168 buffers is inhibited: e.g. the visibility state is not set, the
18169 tables are not re-aligned, etc."
18170 :type 'boolean
18171 :version "24.3"
18172 :group 'org-agenda)
18174 (defcustom org-agenda-ignore-properties nil
18175 "Avoid updating text properties when building the agenda.
18176 Properties are used to prepare buffers for effort estimates,
18177 appointments, statistics and subtree-local categories.
18178 If you don't use these in the agenda, you can add them to this
18179 list and agenda building will be a bit faster.
18180 The value is a list, with zero or more of the symbols `effort', `appt',
18181 `stats' or `category'."
18182 :type '(set :greedy t
18183 (const effort)
18184 (const appt)
18185 (const stats)
18186 (const category))
18187 :version "26.1"
18188 :package-version '(Org . "8.3")
18189 :group 'org-agenda)
18191 ;;;; Files
18193 (defun org-save-all-org-buffers ()
18194 "Save all Org buffers without user confirmation."
18195 (interactive)
18196 (message "Saving all Org buffers...")
18197 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18198 (when (featurep 'org-id) (org-id-locations-save))
18199 (message "Saving all Org buffers... done"))
18201 (defun org-revert-all-org-buffers ()
18202 "Revert all Org buffers.
18203 Prompt for confirmation when there are unsaved changes.
18204 Be sure you know what you are doing before letting this function
18205 overwrite your changes.
18207 This function is useful in a setup where one tracks org files
18208 with a version control system, to revert on one machine after pulling
18209 changes from another. I believe the procedure must be like this:
18211 1. M-x org-save-all-org-buffers
18212 2. Pull changes from the other machine, resolve conflicts
18213 3. M-x org-revert-all-org-buffers"
18214 (interactive)
18215 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18216 (user-error "Abort"))
18217 (save-excursion
18218 (save-window-excursion
18219 (dolist (b (buffer-list))
18220 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18221 (with-current-buffer b buffer-file-name))
18222 (pop-to-buffer-same-window b)
18223 (revert-buffer t 'no-confirm)))
18224 (when (and (featurep 'org-id) org-id-track-globally)
18225 (org-id-locations-load)))))
18227 ;;;; Agenda files
18229 ;;;###autoload
18230 (defun org-switchb (&optional arg)
18231 "Switch between Org buffers.
18233 With `\\[universal-argument]' prefix, restrict available buffers to files.
18235 With `\\[universal-argument] \\[universal-argument]' \
18236 prefix, restrict available buffers to agenda files."
18237 (interactive "P")
18238 (let ((blist (org-buffer-list
18239 (cond ((equal arg '(4)) 'files)
18240 ((equal arg '(16)) 'agenda)))))
18241 (pop-to-buffer-same-window
18242 (completing-read "Org buffer: "
18243 (mapcar #'list (mapcar #'buffer-name blist))
18244 nil t))))
18246 (defun org-buffer-list (&optional predicate exclude-tmp)
18247 "Return a list of Org buffers.
18248 PREDICATE can be `export', `files' or `agenda'.
18250 export restrict the list to Export buffers.
18251 files restrict the list to buffers visiting Org files.
18252 agenda restrict the list to buffers visiting agenda files.
18254 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18255 (let* ((bfn nil)
18256 (agenda-files (and (eq predicate 'agenda)
18257 (mapcar 'file-truename (org-agenda-files t))))
18258 (filter
18259 (cond
18260 ((eq predicate 'files)
18261 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18262 ((eq predicate 'export)
18263 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18264 ((eq predicate 'agenda)
18265 (lambda (b)
18266 (with-current-buffer b
18267 (and (derived-mode-p 'org-mode)
18268 (setq bfn (buffer-file-name b))
18269 (member (file-truename bfn) agenda-files)))))
18270 (t (lambda (b) (with-current-buffer b
18271 (or (derived-mode-p 'org-mode)
18272 (string-match "\\*Org .*Export"
18273 (buffer-name b)))))))))
18274 (delq nil
18275 (mapcar
18276 (lambda(b)
18277 (if (and (funcall filter b)
18278 (or (not exclude-tmp)
18279 (not (string-match "tmp" (buffer-name b)))))
18281 nil))
18282 (buffer-list)))))
18284 (defun org-agenda-files (&optional unrestricted archives)
18285 "Get the list of agenda files.
18286 Optional UNRESTRICTED means return the full list even if a restriction
18287 is currently in place.
18288 When ARCHIVES is t, include all archive files that are really being
18289 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18290 `org-agenda-archives-mode' is t."
18291 (let ((files
18292 (cond
18293 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18294 ((stringp org-agenda-files) (org-read-agenda-file-list))
18295 ((listp org-agenda-files) org-agenda-files)
18296 (t (error "Invalid value of `org-agenda-files'")))))
18297 (setq files (apply 'append
18298 (mapcar (lambda (f)
18299 (if (file-directory-p f)
18300 (directory-files
18301 f t org-agenda-file-regexp)
18302 (list f)))
18303 files)))
18304 (when org-agenda-skip-unavailable-files
18305 (setq files (delq nil
18306 (mapcar (function
18307 (lambda (file)
18308 (and (file-readable-p file) file)))
18309 files))))
18310 (when (or (eq archives t)
18311 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18312 (setq files (org-add-archive-files files)))
18313 files))
18315 (defun org-agenda-file-p (&optional file)
18316 "Return non-nil, if FILE is an agenda file.
18317 If FILE is omitted, use the file associated with the current
18318 buffer."
18319 (let ((fname (or file (buffer-file-name))))
18320 (and fname
18321 (member (file-truename fname)
18322 (mapcar #'file-truename (org-agenda-files t))))))
18324 (defun org-edit-agenda-file-list ()
18325 "Edit the list of agenda files.
18326 Depending on setup, this either uses customize to edit the variable
18327 `org-agenda-files', or it visits the file that is holding the list. In the
18328 latter case, the buffer is set up in a way that saving it automatically kills
18329 the buffer and restores the previous window configuration."
18330 (interactive)
18331 (if (stringp org-agenda-files)
18332 (let ((cw (current-window-configuration)))
18333 (find-file org-agenda-files)
18334 (setq-local org-window-configuration cw)
18335 (add-hook 'after-save-hook
18336 (lambda ()
18337 (set-window-configuration
18338 (prog1 org-window-configuration
18339 (kill-buffer (current-buffer))))
18340 (org-install-agenda-files-menu)
18341 (message "New agenda file list installed"))
18342 nil 'local)
18343 (message "%s" (substitute-command-keys
18344 "Edit list and finish with \\[save-buffer]")))
18345 (customize-variable 'org-agenda-files)))
18347 (defun org-store-new-agenda-file-list (list)
18348 "Set new value for the agenda file list and save it correctly."
18349 (if (stringp org-agenda-files)
18350 (let ((fe (org-read-agenda-file-list t)) b u)
18351 (while (setq b (find-buffer-visiting org-agenda-files))
18352 (kill-buffer b))
18353 (with-temp-file org-agenda-files
18354 (insert
18355 (mapconcat
18356 (lambda (f) ;; Keep un-expanded entries.
18357 (if (setq u (assoc f fe))
18358 (cdr u)
18360 list "\n")
18361 "\n")))
18362 (let ((org-mode-hook nil) (org-inhibit-startup t)
18363 (org-insert-mode-line-in-empty-file nil))
18364 (setq org-agenda-files list)
18365 (customize-save-variable 'org-agenda-files org-agenda-files))))
18367 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18368 "Read the list of agenda files from a file.
18369 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18370 filenames, used by `org-store-new-agenda-file-list' to write back
18371 un-expanded file names."
18372 (when (file-directory-p org-agenda-files)
18373 (error "`org-agenda-files' cannot be a single directory"))
18374 (when (stringp org-agenda-files)
18375 (with-temp-buffer
18376 (insert-file-contents org-agenda-files)
18377 (mapcar
18378 (lambda (f)
18379 (let ((e (expand-file-name (substitute-in-file-name f)
18380 org-directory)))
18381 (if pair-with-expansion
18382 (cons e f)
18383 e)))
18384 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18386 ;;;###autoload
18387 (defun org-cycle-agenda-files ()
18388 "Cycle through the files in `org-agenda-files'.
18389 If the current buffer visits an agenda file, find the next one in the list.
18390 If the current buffer does not, find the first agenda file."
18391 (interactive)
18392 (let* ((fs (or (org-agenda-files t)
18393 (user-error "No agenda files")))
18394 (files (copy-sequence fs))
18395 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18396 file)
18397 (when tcf
18398 (while (and (setq file (pop files))
18399 (not (equal (file-truename file) tcf)))))
18400 (find-file (car (or files fs)))
18401 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18403 (defun org-agenda-file-to-front (&optional to-end)
18404 "Move/add the current file to the top of the agenda file list.
18405 If the file is not present in the list, it is added to the front. If it is
18406 present, it is moved there. With optional argument TO-END, add/move to the
18407 end of the list."
18408 (interactive "P")
18409 (let ((org-agenda-skip-unavailable-files nil)
18410 (file-alist (mapcar (lambda (x)
18411 (cons (file-truename x) x))
18412 (org-agenda-files t)))
18413 (ctf (file-truename
18414 (or buffer-file-name
18415 (user-error "Please save the current buffer to a file"))))
18416 x had)
18417 (setq x (assoc ctf file-alist) had x)
18419 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18420 (if to-end
18421 (setq file-alist (append (delq x file-alist) (list x)))
18422 (setq file-alist (cons x (delq x file-alist))))
18423 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18424 (org-install-agenda-files-menu)
18425 (message "File %s to %s of agenda file list"
18426 (if had "moved" "added") (if to-end "end" "front"))))
18428 (defun org-remove-file (&optional file)
18429 "Remove current file from the list of files in variable `org-agenda-files'.
18430 These are the files which are being checked for agenda entries.
18431 Optional argument FILE means use this file instead of the current."
18432 (interactive)
18433 (let* ((org-agenda-skip-unavailable-files nil)
18434 (file (or file buffer-file-name
18435 (user-error "Current buffer does not visit a file")))
18436 (true-file (file-truename file))
18437 (afile (abbreviate-file-name file))
18438 (files (delq nil (mapcar
18439 (lambda (x)
18440 (unless (equal true-file
18441 (file-truename x))
18443 (org-agenda-files t)))))
18444 (if (not (= (length files) (length (org-agenda-files t))))
18445 (progn
18446 (org-store-new-agenda-file-list files)
18447 (org-install-agenda-files-menu)
18448 (message "Removed from Org Agenda list: %s" afile))
18449 (message "File was not in list: %s (not removed)" afile))))
18451 (defun org-file-menu-entry (file)
18452 (vector file (list 'find-file file) t))
18454 (defun org-check-agenda-file (file)
18455 "Make sure FILE exists. If not, ask user what to do."
18456 (unless (file-exists-p file)
18457 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18458 (abbreviate-file-name file))
18459 (let ((r (downcase (read-char-exclusive))))
18460 (cond
18461 ((equal r ?r)
18462 (org-remove-file file)
18463 (throw 'nextfile t))
18464 (t (user-error "Abort"))))))
18466 (defun org-get-agenda-file-buffer (file)
18467 "Get an agenda buffer visiting FILE.
18468 If the buffer needs to be created, add it to the list of buffers
18469 which might be released later."
18470 (let ((buf (org-find-base-buffer-visiting file)))
18471 (if buf
18472 buf ; just return it
18473 ;; Make a new buffer and remember it
18474 (setq buf (find-file-noselect file))
18475 (when buf (push buf org-agenda-new-buffers))
18476 buf)))
18478 (defun org-release-buffers (blist)
18479 "Release all buffers in list, asking the user for confirmation when needed.
18480 When a buffer is unmodified, it is just killed. When modified, it is saved
18481 \(if the user agrees) and then killed."
18482 (let (file)
18483 (dolist (buf blist)
18484 (setq file (buffer-file-name buf))
18485 (when (and (buffer-modified-p buf)
18486 file
18487 (y-or-n-p (format "Save file %s? " file)))
18488 (with-current-buffer buf (save-buffer)))
18489 (kill-buffer buf))))
18491 (defun org-agenda-prepare-buffers (files)
18492 "Create buffers for all agenda files, protect archived trees and comments."
18493 (interactive)
18494 (let ((pa '(:org-archived t))
18495 (pc '(:org-comment t))
18496 (pall '(:org-archived t :org-comment t))
18497 (inhibit-read-only t)
18498 (org-inhibit-startup org-agenda-inhibit-startup)
18499 (rea (concat ":" org-archive-tag ":"))
18500 re pos)
18501 (setq org-tag-alist-for-agenda nil
18502 org-tag-groups-alist-for-agenda nil)
18503 (save-excursion
18504 (save-restriction
18505 (dolist (file files)
18506 (catch 'nextfile
18507 (if (bufferp file)
18508 (set-buffer file)
18509 (org-check-agenda-file file)
18510 (set-buffer (org-get-agenda-file-buffer file)))
18511 (widen)
18512 (org-set-regexps-and-options 'tags-only)
18513 (setq pos (point))
18514 (or (memq 'category org-agenda-ignore-properties)
18515 (org-refresh-category-properties))
18516 (or (memq 'stats org-agenda-ignore-properties)
18517 (org-refresh-stats-properties))
18518 (or (memq 'effort org-agenda-ignore-properties)
18519 (org-refresh-effort-properties))
18520 (or (memq 'appt org-agenda-ignore-properties)
18521 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18522 (setq org-todo-keywords-for-agenda
18523 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18524 (setq org-done-keywords-for-agenda
18525 (append org-done-keywords-for-agenda org-done-keywords))
18526 (setq org-todo-keyword-alist-for-agenda
18527 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18528 (setq org-tag-alist-for-agenda
18529 (org-uniquify
18530 (append org-tag-alist-for-agenda
18531 org-current-tag-alist)))
18532 ;; Merge current file's tag groups into global
18533 ;; `org-tag-groups-alist-for-agenda'.
18534 (when org-group-tags
18535 (dolist (alist org-tag-groups-alist)
18536 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18537 (if old
18538 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18539 (push alist org-tag-groups-alist-for-agenda)))))
18540 (org-with-silent-modifications
18541 (save-excursion
18542 (remove-text-properties (point-min) (point-max) pall)
18543 (when org-agenda-skip-archived-trees
18544 (goto-char (point-min))
18545 (while (re-search-forward rea nil t)
18546 (when (org-at-heading-p t)
18547 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18548 (goto-char (point-min))
18549 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18550 (while (re-search-forward re nil t)
18551 (when (save-match-data (org-in-commented-heading-p t))
18552 (add-text-properties
18553 (match-beginning 0) (org-end-of-subtree t) pc)))))
18554 (goto-char pos)))))
18555 (setq org-todo-keywords-for-agenda
18556 (org-uniquify org-todo-keywords-for-agenda))
18557 (setq org-todo-keyword-alist-for-agenda
18558 (org-uniquify org-todo-keyword-alist-for-agenda))))
18561 ;;;; CDLaTeX minor mode
18563 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18564 "Keymap for the minor `org-cdlatex-mode'.")
18566 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18567 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18568 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18569 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18570 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18572 (defvar org-cdlatex-texmathp-advice-is-done nil
18573 "Flag remembering if we have applied the advice to texmathp already.")
18575 (define-minor-mode org-cdlatex-mode
18576 "Toggle the minor `org-cdlatex-mode'.
18577 This mode supports entering LaTeX environment and math in LaTeX fragments
18578 in Org mode.
18579 \\{org-cdlatex-mode-map}"
18580 nil " OCDL" nil
18581 (when org-cdlatex-mode
18582 (require 'cdlatex)
18583 (run-hooks 'cdlatex-mode-hook)
18584 (cdlatex-compute-tables))
18585 (unless org-cdlatex-texmathp-advice-is-done
18586 (setq org-cdlatex-texmathp-advice-is-done t)
18587 (defadvice texmathp (around org-math-always-on activate)
18588 "Always return t in Org buffers.
18589 This is because we want to insert math symbols without dollars even outside
18590 the LaTeX math segments. If Org mode thinks that point is actually inside
18591 an embedded LaTeX fragment, let `texmathp' do its job.
18592 `\\[org-cdlatex-mode-map]'"
18593 (interactive)
18594 (let (p)
18595 (cond
18596 ((not (derived-mode-p 'org-mode)) ad-do-it)
18597 ((eq this-command 'cdlatex-math-symbol)
18598 (setq ad-return-value t
18599 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18601 (let ((p (org-inside-LaTeX-fragment-p)))
18602 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18603 (setq ad-return-value t
18604 texmathp-why '("Org mode embedded math" . 0))
18605 (when p ad-do-it)))))))))
18607 (defun turn-on-org-cdlatex ()
18608 "Unconditionally turn on `org-cdlatex-mode'."
18609 (org-cdlatex-mode 1))
18611 (defun org-try-cdlatex-tab ()
18612 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18613 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18614 - inside a LaTeX fragment, or
18615 - after the first word in a line, where an abbreviation expansion could
18616 insert a LaTeX environment."
18617 (when org-cdlatex-mode
18618 (cond
18619 ;; Before any word on the line: No expansion possible.
18620 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18621 ;; Just after first word on the line: Expand it. Make sure it
18622 ;; cannot happen on headlines, though.
18623 ((save-excursion
18624 (skip-chars-backward "a-zA-Z0-9*")
18625 (skip-chars-backward " \t")
18626 (and (bolp) (not (org-at-heading-p))))
18627 (cdlatex-tab) t)
18628 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18630 (defun org-cdlatex-underscore-caret (&optional _arg)
18631 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18632 Revert to the normal definition outside of these fragments."
18633 (interactive "P")
18634 (if (org-inside-LaTeX-fragment-p)
18635 (call-interactively 'cdlatex-sub-superscript)
18636 (let (org-cdlatex-mode)
18637 (call-interactively (key-binding (vector last-input-event))))))
18639 (defun org-cdlatex-math-modify (&optional _arg)
18640 "Execute `cdlatex-math-modify' in LaTeX fragments.
18641 Revert to the normal definition outside of these fragments."
18642 (interactive "P")
18643 (if (org-inside-LaTeX-fragment-p)
18644 (call-interactively 'cdlatex-math-modify)
18645 (let (org-cdlatex-mode)
18646 (call-interactively (key-binding (vector last-input-event))))))
18648 (defun org-cdlatex-environment-indent (&optional environment item)
18649 "Execute `cdlatex-environment' and indent the inserted environment.
18651 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18653 The inserted environment is indented to current indentation
18654 unless point is at the beginning of the line, in which the
18655 environment remains unintended."
18656 (interactive)
18657 ;; cdlatex-environment always return nil. Therefore, capture output
18658 ;; first and determine if an environment was selected.
18659 (let* ((beg (point-marker))
18660 (end (copy-marker (point) t))
18661 (inserted (progn
18662 (ignore-errors (cdlatex-environment environment item))
18663 (< beg end)))
18664 ;; Figure out how many lines to move forward after the
18665 ;; environment has been inserted.
18666 (lines (when inserted
18667 (save-excursion
18668 (- (cl-loop while (< beg (point))
18669 with x = 0
18670 do (forward-line -1)
18671 (cl-incf x)
18672 finally return x)
18673 (if (progn (goto-char beg)
18674 (and (progn (skip-chars-forward " \t") (eolp))
18675 (progn (skip-chars-backward " \t") (bolp))))
18676 1 0)))))
18677 (env (org-trim (delete-and-extract-region beg end))))
18678 (when inserted
18679 ;; Get indentation of next line unless at column 0.
18680 (let ((ind (if (bolp) 0
18681 (save-excursion
18682 (org-return-indent)
18683 (prog1 (org-get-indentation)
18684 (when (progn (skip-chars-forward " \t") (eolp))
18685 (delete-region beg (point)))))))
18686 (bol (progn (skip-chars-backward " \t") (bolp))))
18687 ;; Insert a newline before environment unless at column zero
18688 ;; to "escape" the current line. Insert a newline if
18689 ;; something is one the same line as \end{ENVIRONMENT}.
18690 (insert
18691 (concat (unless bol "\n") env
18692 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18693 (unless (zerop ind)
18694 (save-excursion
18695 (goto-char beg)
18696 (while (< (point) end)
18697 (unless (eolp) (indent-line-to ind))
18698 (forward-line))))
18699 (goto-char beg)
18700 (forward-line lines)
18701 (indent-line-to ind)))
18702 (set-marker beg nil)
18703 (set-marker end nil)))
18706 ;;;; LaTeX fragments
18708 (defun org-inside-LaTeX-fragment-p ()
18709 "Test if point is inside a LaTeX fragment.
18710 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18711 sequence appearing also before point.
18712 Even though the matchers for math are configurable, this function assumes
18713 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18714 delimiters are skipped when they have been removed by customization.
18715 The return value is nil, or a cons cell with the delimiter and the
18716 position of this delimiter.
18718 This function does a reasonably good job, but can locally be fooled by
18719 for example currency specifications. For example it will assume being in
18720 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18721 fragments that are properly closed, but during editing, we have to live
18722 with the uncertainty caused by missing closing delimiters. This function
18723 looks only before point, not after."
18724 (catch 'exit
18725 (let ((pos (point))
18726 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18727 (lim (save-excursion (org-backward-paragraph) (point)))
18728 dd-on str (start 0) m re)
18729 (goto-char pos)
18730 (when dodollar
18731 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18732 re (nth 1 (assoc "$" org-latex-regexps)))
18733 (while (string-match re str start)
18734 (cond
18735 ((= (match-end 0) (length str))
18736 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18737 ((= (match-end 0) (- (length str) 5))
18738 (throw 'exit nil))
18739 (t (setq start (match-end 0))))))
18740 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18741 (goto-char pos)
18742 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18743 (and (match-beginning 2) (throw 'exit nil))
18744 ;; count $$
18745 (while (re-search-backward "\\$\\$" lim t)
18746 (setq dd-on (not dd-on)))
18747 (goto-char pos)
18748 (when dd-on (cons "$$" m))))))
18750 (defun org-inside-latex-macro-p ()
18751 "Is point inside a LaTeX macro or its arguments?"
18752 (save-match-data
18753 (org-in-regexp
18754 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18756 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18757 "Build an overlay between BEG and END using IMAGE file.
18758 Argument IMAGETYPE is the extension of the displayed image,
18759 as a string. It defaults to \"png\"."
18760 (let ((ov (make-overlay beg end))
18761 (imagetype (or (intern imagetype) 'png)))
18762 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18763 (overlay-put ov 'evaporate t)
18764 (overlay-put ov
18765 'modification-hooks
18766 (list (lambda (o _flag _beg _end &optional _l)
18767 (delete-overlay o))))
18768 (overlay-put ov
18769 'display
18770 (list 'image :type imagetype :file image :ascent 'center))))
18772 (defun org--list-latex-overlays (&optional beg end)
18773 "List all Org LaTeX overlays in current buffer.
18774 Limit to overlays between BEG and END when those are provided."
18775 (cl-remove-if-not
18776 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18777 (overlays-in (or beg (point-min)) (or end (point-max)))))
18779 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18780 "Remove all overlays with LaTeX fragment images in current buffer.
18781 When optional arguments BEG and END are non-nil, remove all
18782 overlays between them instead. Return a non-nil value when some
18783 overlays were removed, nil otherwise."
18784 (let ((overlays (org--list-latex-overlays beg end)))
18785 (mapc #'delete-overlay overlays)
18786 overlays))
18788 (defun org-toggle-latex-fragment (&optional arg)
18789 "Preview the LaTeX fragment at point, or all locally or globally.
18791 If the cursor is on a LaTeX fragment, create the image and overlay
18792 it over the source code, if there is none. Remove it otherwise.
18793 If there is no fragment at point, display all fragments in the
18794 current section.
18796 With prefix ARG, preview or clear image for all fragments in the
18797 current subtree or in the whole buffer when used before the first
18798 headline. With a prefix ARG `\\[universal-argument] \
18799 \\[universal-argument]' preview or clear images
18800 for all fragments in the buffer."
18801 (interactive "P")
18802 (when (display-graphic-p)
18803 (catch 'exit
18804 (save-excursion
18805 (let (beg end msg)
18806 (cond
18807 ((or (equal arg '(16))
18808 (and (equal arg '(4))
18809 (org-with-limited-levels (org-before-first-heading-p))))
18810 (if (org-remove-latex-fragment-image-overlays)
18811 (progn (message "LaTeX fragments images removed from buffer")
18812 (throw 'exit nil))
18813 (setq msg "Creating images for buffer...")))
18814 ((equal arg '(4))
18815 (org-with-limited-levels (org-back-to-heading t))
18816 (setq beg (point))
18817 (setq end (progn (org-end-of-subtree t) (point)))
18818 (if (org-remove-latex-fragment-image-overlays beg end)
18819 (progn
18820 (message "LaTeX fragment images removed from subtree")
18821 (throw 'exit nil))
18822 (setq msg "Creating images for subtree...")))
18823 ((let ((datum (org-element-context)))
18824 (when (memq (org-element-type datum)
18825 '(latex-environment latex-fragment))
18826 (setq beg (org-element-property :begin datum))
18827 (setq end (org-element-property :end datum))
18828 (if (org-remove-latex-fragment-image-overlays beg end)
18829 (progn (message "LaTeX fragment image removed")
18830 (throw 'exit nil))
18831 (setq msg "Creating image...")))))
18833 (org-with-limited-levels
18834 (setq beg (if (org-at-heading-p) (line-beginning-position)
18835 (outline-previous-heading)
18836 (point)))
18837 (setq end (progn (outline-next-heading) (point)))
18838 (if (org-remove-latex-fragment-image-overlays beg end)
18839 (progn
18840 (message "LaTeX fragment images removed from section")
18841 (throw 'exit nil))
18842 (setq msg "Creating images for section...")))))
18843 (let ((file (buffer-file-name (buffer-base-buffer))))
18844 (org-format-latex
18845 (concat org-preview-latex-image-directory "org-ltximg")
18846 beg end
18847 ;; Emacs cannot overlay images from remote hosts. Create
18848 ;; it in `temporary-file-directory' instead.
18849 (if (or (not file) (file-remote-p file))
18850 temporary-file-directory
18851 default-directory)
18852 'overlays msg 'forbuffer org-preview-latex-default-process))
18853 (message (concat msg "done")))))))
18855 (defun org-format-latex
18856 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18857 "Replace LaTeX fragments with links to an image.
18859 The function takes care of creating the replacement image.
18861 Only consider fragments between BEG and END when those are
18862 provided.
18864 When optional argument OVERLAYS is non-nil, display the image on
18865 top of the fragment instead of replacing it.
18867 PROCESSING-TYPE is the conversion method to use, as a symbol.
18869 Some of the options can be changed using the variable
18870 `org-format-latex-options', which see."
18871 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18872 (unless (eq processing-type 'verbatim)
18873 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18874 (cnt 0)
18875 checkdir-flag)
18876 (goto-char (or beg (point-min)))
18877 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18878 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18879 (overlay-recenter (or end (point-max))))
18880 (while (re-search-forward math-regexp end t)
18881 (unless (and overlays
18882 (eq (get-char-property (point) 'org-overlay-type)
18883 'org-latex-overlay))
18884 (let* ((context (org-element-context))
18885 (type (org-element-type context)))
18886 (when (memq type '(latex-environment latex-fragment))
18887 (let ((block-type (eq type 'latex-environment))
18888 (value (org-element-property :value context))
18889 (beg (org-element-property :begin context))
18890 (end (save-excursion
18891 (goto-char (org-element-property :end context))
18892 (skip-chars-backward " \r\t\n")
18893 (point))))
18894 (cond
18895 ((eq processing-type 'mathjax)
18896 ;; Prepare for MathJax processing.
18897 (if (not (string-match "\\`\\$\\$?" value))
18898 (goto-char end)
18899 (delete-region beg end)
18900 (if (string= (match-string 0 value) "$$")
18901 (insert "\\[" (substring value 2 -2) "\\]")
18902 (insert "\\(" (substring value 1 -1) "\\)"))))
18903 ((assq processing-type org-preview-latex-process-alist)
18904 ;; Process to an image.
18905 (cl-incf cnt)
18906 (goto-char beg)
18907 (let* ((processing-info
18908 (cdr (assq processing-type org-preview-latex-process-alist)))
18909 (face (face-at-point))
18910 ;; Get the colors from the face at point.
18912 (let ((color (plist-get org-format-latex-options
18913 :foreground)))
18914 (if (and forbuffer (eq color 'auto))
18915 (face-attribute face :foreground nil 'default)
18916 color)))
18918 (let ((color (plist-get org-format-latex-options
18919 :background)))
18920 (if (and forbuffer (eq color 'auto))
18921 (face-attribute face :background nil 'default)
18922 color)))
18923 (hash (sha1 (prin1-to-string
18924 (list org-format-latex-header
18925 org-latex-default-packages-alist
18926 org-latex-packages-alist
18927 org-format-latex-options
18928 forbuffer value fg bg))))
18929 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18930 (absprefix (expand-file-name prefix dir))
18931 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18932 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18933 (sep (and block-type "\n\n"))
18934 (link (concat sep "[[file:" linkfile "]]" sep))
18935 (options
18936 (org-combine-plists
18937 org-format-latex-options
18938 `(:foreground ,fg :background ,bg))))
18939 (when msg (message msg cnt))
18940 (unless checkdir-flag ; Ensure the directory exists.
18941 (setq checkdir-flag t)
18942 (let ((todir (file-name-directory absprefix)))
18943 (unless (file-directory-p todir)
18944 (make-directory todir t))))
18945 (unless (file-exists-p movefile)
18946 (org-create-formula-image
18947 value movefile options forbuffer processing-type))
18948 (if overlays
18949 (progn
18950 (dolist (o (overlays-in beg end))
18951 (when (eq (overlay-get o 'org-overlay-type)
18952 'org-latex-overlay)
18953 (delete-overlay o)))
18954 (org--format-latex-make-overlay beg end movefile imagetype)
18955 (goto-char end))
18956 (delete-region beg end)
18957 (insert
18958 (org-add-props link
18959 (list 'org-latex-src
18960 (replace-regexp-in-string "\"" "" value)
18961 'org-latex-src-embed-type
18962 (if block-type 'paragraph 'character)))))))
18963 ((eq processing-type 'mathml)
18964 ;; Process to MathML.
18965 (unless (org-format-latex-mathml-available-p)
18966 (user-error "LaTeX to MathML converter not configured"))
18967 (cl-incf cnt)
18968 (when msg (message msg cnt))
18969 (goto-char beg)
18970 (delete-region beg end)
18971 (insert (org-format-latex-as-mathml
18972 value block-type prefix dir)))
18974 (error "Unknown conversion process %s for LaTeX fragments"
18975 processing-type)))))))))))
18977 (defun org-create-math-formula (latex-frag &optional mathml-file)
18978 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18979 Use `org-latex-to-mathml-convert-command'. If the conversion is
18980 sucessful, return the portion between \"<math...> </math>\"
18981 elements otherwise return nil. When MATHML-FILE is specified,
18982 write the results in to that file. When invoked as an
18983 interactive command, prompt for LATEX-FRAG, with initial value
18984 set to the current active region and echo the results for user
18985 inspection."
18986 (interactive (list (let ((frag (when (org-region-active-p)
18987 (buffer-substring-no-properties
18988 (region-beginning) (region-end)))))
18989 (read-string "LaTeX Fragment: " frag nil frag))))
18990 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18991 (let* ((tmp-in-file
18992 (let ((file (file-relative-name
18993 (make-temp-name (expand-file-name "ltxmathml-in")))))
18994 (write-region latex-frag nil file)
18995 file))
18996 (tmp-out-file (file-relative-name
18997 (make-temp-name (expand-file-name "ltxmathml-out"))))
18998 (cmd (format-spec
18999 org-latex-to-mathml-convert-command
19000 `((?j . ,(and org-latex-to-mathml-jar-file
19001 (shell-quote-argument
19002 (expand-file-name
19003 org-latex-to-mathml-jar-file))))
19004 (?I . ,(shell-quote-argument tmp-in-file))
19005 (?i . ,latex-frag)
19006 (?o . ,(shell-quote-argument tmp-out-file)))))
19007 mathml shell-command-output)
19008 (when (called-interactively-p 'any)
19009 (unless (org-format-latex-mathml-available-p)
19010 (user-error "LaTeX to MathML converter not configured")))
19011 (message "Running %s" cmd)
19012 (setq shell-command-output (shell-command-to-string cmd))
19013 (setq mathml
19014 (when (file-readable-p tmp-out-file)
19015 (with-current-buffer (find-file-noselect tmp-out-file t)
19016 (goto-char (point-min))
19017 (when (re-search-forward
19018 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19019 (regexp-quote
19020 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19021 nil t)
19022 (prog1 (match-string 0) (kill-buffer))))))
19023 (cond
19024 (mathml
19025 (setq mathml
19026 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19027 (when mathml-file
19028 (write-region mathml nil mathml-file))
19029 (when (called-interactively-p 'any)
19030 (message mathml)))
19031 ((message "LaTeX to MathML conversion failed")
19032 (message shell-command-output)))
19033 (delete-file tmp-in-file)
19034 (when (file-exists-p tmp-out-file)
19035 (delete-file tmp-out-file))
19036 mathml))
19038 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19039 prefix &optional dir)
19040 "Use `org-create-math-formula' but check local cache first."
19041 (let* ((absprefix (expand-file-name prefix dir))
19042 (print-length nil) (print-level nil)
19043 (formula-id (concat
19044 "formula-"
19045 (sha1
19046 (prin1-to-string
19047 (list latex-frag
19048 org-latex-to-mathml-convert-command)))))
19049 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19050 (formula-cache-dir (file-name-directory formula-cache)))
19052 (unless (file-directory-p formula-cache-dir)
19053 (make-directory formula-cache-dir t))
19055 (unless (file-exists-p formula-cache)
19056 (org-create-math-formula latex-frag formula-cache))
19058 (if (file-exists-p formula-cache)
19059 ;; Successful conversion. Return the link to MathML file.
19060 (org-add-props
19061 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19062 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19063 'org-latex-src-embed-type (if latex-frag-type
19064 'paragraph 'character)))
19065 ;; Failed conversion. Return the LaTeX fragment verbatim
19066 latex-frag)))
19068 (defun org--get-display-dpi ()
19069 "Get the DPI of the display.
19070 The function assumes that the display has the same pixel width in
19071 the horizontal and vertical directions."
19072 (if (display-graphic-p)
19073 (round (/ (display-pixel-height)
19074 (/ (display-mm-height) 25.4)))
19075 (error "Attempt to calculate the dpi of a non-graphic display")))
19077 (defun org-create-formula-image
19078 (string tofile options buffer &optional processing-type)
19079 "Create an image from LaTeX source using external processes.
19081 The LaTeX STRING is saved to a temporary LaTeX file, then
19082 converted to an image file by process PROCESSING-TYPE defined in
19083 `org-preview-latex-process-alist'. A nil value defaults to
19084 `org-preview-latex-default-process'.
19086 The generated image file is eventually moved to TOFILE.
19088 The OPTIONS argument controls the size, foreground color and
19089 background color of the generated image.
19091 When BUFFER non-nil, this function is used for LaTeX previewing.
19092 Otherwise, it is used to deal with LaTeX snippets showed in
19093 a HTML file."
19094 (let* ((processing-type (or processing-type
19095 org-preview-latex-default-process))
19096 (processing-info
19097 (cdr (assq processing-type org-preview-latex-process-alist)))
19098 (programs (plist-get processing-info :programs))
19099 (error-message (or (plist-get processing-info :message) ""))
19100 (use-xcolor (plist-get processing-info :use-xcolor))
19101 (image-input-type (plist-get processing-info :image-input-type))
19102 (image-output-type (plist-get processing-info :image-output-type))
19103 (post-clean (or (plist-get processing-info :post-clean)
19104 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19105 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19106 (latex-header
19107 (or (plist-get processing-info :latex-header)
19108 (org-latex-make-preamble
19109 (org-export-get-environment (org-export-get-backend 'latex))
19110 org-format-latex-header
19111 'snippet)))
19112 (latex-compiler (plist-get processing-info :latex-compiler))
19113 (image-converter (plist-get processing-info :image-converter))
19114 (tmpdir temporary-file-directory)
19115 (texfilebase (make-temp-name
19116 (expand-file-name "orgtex" tmpdir)))
19117 (texfile (concat texfilebase ".tex"))
19118 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19119 '(1.0 . 1.0)))
19120 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19121 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19122 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19123 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19124 "Black"))
19125 (bg (or (plist-get options (if buffer :background :html-background))
19126 "Transparent"))
19127 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19128 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19129 (dolist (program programs)
19130 (org-check-external-command program error-message))
19131 (if use-xcolor
19132 (progn (if (eq fg 'default)
19133 (setq fg (org-latex-color :foreground))
19134 (setq fg (org-latex-color-format fg)))
19135 (if (eq bg 'default)
19136 (setq bg (org-latex-color :background))
19137 (setq bg (org-latex-color-format
19138 (if (string= bg "Transparent") "white" bg))))
19139 (with-temp-file texfile
19140 (insert latex-header)
19141 (insert "\n\\begin{document}\n"
19142 "\\definecolor{fg}{rgb}{" fg "}\n"
19143 "\\definecolor{bg}{rgb}{" bg "}\n"
19144 "\n\\pagecolor{bg}\n"
19145 "\n{\\color{fg}\n"
19146 string
19147 "\n}\n"
19148 "\n\\end{document}\n")))
19149 (if (eq fg 'default)
19150 (setq fg (org-dvipng-color :foreground))
19151 (unless (string= fg "Transparent")
19152 (setq fg (org-dvipng-color-format fg))))
19153 (if (eq bg 'default)
19154 (setq bg (org-dvipng-color :background))
19155 (unless (string= bg "Transparent")
19156 (setq bg (org-dvipng-color-format bg))))
19157 (with-temp-file texfile
19158 (insert latex-header)
19159 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19161 (let* ((err-msg (format "Please adjust `%s' part of \
19162 `org-preview-latex-process-alist'."
19163 processing-type))
19164 (image-input-file
19165 (org-compile-file
19166 texfile latex-compiler image-input-type err-msg log-buf))
19167 (image-output-file
19168 (org-compile-file
19169 image-input-file image-converter image-output-type err-msg log-buf
19170 `((?F . ,(shell-quote-argument fg))
19171 (?B . ,(shell-quote-argument bg))
19172 (?D . ,(shell-quote-argument (format "%s" dpi)))
19173 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19174 (copy-file image-output-file tofile 'replace)
19175 (dolist (e post-clean)
19176 (when (file-exists-p (concat texfilebase e))
19177 (delete-file (concat texfilebase e))))
19178 image-output-file)))
19180 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19181 "Fill a LaTeX header template TPL.
19182 In the template, the following place holders will be recognized:
19184 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19185 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19186 [PACKAGES] \\usepackage statements for PKG
19187 [NO-PACKAGES] do not include PKG
19188 [EXTRA] the string EXTRA
19189 [NO-EXTRA] do not include EXTRA
19191 For backward compatibility, if both the positive and the negative place
19192 holder is missing, the positive one (without the \"NO-\") will be
19193 assumed to be present at the end of the template.
19194 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19195 EXTRA is a string.
19196 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19197 (let (rpl (end ""))
19198 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19199 (setq rpl (if (or (match-end 1) (not def-pkg))
19200 "" (org-latex-packages-to-string def-pkg snippets-p t))
19201 tpl (replace-match rpl t t tpl))
19202 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19204 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19205 (setq rpl (if (or (match-end 1) (not pkg))
19206 "" (org-latex-packages-to-string pkg snippets-p t))
19207 tpl (replace-match rpl t t tpl))
19208 (when pkg (setq end
19209 (concat end "\n"
19210 (org-latex-packages-to-string pkg snippets-p)))))
19212 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19213 (setq rpl (if (or (match-end 1) (not extra))
19214 "" (concat extra "\n"))
19215 tpl (replace-match rpl t t tpl))
19216 (when (and extra (string-match "\\S-" extra))
19217 (setq end (concat end "\n" extra))))
19219 (if (string-match "\\S-" end)
19220 (concat tpl "\n" end)
19221 tpl)))
19223 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19224 "Turn an alist of packages into a string with the \\usepackage macros."
19225 (setq pkg (mapconcat (lambda(p)
19226 (cond
19227 ((stringp p) p)
19228 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19229 (format "%% Package %s omitted" (cadr p)))
19230 ((equal "" (car p))
19231 (format "\\usepackage{%s}" (cadr p)))
19233 (format "\\usepackage[%s]{%s}"
19234 (car p) (cadr p)))))
19236 "\n"))
19237 (if newline (concat pkg "\n") pkg))
19239 (defun org-dvipng-color (attr)
19240 "Return a RGB color specification for dvipng."
19241 (org-dvipng-color-format (face-attribute 'default attr nil)))
19243 (defun org-dvipng-color-format (color-name)
19244 "Convert COLOR-NAME to a RGB color value for dvipng."
19245 (apply #'format "rgb %s %s %s"
19246 (mapcar 'org-normalize-color
19247 (color-values color-name))))
19249 (defun org-latex-color (attr)
19250 "Return a RGB color for the LaTeX color package."
19251 (org-latex-color-format (face-attribute 'default attr nil)))
19253 (defun org-latex-color-format (color-name)
19254 "Convert COLOR-NAME to a RGB color value."
19255 (apply #'format "%s,%s,%s"
19256 (mapcar 'org-normalize-color
19257 (color-values color-name))))
19259 (defun org-normalize-color (value)
19260 "Return string to be used as color value for an RGB component."
19261 (format "%g" (/ value 65535.0)))
19265 ;; Image display
19267 (defvar-local org-inline-image-overlays nil)
19269 (defun org-toggle-inline-images (&optional include-linked)
19270 "Toggle the display of inline images.
19271 INCLUDE-LINKED is passed to `org-display-inline-images'."
19272 (interactive "P")
19273 (if org-inline-image-overlays
19274 (progn
19275 (org-remove-inline-images)
19276 (when (called-interactively-p 'interactive)
19277 (message "Inline image display turned off")))
19278 (org-display-inline-images include-linked)
19279 (when (called-interactively-p 'interactive)
19280 (message (if org-inline-image-overlays
19281 (format "%d images displayed inline"
19282 (length org-inline-image-overlays))
19283 "No images to display inline")))))
19285 (defun org-redisplay-inline-images ()
19286 "Refresh the display of inline images."
19287 (interactive)
19288 (if (not org-inline-image-overlays)
19289 (org-toggle-inline-images)
19290 (org-toggle-inline-images)
19291 (org-toggle-inline-images)))
19293 (defun org-display-inline-images (&optional include-linked refresh beg end)
19294 "Display inline images.
19296 An inline image is a link which follows either of these
19297 conventions:
19299 1. Its path is a file with an extension matching return value
19300 from `image-file-name-regexp' and it has no contents.
19302 2. Its description consists in a single link of the previous
19303 type.
19305 When optional argument INCLUDE-LINKED is non-nil, also links with
19306 a text description part will be inlined. This can be nice for
19307 a quick look at those images, but it does not reflect what
19308 exported files will look like.
19310 When optional argument REFRESH is non-nil, refresh existing
19311 images between BEG and END. This will create new image displays
19312 only if necessary. BEG and END default to the buffer
19313 boundaries."
19314 (interactive "P")
19315 (when (display-graphic-p)
19316 (unless refresh
19317 (org-remove-inline-images)
19318 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19319 (org-with-wide-buffer
19320 (goto-char (or beg (point-min)))
19321 (let* ((case-fold-search t)
19322 (file-extension-re (image-file-name-regexp))
19323 (link-abbrevs (mapcar #'car
19324 (append org-link-abbrev-alist-local
19325 org-link-abbrev-alist)))
19326 ;; Check absolute, relative file names and explicit
19327 ;; "file:" links. Also check link abbreviations since
19328 ;; some might expand to "file" links.
19329 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19330 (and link-abbrevs
19331 (format "\\|\\(?:%s:\\)"
19332 (regexp-opt link-abbrevs))))))
19333 (while (re-search-forward file-types-re end t)
19334 (let ((link (save-match-data (org-element-context))))
19335 ;; Check if we're at an inline image, i.e., an image file
19336 ;; link without a description (unless INCLUDE-LINKED is
19337 ;; non-nil).
19338 (when (and (equal "file" (org-element-property :type link))
19339 (or include-linked
19340 (null (org-element-contents link)))
19341 (string-match-p file-extension-re
19342 (org-element-property :path link)))
19343 (let ((file (expand-file-name
19344 (org-link-unescape
19345 (org-element-property :path link)))))
19346 (when (file-exists-p file)
19347 (let ((width
19348 ;; Apply `org-image-actual-width' specifications.
19349 (cond
19350 ((not (image-type-available-p 'imagemagick)) nil)
19351 ((eq org-image-actual-width t) nil)
19352 ((listp org-image-actual-width)
19354 ;; First try to find a width among
19355 ;; attributes associated to the paragraph
19356 ;; containing link.
19357 (let ((paragraph
19358 (let ((e link))
19359 (while (and (setq e (org-element-property
19360 :parent e))
19361 (not (eq (org-element-type e)
19362 'paragraph))))
19363 e)))
19364 (when paragraph
19365 (save-excursion
19366 (goto-char (org-element-property :begin paragraph))
19367 (when
19368 (re-search-forward
19369 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19370 (org-element-property
19371 :post-affiliated paragraph)
19373 (string-to-number (match-string 1))))))
19374 ;; Otherwise, fall-back to provided number.
19375 (car org-image-actual-width)))
19376 ((numberp org-image-actual-width)
19377 org-image-actual-width)))
19378 (old (get-char-property-and-overlay
19379 (org-element-property :begin link)
19380 'org-image-overlay)))
19381 (if (and (car-safe old) refresh)
19382 (image-refresh (overlay-get (cdr old) 'display))
19383 (let ((image (create-image file
19384 (and width 'imagemagick)
19386 :width width)))
19387 (when image
19388 (let ((ov (make-overlay
19389 (org-element-property :begin link)
19390 (progn
19391 (goto-char
19392 (org-element-property :end link))
19393 (skip-chars-backward " \t")
19394 (point)))))
19395 (overlay-put ov 'display image)
19396 (overlay-put ov 'face 'default)
19397 (overlay-put ov 'org-image-overlay t)
19398 (overlay-put
19399 ov 'modification-hooks
19400 (list 'org-display-inline-remove-overlay))
19401 (push ov org-inline-image-overlays)))))))))))))))
19403 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19404 "Remove inline-display overlay if a corresponding region is modified."
19405 (let ((inhibit-modification-hooks t))
19406 (when (and ov after)
19407 (delete ov org-inline-image-overlays)
19408 (delete-overlay ov))))
19410 (defun org-remove-inline-images ()
19411 "Remove inline display of images."
19412 (interactive)
19413 (mapc #'delete-overlay org-inline-image-overlays)
19414 (setq org-inline-image-overlays nil))
19416 ;;;; Key bindings
19418 (defun org-remap (map &rest commands)
19419 "In MAP, remap the functions given in COMMANDS.
19420 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19421 (let (new old)
19422 (while commands
19423 (setq old (pop commands) new (pop commands))
19424 (org-defkey map (vector 'remap old) new))))
19426 ;; Outline functions from `outline-mode-prefix-map'
19427 ;; that can be remapped in Org:
19428 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19429 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19430 (define-key org-mode-map [remap outline-forward-same-level]
19431 'org-forward-heading-same-level)
19432 (define-key org-mode-map [remap outline-backward-same-level]
19433 'org-backward-heading-same-level)
19434 (define-key org-mode-map [remap outline-show-branches]
19435 'org-kill-note-or-show-branches)
19436 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19437 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19438 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19439 (define-key org-mode-map [remap outline-next-visible-heading]
19440 'org-next-visible-heading)
19441 (define-key org-mode-map [remap outline-previous-visible-heading]
19442 'org-previous-visible-heading)
19443 (define-key org-mode-map [remap show-children] 'org-show-children)
19445 ;; Outline functions from `outline-mode-prefix-map' that can not
19446 ;; be remapped in Org:
19448 ;; - the column "key binding" shows whether the Outline function is still
19449 ;; available in Org mode on the same key that it has been bound to in
19450 ;; Outline mode:
19451 ;; - "overridden": key used for a different functionality in Org mode
19452 ;; - else: key still bound to the same Outline function in Org mode
19454 ;; | Outline function | key binding | Org replacement |
19455 ;; |------------------------------------+-------------+--------------------------|
19456 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19457 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19458 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19459 ;; | `show-entry' | overridden | no replacement |
19460 ;; | `show-branches' | `C-c C-k' | still same function |
19461 ;; | `show-subtree' | overridden | visibility cycling |
19462 ;; | `show-all' | overridden | no replacement |
19463 ;; | `hide-subtree' | overridden | visibility cycling |
19464 ;; | `hide-body' | overridden | no replacement |
19465 ;; | `hide-entry' | overridden | visibility cycling |
19466 ;; | `hide-leaves' | overridden | no replacement |
19467 ;; | `hide-sublevels' | overridden | no replacement |
19468 ;; | `hide-other' | overridden | no replacement |
19470 ;; Make `C-c C-x' a prefix key
19471 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19473 ;; TAB key with modifiers
19474 (org-defkey org-mode-map "\C-i" 'org-cycle)
19475 (org-defkey org-mode-map [(tab)] 'org-cycle)
19476 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19477 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19479 ;; The following line is necessary under Suse GNU/Linux
19480 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19481 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19482 (define-key org-mode-map [backtab] 'org-shifttab)
19484 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19485 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19486 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19488 ;; Cursor keys with modifiers
19489 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19490 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19491 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19492 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19494 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19495 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19496 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19497 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19498 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19499 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19501 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19502 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19503 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19504 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19506 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19507 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19508 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19509 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19511 ;; Babel keys
19512 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19513 (dolist (pair org-babel-key-bindings)
19514 (define-key org-babel-map (car pair) (cdr pair)))
19516 ;;; Extra keys for tty access.
19517 ;; We only set them when really needed because otherwise the
19518 ;; menus don't show the simple keys
19520 (when (or org-use-extra-keys (not window-system))
19521 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19522 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19523 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19524 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19525 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19526 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19527 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19528 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19529 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19530 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19531 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19532 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19533 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19534 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19535 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19536 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19537 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19538 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19539 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19540 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19541 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19542 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19543 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19544 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19545 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19546 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19547 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19548 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19550 ;; All the other keys
19551 (org-remap org-mode-map
19552 'self-insert-command 'org-self-insert-command
19553 'delete-char 'org-delete-char
19554 'delete-backward-char 'org-delete-backward-char)
19555 (org-defkey org-mode-map "|" 'org-force-self-insert)
19557 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19558 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19559 (if (boundp 'narrow-map)
19560 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19561 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19562 (if (boundp 'narrow-map)
19563 (org-defkey narrow-map "b" 'org-narrow-to-block)
19564 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19565 (if (boundp 'narrow-map)
19566 (org-defkey narrow-map "e" 'org-narrow-to-element)
19567 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19568 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19569 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19570 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19571 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19572 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19573 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19574 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19575 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19576 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19577 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19578 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19579 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19580 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19581 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19582 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19583 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19584 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19585 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19586 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19587 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19588 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19589 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19590 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19591 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19592 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19593 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19594 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19595 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19596 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19597 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19598 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19599 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19600 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19601 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19602 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19603 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19604 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19605 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19606 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19607 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19608 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19609 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19610 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19611 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19612 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19613 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19614 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19615 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19616 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19617 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19618 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19619 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19620 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19621 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19622 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19623 (org-defkey org-mode-map "\C-c^" 'org-sort)
19624 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19625 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19626 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19627 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19628 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19629 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19630 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19631 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19632 (org-defkey org-mode-map "\C-m" 'org-return)
19633 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19634 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19635 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19636 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19637 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19638 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19639 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19640 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19641 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19642 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19643 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19644 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19645 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19646 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19647 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19648 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19649 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19650 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19651 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19652 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19653 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19654 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19655 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19656 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19657 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19659 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19660 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19661 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19663 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19664 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19665 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19666 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19667 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19668 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19669 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19670 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19671 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19672 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19673 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19674 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19675 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19676 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19677 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19678 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19679 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19680 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19681 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19682 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19683 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19684 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19686 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19687 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19688 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19689 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19690 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19692 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19694 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19696 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19697 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19699 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19702 (defconst org-speed-commands-default
19704 ("Outline Navigation")
19705 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19706 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19707 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19708 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19709 ("F" . org-next-block)
19710 ("B" . org-previous-block)
19711 ("u" . (org-speed-move-safe 'outline-up-heading))
19712 ("j" . org-goto)
19713 ("g" . (org-refile t))
19714 ("Outline Visibility")
19715 ("c" . org-cycle)
19716 ("C" . org-shifttab)
19717 (" " . org-display-outline-path)
19718 ("s" . org-narrow-to-subtree)
19719 ("=" . org-columns)
19720 ("Outline Structure Editing")
19721 ("U" . org-metaup)
19722 ("D" . org-metadown)
19723 ("r" . org-metaright)
19724 ("l" . org-metaleft)
19725 ("R" . org-shiftmetaright)
19726 ("L" . org-shiftmetaleft)
19727 ("i" . (progn (forward-char 1) (call-interactively
19728 'org-insert-heading-respect-content)))
19729 ("^" . org-sort)
19730 ("w" . org-refile)
19731 ("a" . org-archive-subtree-default-with-confirmation)
19732 ("@" . org-mark-subtree)
19733 ("#" . org-toggle-comment)
19734 ("Clock Commands")
19735 ("I" . org-clock-in)
19736 ("O" . org-clock-out)
19737 ("Meta Data Editing")
19738 ("t" . org-todo)
19739 ("," . (org-priority))
19740 ("0" . (org-priority ?\ ))
19741 ("1" . (org-priority ?A))
19742 ("2" . (org-priority ?B))
19743 ("3" . (org-priority ?C))
19744 (":" . org-set-tags-command)
19745 ("e" . org-set-effort)
19746 ("E" . org-inc-effort)
19747 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19748 (org-entry-put (point) "APPT_WARNTIME" m)))
19749 ("Agenda Views etc")
19750 ("v" . org-agenda)
19751 ("/" . org-sparse-tree)
19752 ("Misc")
19753 ("o" . org-open-at-point)
19754 ("?" . org-speed-command-help)
19755 ("<" . (org-agenda-set-restriction-lock 'subtree))
19756 (">" . (org-agenda-remove-restriction-lock))
19758 "The default speed commands.")
19760 (defun org-print-speed-command (e)
19761 (if (> (length (car e)) 1)
19762 (progn
19763 (princ "\n")
19764 (princ (car e))
19765 (princ "\n")
19766 (princ (make-string (length (car e)) ?-))
19767 (princ "\n"))
19768 (princ (car e))
19769 (princ " ")
19770 (if (symbolp (cdr e))
19771 (princ (symbol-name (cdr e)))
19772 (prin1 (cdr e)))
19773 (princ "\n")))
19775 (defun org-speed-command-help ()
19776 "Show the available speed commands."
19777 (interactive)
19778 (if (not org-use-speed-commands)
19779 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19780 (with-output-to-temp-buffer "*Help*"
19781 (princ "User-defined Speed commands\n===========================\n")
19782 (mapc #'org-print-speed-command org-speed-commands-user)
19783 (princ "\n")
19784 (princ "Built-in Speed commands\n=======================\n")
19785 (mapc #'org-print-speed-command org-speed-commands-default))
19786 (with-current-buffer "*Help*"
19787 (setq truncate-lines t))))
19789 (defun org-speed-move-safe (cmd)
19790 "Execute CMD, but make sure that the cursor always ends up in a headline.
19791 If not, return to the original position and throw an error."
19792 (interactive)
19793 (let ((pos (point)))
19794 (call-interactively cmd)
19795 (unless (and (bolp) (org-at-heading-p))
19796 (goto-char pos)
19797 (error "Boundary reached while executing %s" cmd))))
19799 (defvar org-self-insert-command-undo-counter 0)
19801 (defvar org-table-auto-blank-field) ; defined in org-table.el
19802 (defvar org-speed-command nil)
19804 (defun org-speed-command-activate (keys)
19805 "Hook for activating single-letter speed commands.
19806 `org-speed-commands-default' specifies a minimal command set.
19807 Use `org-speed-commands-user' for further customization."
19808 (when (or (and (bolp) (looking-at org-outline-regexp))
19809 (and (functionp org-use-speed-commands)
19810 (funcall org-use-speed-commands)))
19811 (cdr (assoc keys (append org-speed-commands-user
19812 org-speed-commands-default)))))
19814 (defun org-babel-speed-command-activate (keys)
19815 "Hook for activating single-letter code block commands."
19816 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19817 (cdr (assoc keys org-babel-key-bindings))))
19819 (defcustom org-speed-command-hook
19820 '(org-speed-command-activate org-babel-speed-command-activate)
19821 "Hook for activating speed commands at strategic locations.
19822 Hook functions are called in sequence until a valid handler is
19823 found.
19825 Each hook takes a single argument, a user-pressed command key
19826 which is also a `self-insert-command' from the global map.
19828 Within the hook, examine the cursor position and the command key
19829 and return nil or a valid handler as appropriate. Handler could
19830 be one of an interactive command, a function, or a form.
19832 Set `org-use-speed-commands' to non-nil value to enable this
19833 hook. The default setting is `org-speed-command-activate'."
19834 :group 'org-structure
19835 :version "24.1"
19836 :type 'hook)
19838 (defun org-self-insert-command (N)
19839 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19840 If the cursor is in a table looking at whitespace, the whitespace is
19841 overwritten, and the table is not marked as requiring realignment."
19842 (interactive "p")
19843 (org-check-before-invisible-edit 'insert)
19844 (cond
19845 ((and org-use-speed-commands
19846 (let ((kv (this-command-keys-vector)))
19847 (setq org-speed-command
19848 (run-hook-with-args-until-success
19849 'org-speed-command-hook
19850 (make-string 1 (aref kv (1- (length kv))))))))
19851 (cond
19852 ((commandp org-speed-command)
19853 (setq this-command org-speed-command)
19854 (call-interactively org-speed-command))
19855 ((functionp org-speed-command)
19856 (funcall org-speed-command))
19857 ((and org-speed-command (listp org-speed-command))
19858 (eval org-speed-command))
19859 (t (let (org-use-speed-commands)
19860 (call-interactively 'org-self-insert-command)))))
19861 ((and
19862 (org-at-table-p)
19863 (eq N 1)
19864 (not (org-region-active-p))
19865 (progn
19866 ;; Check if we blank the field, and if that triggers align.
19867 (and (featurep 'org-table) org-table-auto-blank-field
19868 (memq last-command
19869 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19870 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19871 ;; Got extra space, this field does not determine
19872 ;; column width.
19873 (let (org-table-may-need-update) (org-table-blank-field))
19874 ;; No extra space, this field may determine column
19875 ;; width.
19876 (org-table-blank-field)))
19878 (looking-at "[^|\n]* \\( \\)|"))
19879 ;; There is room for insertion without re-aligning the table.
19880 (delete-region (match-beginning 1) (match-end 1))
19881 (self-insert-command N))
19883 (setq org-table-may-need-update t)
19884 (self-insert-command N)
19885 (org-fix-tags-on-the-fly)
19886 (when org-self-insert-cluster-for-undo
19887 (if (not (eq last-command 'org-self-insert-command))
19888 (setq org-self-insert-command-undo-counter 1)
19889 (if (>= org-self-insert-command-undo-counter 20)
19890 (setq org-self-insert-command-undo-counter 1)
19891 (and (> org-self-insert-command-undo-counter 0)
19892 buffer-undo-list (listp buffer-undo-list)
19893 (not (cadr buffer-undo-list)) ; remove nil entry
19894 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19895 (setq org-self-insert-command-undo-counter
19896 (1+ org-self-insert-command-undo-counter))))))))
19898 (defun org-check-before-invisible-edit (kind)
19899 "Check is editing if kind KIND would be dangerous with invisible text around.
19900 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19901 ;; First, try to get out of here as quickly as possible, to reduce overhead
19902 (when (and org-catch-invisible-edits
19903 (or (not (boundp 'visible-mode)) (not visible-mode))
19904 (or (get-char-property (point) 'invisible)
19905 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19906 ;; OK, we need to take a closer look. Do not consider
19907 ;; invisibility obtained through text properties (e.g., link
19908 ;; fontification), as it cannot be toggled.
19909 (let* ((invisible-at-point
19910 (pcase (get-char-property-and-overlay (point) 'invisible)
19911 (`(,_ . ,(and (pred overlayp) o)) o)))
19912 ;; Assume that point cannot land in the middle of an
19913 ;; overlay, or between two overlays.
19914 (invisible-before-point
19915 (and (not invisible-at-point)
19916 (not (bobp))
19917 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19918 (`(,_ . ,(and (pred overlayp) o)) o))))
19919 (border-and-ok-direction
19921 ;; Check if we are acting predictably before invisible
19922 ;; text.
19923 (and invisible-at-point
19924 (memq kind '(insert delete-backward)))
19925 ;; Check if we are acting predictably after invisible text
19926 ;; This works not well, and I have turned it off. It seems
19927 ;; better to always show and stop after invisible text.
19928 ;; (and (not invisible-at-point) invisible-before-point
19929 ;; (memq kind '(insert delete)))
19931 (when (or invisible-at-point invisible-before-point)
19932 (when (eq org-catch-invisible-edits 'error)
19933 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19934 (if (and org-custom-properties-overlays
19935 (y-or-n-p "Display invisible properties in this buffer? "))
19936 (org-toggle-custom-properties-visibility)
19937 ;; Make the area visible
19938 (save-excursion
19939 (when invisible-before-point
19940 (goto-char
19941 (previous-single-char-property-change (point) 'invisible)))
19942 ;; Remove whatever overlay is currently making yet-to-be
19943 ;; edited text invisible. Also remove nested invisibility
19944 ;; related overlays.
19945 (delete-overlay (or invisible-at-point invisible-before-point))
19946 (let ((origin (if invisible-at-point (point) (1- (point)))))
19947 (while (pcase (get-char-property-and-overlay origin 'invisible)
19948 (`(,_ . ,(and (pred overlayp) o))
19949 (delete-overlay o)
19950 t)))))
19951 (cond
19952 ((eq org-catch-invisible-edits 'show)
19953 ;; That's it, we do the edit after showing
19954 (message
19955 "Unfolding invisible region around point before editing")
19956 (sit-for 1))
19957 ((and (eq org-catch-invisible-edits 'smart)
19958 border-and-ok-direction)
19959 (message "Unfolding invisible region around point before editing"))
19961 ;; Don't do the edit, make the user repeat it in full visibility
19962 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19964 (defun org-fix-tags-on-the-fly ()
19965 "Align tags in headline at point.
19966 Unlike to `org-set-tags', it ignores region and sorting."
19967 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19968 (org-at-heading-p))
19969 (let ((org-ignore-region t)
19970 (org-tags-sort-function nil))
19971 (org-set-tags nil t))))
19973 (defun org-delete-backward-char (N)
19974 "Like `delete-backward-char', insert whitespace at field end in tables.
19975 When deleting backwards, in tables this function will insert whitespace in
19976 front of the next \"|\" separator, to keep the table aligned. The table will
19977 still be marked for re-alignment if the field did fill the entire column,
19978 because, in this case the deletion might narrow the column."
19979 (interactive "p")
19980 (save-match-data
19981 (org-check-before-invisible-edit 'delete-backward)
19982 (if (and (org-at-table-p)
19983 (eq N 1)
19984 (not (org-region-active-p))
19985 (string-match "|" (buffer-substring (point-at-bol) (point)))
19986 (looking-at ".*?|"))
19987 (let ((pos (point))
19988 (noalign (looking-at "[^|\n\r]* |"))
19989 (c org-table-may-need-update))
19990 (backward-delete-char N)
19991 (unless overwrite-mode
19992 (skip-chars-forward "^|")
19993 (insert " ")
19994 (goto-char (1- pos)))
19995 ;; noalign: if there were two spaces at the end, this field
19996 ;; does not determine the width of the column.
19997 (when noalign (setq org-table-may-need-update c)))
19998 (backward-delete-char N)
19999 (org-fix-tags-on-the-fly))))
20001 (defun org-delete-char (N)
20002 "Like `delete-char', but insert whitespace at field end in tables.
20003 When deleting characters, in tables this function will insert whitespace in
20004 front of the next \"|\" separator, to keep the table aligned. The table will
20005 still be marked for re-alignment if the field did fill the entire column,
20006 because, in this case the deletion might narrow the column."
20007 (interactive "p")
20008 (save-match-data
20009 (org-check-before-invisible-edit 'delete)
20010 (if (and (org-at-table-p)
20011 (not (bolp))
20012 (not (= (char-after) ?|))
20013 (eq N 1))
20014 (if (looking-at ".*?|")
20015 (let ((pos (point))
20016 (noalign (looking-at "[^|\n\r]* |"))
20017 (c org-table-may-need-update))
20018 (replace-match
20019 (concat (substring (match-string 0) 1 -1) " |") nil t)
20020 (goto-char pos)
20021 ;; noalign: if there were two spaces at the end, this field
20022 ;; does not determine the width of the column.
20023 (when noalign (setq org-table-may-need-update c)))
20024 (delete-char N))
20025 (delete-char N)
20026 (org-fix-tags-on-the-fly))))
20028 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20029 (put 'org-self-insert-command 'delete-selection
20030 (lambda ()
20031 (not (run-hook-with-args-until-success
20032 'self-insert-uses-region-functions))))
20033 (put 'orgtbl-self-insert-command 'delete-selection
20034 (lambda ()
20035 (not (run-hook-with-args-until-success
20036 'self-insert-uses-region-functions))))
20037 (put 'org-delete-char 'delete-selection 'supersede)
20038 (put 'org-delete-backward-char 'delete-selection 'supersede)
20039 (put 'org-yank 'delete-selection 'yank)
20041 ;; Make `flyspell-mode' delay after some commands
20042 (put 'org-self-insert-command 'flyspell-delayed t)
20043 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20044 (put 'org-delete-char 'flyspell-delayed t)
20045 (put 'org-delete-backward-char 'flyspell-delayed t)
20047 ;; Make pabbrev-mode expand after Org mode commands
20048 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20049 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20051 (defun org-transpose-words ()
20052 "Transpose words for Org.
20053 This uses the `org-mode-transpose-word-syntax-table' syntax
20054 table, which interprets characters in `org-emphasis-alist' as
20055 word constituents."
20056 (interactive)
20057 (with-syntax-table org-mode-transpose-word-syntax-table
20058 (call-interactively 'transpose-words)))
20059 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20061 (defvar org-ctrl-c-ctrl-c-hook nil
20062 "Hook for functions attaching themselves to `C-c C-c'.
20064 This can be used to add additional functionality to the C-c C-c
20065 key which executes context-dependent commands. This hook is run
20066 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20067 run after the last test.
20069 Each function will be called with no arguments. The function
20070 must check if the context is appropriate for it to act. If yes,
20071 it should do its thing and then return a non-nil value. If the
20072 context is wrong, just do nothing and return nil.")
20074 (defvar org-ctrl-c-ctrl-c-final-hook nil
20075 "Hook for functions attaching themselves to `C-c C-c'.
20077 This can be used to add additional functionality to the C-c C-c
20078 key which executes context-dependent commands. This hook is run
20079 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20080 before the first test.
20082 Each function will be called with no arguments. The function
20083 must check if the context is appropriate for it to act. If yes,
20084 it should do its thing and then return a non-nil value. If the
20085 context is wrong, just do nothing and return nil.")
20087 (defvar org-tab-first-hook nil
20088 "Hook for functions to attach themselves to TAB.
20089 See `org-ctrl-c-ctrl-c-hook' for more information.
20090 This hook runs as the first action when TAB is pressed, even before
20091 `org-cycle' messes around with the `outline-regexp' to cater for
20092 inline tasks and plain list item folding.
20093 If any function in this hook returns t, any other actions that
20094 would have been caused by TAB (such as table field motion or visibility
20095 cycling) will not occur.")
20097 (defvar org-tab-after-check-for-table-hook nil
20098 "Hook for functions to attach themselves to TAB.
20099 See `org-ctrl-c-ctrl-c-hook' for more information.
20100 This hook runs after it has been established that the cursor is not in a
20101 table, but before checking if the cursor is in a headline or if global cycling
20102 should be done.
20103 If any function in this hook returns t, not other actions like visibility
20104 cycling will be done.")
20106 (defvar org-tab-after-check-for-cycling-hook nil
20107 "Hook for functions to attach themselves to TAB.
20108 See `org-ctrl-c-ctrl-c-hook' for more information.
20109 This hook runs after it has been established that not table field motion and
20110 not visibility should be done because of current context. This is probably
20111 the place where a package like yasnippets can hook in.")
20113 (defvar org-tab-before-tab-emulation-hook nil
20114 "Hook for functions to attach themselves to TAB.
20115 See `org-ctrl-c-ctrl-c-hook' for more information.
20116 This hook runs after every other options for TAB have been exhausted, but
20117 before indentation and \t insertion takes place.")
20119 (defvar org-metaleft-hook nil
20120 "Hook for functions attaching themselves to `M-left'.
20121 See `org-ctrl-c-ctrl-c-hook' for more information.")
20122 (defvar org-metaright-hook nil
20123 "Hook for functions attaching themselves to `M-right'.
20124 See `org-ctrl-c-ctrl-c-hook' for more information.")
20125 (defvar org-metaup-hook nil
20126 "Hook for functions attaching themselves to `M-up'.
20127 See `org-ctrl-c-ctrl-c-hook' for more information.")
20128 (defvar org-metadown-hook nil
20129 "Hook for functions attaching themselves to `M-down'.
20130 See `org-ctrl-c-ctrl-c-hook' for more information.")
20131 (defvar org-shiftmetaleft-hook nil
20132 "Hook for functions attaching themselves to `M-S-left'.
20133 See `org-ctrl-c-ctrl-c-hook' for more information.")
20134 (defvar org-shiftmetaright-hook nil
20135 "Hook for functions attaching themselves to `M-S-right'.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-shiftmetaup-hook nil
20138 "Hook for functions attaching themselves to `M-S-up'.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.")
20140 (defvar org-shiftmetadown-hook nil
20141 "Hook for functions attaching themselves to `M-S-down'.
20142 See `org-ctrl-c-ctrl-c-hook' for more information.")
20143 (defvar org-metareturn-hook nil
20144 "Hook for functions attaching themselves to `M-RET'.
20145 See `org-ctrl-c-ctrl-c-hook' for more information.")
20146 (defvar org-shiftup-hook nil
20147 "Hook for functions attaching themselves to `S-up'.
20148 See `org-ctrl-c-ctrl-c-hook' for more information.")
20149 (defvar org-shiftup-final-hook nil
20150 "Hook for functions attaching themselves to `S-up'.
20151 This one runs after all other options except shift-select have been excluded.
20152 See `org-ctrl-c-ctrl-c-hook' for more information.")
20153 (defvar org-shiftdown-hook nil
20154 "Hook for functions attaching themselves to `S-down'.
20155 See `org-ctrl-c-ctrl-c-hook' for more information.")
20156 (defvar org-shiftdown-final-hook nil
20157 "Hook for functions attaching themselves to `S-down'.
20158 This one runs after all other options except shift-select have been excluded.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.")
20160 (defvar org-shiftleft-hook nil
20161 "Hook for functions attaching themselves to `S-left'.
20162 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defvar org-shiftleft-final-hook nil
20164 "Hook for functions attaching themselves to `S-left'.
20165 This one runs after all other options except shift-select have been excluded.
20166 See `org-ctrl-c-ctrl-c-hook' for more information.")
20167 (defvar org-shiftright-hook nil
20168 "Hook for functions attaching themselves to `S-right'.
20169 See `org-ctrl-c-ctrl-c-hook' for more information.")
20170 (defvar org-shiftright-final-hook nil
20171 "Hook for functions attaching themselves to `S-right'.
20172 This one runs after all other options except shift-select have been excluded.
20173 See `org-ctrl-c-ctrl-c-hook' for more information.")
20175 (defun org-modifier-cursor-error ()
20176 "Throw an error, a modified cursor command was applied in wrong context."
20177 (user-error "This command is active in special context like tables, headlines or items"))
20179 (defun org-shiftselect-error ()
20180 "Throw an error because Shift-Cursor command was applied in wrong context."
20181 (if (and (boundp 'shift-select-mode) shift-select-mode)
20182 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20183 (user-error "This command works only in special context like headlines or timestamps")))
20185 (defun org-call-for-shift-select (cmd)
20186 (let ((this-command-keys-shift-translated t))
20187 (call-interactively cmd)))
20189 (defun org-shifttab (&optional arg)
20190 "Global visibility cycling or move to previous table field.
20191 Call `org-table-previous-field' within a table.
20192 When ARG is nil, cycle globally through visibility states.
20193 When ARG is a numeric prefix, show contents of this level."
20194 (interactive "P")
20195 (cond
20196 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20197 ((integerp arg)
20198 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20199 (message "Content view to level: %d" arg)
20200 (org-content (prefix-numeric-value arg2))
20201 (org-cycle-show-empty-lines t)
20202 (setq org-cycle-global-status 'overview)))
20203 (t (call-interactively 'org-global-cycle))))
20205 (defun org-shiftmetaleft ()
20206 "Promote subtree or delete table column.
20207 Calls `org-promote-subtree', `org-outdent-item-tree', or
20208 `org-table-delete-column', depending on context. See the
20209 individual commands for more information."
20210 (interactive)
20211 (cond
20212 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20213 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20214 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20215 ((if (not (org-region-active-p)) (org-at-item-p)
20216 (save-excursion (goto-char (region-beginning))
20217 (org-at-item-p)))
20218 (call-interactively 'org-outdent-item-tree))
20219 (t (org-modifier-cursor-error))))
20221 (defun org-shiftmetaright ()
20222 "Demote subtree or insert table column.
20223 Calls `org-demote-subtree', `org-indent-item-tree', or
20224 `org-table-insert-column', depending on context. See the
20225 individual commands for more information."
20226 (interactive)
20227 (cond
20228 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20229 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20230 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20231 ((if (not (org-region-active-p)) (org-at-item-p)
20232 (save-excursion (goto-char (region-beginning))
20233 (org-at-item-p)))
20234 (call-interactively 'org-indent-item-tree))
20235 (t (org-modifier-cursor-error))))
20237 (defun org-shiftmetaup (&optional _arg)
20238 "Drag the line at point up.
20239 In a table, kill the current row.
20240 On a clock timestamp, update the value of the timestamp like `S-<up>'
20241 but also adjust the previous clocked item in the clock history.
20242 Everywhere else, drag the line at point up."
20243 (interactive "P")
20244 (cond
20245 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20246 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20247 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20248 (call-interactively 'org-timestamp-up)))
20249 (t (call-interactively 'org-drag-line-backward))))
20251 (defun org-shiftmetadown (&optional _arg)
20252 "Drag the line at point down.
20253 In a table, insert an empty row at the current line.
20254 On a clock timestamp, update the value of the timestamp like `S-<down>'
20255 but also adjust the previous clocked item in the clock history.
20256 Everywhere else, drag the line at point down."
20257 (interactive "P")
20258 (cond
20259 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20260 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20261 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20262 (call-interactively 'org-timestamp-down)))
20263 (t (call-interactively 'org-drag-line-forward))))
20265 (defsubst org-hidden-tree-error ()
20266 (user-error
20267 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20269 (defun org-metaleft (&optional _arg)
20270 "Promote heading, list item at point or move table column left.
20272 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20273 depending on context. With no specific context, calls the Emacs
20274 default `backward-word'. See the individual commands for more
20275 information.
20277 This function runs the hook `org-metaleft-hook' as a first step,
20278 and returns at first non-nil value."
20279 (interactive "P")
20280 (cond
20281 ((run-hook-with-args-until-success 'org-metaleft-hook))
20282 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20283 ((org-with-limited-levels
20284 (or (org-at-heading-p)
20285 (and (org-region-active-p)
20286 (save-excursion
20287 (goto-char (region-beginning))
20288 (org-at-heading-p)))))
20289 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20290 (call-interactively 'org-do-promote))
20291 ;; At an inline task.
20292 ((org-at-heading-p)
20293 (call-interactively 'org-inlinetask-promote))
20294 ((or (org-at-item-p)
20295 (and (org-region-active-p)
20296 (save-excursion
20297 (goto-char (region-beginning))
20298 (org-at-item-p))))
20299 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20300 (call-interactively 'org-outdent-item))
20301 (t (call-interactively 'backward-word))))
20303 (defun org-metaright (&optional _arg)
20304 "Demote heading, list item at point or move table column right.
20306 In front of a drawer or a block keyword, indent it correctly.
20308 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20309 `org-indent-drawer' or `org-indent-block' depending on context.
20310 With no specific context, calls the Emacs default `forward-word'.
20311 See the individual commands for more information.
20313 This function runs the hook `org-metaright-hook' as a first step,
20314 and returns at first non-nil value."
20315 (interactive "P")
20316 (cond
20317 ((run-hook-with-args-until-success 'org-metaright-hook))
20318 ((org-at-table-p) (call-interactively 'org-table-move-column))
20319 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20320 ((org-at-block-p) (call-interactively 'org-indent-block))
20321 ((org-with-limited-levels
20322 (or (org-at-heading-p)
20323 (and (org-region-active-p)
20324 (save-excursion
20325 (goto-char (region-beginning))
20326 (org-at-heading-p)))))
20327 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20328 (call-interactively 'org-do-demote))
20329 ;; At an inline task.
20330 ((org-at-heading-p)
20331 (call-interactively 'org-inlinetask-demote))
20332 ((or (org-at-item-p)
20333 (and (org-region-active-p)
20334 (save-excursion
20335 (goto-char (region-beginning))
20336 (org-at-item-p))))
20337 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20338 (call-interactively 'org-indent-item))
20339 (t (call-interactively 'forward-word))))
20341 (defun org-check-for-hidden (what)
20342 "Check if there are hidden headlines/items in the current visual line.
20343 WHAT can be either `headlines' or `items'. If the current line is
20344 an outline or item heading and it has a folded subtree below it,
20345 this function returns t, nil otherwise."
20346 (let ((re (cond
20347 ((eq what 'headlines) org-outline-regexp-bol)
20348 ((eq what 'items) (org-item-beginning-re))
20349 (t (error "This should not happen"))))
20350 beg end)
20351 (save-excursion
20352 (catch 'exit
20353 (unless (org-region-active-p)
20354 (setq beg (point-at-bol))
20355 (beginning-of-line 2)
20356 (while (and (not (eobp)) ;; this is like `next-line'
20357 (get-char-property (1- (point)) 'invisible))
20358 (beginning-of-line 2))
20359 (setq end (point))
20360 (goto-char beg)
20361 (goto-char (point-at-eol))
20362 (setq end (max end (point)))
20363 (while (re-search-forward re end t)
20364 (when (get-char-property (match-beginning 0) 'invisible)
20365 (throw 'exit t))))
20366 nil))))
20368 (defun org-metaup (&optional _arg)
20369 "Move subtree up or move table row up.
20370 Calls `org-move-subtree-up' or `org-table-move-row' or
20371 `org-move-item-up', depending on context. See the individual commands
20372 for more information."
20373 (interactive "P")
20374 (cond
20375 ((run-hook-with-args-until-success 'org-metaup-hook))
20376 ((org-region-active-p)
20377 (let* ((a (min (region-beginning) (region-end)))
20378 (b (1- (max (region-beginning) (region-end))))
20379 (c (save-excursion (goto-char a)
20380 (move-beginning-of-line 0)))
20381 (d (save-excursion (goto-char a)
20382 (move-end-of-line 0) (point))))
20383 (transpose-regions a b c d)
20384 (goto-char c)))
20385 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20386 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20387 ((org-at-item-p) (call-interactively 'org-move-item-up))
20388 (t (org-drag-element-backward))))
20390 (defun org-metadown (&optional _arg)
20391 "Move subtree down or move table row down.
20392 Calls `org-move-subtree-down' or `org-table-move-row' or
20393 `org-move-item-down', depending on context. See the individual
20394 commands for more information."
20395 (interactive "P")
20396 (cond
20397 ((run-hook-with-args-until-success 'org-metadown-hook))
20398 ((org-region-active-p)
20399 (let* ((a (min (region-beginning) (region-end)))
20400 (b (max (region-beginning) (region-end)))
20401 (c (save-excursion (goto-char b)
20402 (move-beginning-of-line 1)))
20403 (d (save-excursion (goto-char b)
20404 (move-end-of-line 1) (1+ (point)))))
20405 (transpose-regions a b c d)
20406 (goto-char d)))
20407 ((org-at-table-p) (call-interactively 'org-table-move-row))
20408 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20409 ((org-at-item-p) (call-interactively 'org-move-item-down))
20410 (t (org-drag-element-forward))))
20412 (defun org-shiftup (&optional arg)
20413 "Increase item in timestamp or increase priority of current headline.
20414 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20415 depending on context. See the individual commands for more information."
20416 (interactive "P")
20417 (cond
20418 ((run-hook-with-args-until-success 'org-shiftup-hook))
20419 ((and org-support-shift-select (org-region-active-p))
20420 (org-call-for-shift-select 'previous-line))
20421 ((org-at-timestamp-p 'lax)
20422 (call-interactively (if org-edit-timestamp-down-means-later
20423 'org-timestamp-down 'org-timestamp-up)))
20424 ((and (not (eq org-support-shift-select 'always))
20425 org-enable-priority-commands
20426 (org-at-heading-p))
20427 (call-interactively 'org-priority-up))
20428 ((and (not org-support-shift-select) (org-at-item-p))
20429 (call-interactively 'org-previous-item))
20430 ((org-clocktable-try-shift 'up arg))
20431 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20432 (org-support-shift-select
20433 (org-call-for-shift-select 'previous-line))
20434 (t (org-shiftselect-error))))
20436 (defun org-shiftdown (&optional arg)
20437 "Decrease item in timestamp or decrease priority of current headline.
20438 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20439 depending on context. See the individual commands for more information."
20440 (interactive "P")
20441 (cond
20442 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20443 ((and org-support-shift-select (org-region-active-p))
20444 (org-call-for-shift-select 'next-line))
20445 ((org-at-timestamp-p 'lax)
20446 (call-interactively (if org-edit-timestamp-down-means-later
20447 'org-timestamp-up 'org-timestamp-down)))
20448 ((and (not (eq org-support-shift-select 'always))
20449 org-enable-priority-commands
20450 (org-at-heading-p))
20451 (call-interactively 'org-priority-down))
20452 ((and (not org-support-shift-select) (org-at-item-p))
20453 (call-interactively 'org-next-item))
20454 ((org-clocktable-try-shift 'down arg))
20455 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20456 (org-support-shift-select
20457 (org-call-for-shift-select 'next-line))
20458 (t (org-shiftselect-error))))
20460 (defun org-shiftright (&optional arg)
20461 "Cycle the thing at point or in the current line, depending on context.
20462 Depending on context, this does one of the following:
20464 - switch a timestamp at point one day into the future
20465 - on a headline, switch to the next TODO keyword.
20466 - on an item, switch entire list to the next bullet type
20467 - on a property line, switch to the next allowed value
20468 - on a clocktable definition line, move time block into the future"
20469 (interactive "P")
20470 (cond
20471 ((run-hook-with-args-until-success 'org-shiftright-hook))
20472 ((and org-support-shift-select (org-region-active-p))
20473 (org-call-for-shift-select 'forward-char))
20474 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20475 ((and (not (eq org-support-shift-select 'always))
20476 (org-at-heading-p))
20477 (let ((org-inhibit-logging
20478 (not org-treat-S-cursor-todo-selection-as-state-change))
20479 (org-inhibit-blocking
20480 (not org-treat-S-cursor-todo-selection-as-state-change)))
20481 (org-call-with-arg 'org-todo 'right)))
20482 ((or (and org-support-shift-select
20483 (not (eq org-support-shift-select 'always))
20484 (org-at-item-bullet-p))
20485 (and (not org-support-shift-select) (org-at-item-p)))
20486 (org-call-with-arg 'org-cycle-list-bullet nil))
20487 ((and (not (eq org-support-shift-select 'always))
20488 (org-at-property-p))
20489 (call-interactively 'org-property-next-allowed-value))
20490 ((org-clocktable-try-shift 'right arg))
20491 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20492 (org-support-shift-select
20493 (org-call-for-shift-select 'forward-char))
20494 (t (org-shiftselect-error))))
20496 (defun org-shiftleft (&optional arg)
20497 "Cycle the thing at point or in the current line, depending on context.
20498 Depending on context, this does one of the following:
20500 - switch a timestamp at point one day into the past
20501 - on a headline, switch to the previous TODO keyword.
20502 - on an item, switch entire list to the previous bullet type
20503 - on a property line, switch to the previous allowed value
20504 - on a clocktable definition line, move time block into the past"
20505 (interactive "P")
20506 (cond
20507 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20508 ((and org-support-shift-select (org-region-active-p))
20509 (org-call-for-shift-select 'backward-char))
20510 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20511 ((and (not (eq org-support-shift-select 'always))
20512 (org-at-heading-p))
20513 (let ((org-inhibit-logging
20514 (not org-treat-S-cursor-todo-selection-as-state-change))
20515 (org-inhibit-blocking
20516 (not org-treat-S-cursor-todo-selection-as-state-change)))
20517 (org-call-with-arg 'org-todo 'left)))
20518 ((or (and org-support-shift-select
20519 (not (eq org-support-shift-select 'always))
20520 (org-at-item-bullet-p))
20521 (and (not org-support-shift-select) (org-at-item-p)))
20522 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20523 ((and (not (eq org-support-shift-select 'always))
20524 (org-at-property-p))
20525 (call-interactively 'org-property-previous-allowed-value))
20526 ((org-clocktable-try-shift 'left arg))
20527 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20528 (org-support-shift-select
20529 (org-call-for-shift-select 'backward-char))
20530 (t (org-shiftselect-error))))
20532 (defun org-shiftcontrolright ()
20533 "Switch to next TODO set."
20534 (interactive)
20535 (cond
20536 ((and org-support-shift-select (org-region-active-p))
20537 (org-call-for-shift-select 'forward-word))
20538 ((and (not (eq org-support-shift-select 'always))
20539 (org-at-heading-p))
20540 (org-call-with-arg 'org-todo 'nextset))
20541 (org-support-shift-select
20542 (org-call-for-shift-select 'forward-word))
20543 (t (org-shiftselect-error))))
20545 (defun org-shiftcontrolleft ()
20546 "Switch to previous TODO set."
20547 (interactive)
20548 (cond
20549 ((and org-support-shift-select (org-region-active-p))
20550 (org-call-for-shift-select 'backward-word))
20551 ((and (not (eq org-support-shift-select 'always))
20552 (org-at-heading-p))
20553 (org-call-with-arg 'org-todo 'previousset))
20554 (org-support-shift-select
20555 (org-call-for-shift-select 'backward-word))
20556 (t (org-shiftselect-error))))
20558 (defun org-shiftcontrolup (&optional n)
20559 "Change timestamps synchronously up in CLOCK log lines.
20560 Optional argument N tells to change by that many units."
20561 (interactive "P")
20562 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20563 (let (org-support-shift-select)
20564 (org-clock-timestamps-up n))
20565 (user-error "Not at a clock log")))
20567 (defun org-shiftcontroldown (&optional n)
20568 "Change timestamps synchronously down in CLOCK log lines.
20569 Optional argument N tells to change by that many units."
20570 (interactive "P")
20571 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20572 (let (org-support-shift-select)
20573 (org-clock-timestamps-down n))
20574 (user-error "Not at a clock log")))
20576 (defun org-increase-number-at-point (&optional inc)
20577 "Increment the number at point.
20578 With an optional prefix numeric argument INC, increment using
20579 this numeric value."
20580 (interactive "p")
20581 (if (not (number-at-point))
20582 (user-error "Not on a number")
20583 (unless inc (setq inc 1))
20584 (let ((pos (point))
20585 (beg (skip-chars-backward "-+^/*0-9eE."))
20586 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20587 (setq nap (buffer-substring-no-properties
20588 (+ pos beg) (+ pos beg end)))
20589 (delete-region (+ pos beg) (+ pos beg end))
20590 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20591 (when (org-at-table-p)
20592 (org-table-align)
20593 (org-table-end-of-field 1))))
20595 (defun org-decrease-number-at-point (&optional inc)
20596 "Decrement the number at point.
20597 With an optional prefix numeric argument INC, decrement using
20598 this numeric value."
20599 (interactive "p")
20600 (org-increase-number-at-point (- (or inc 1))))
20602 (defun org-ctrl-c-ret ()
20603 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20604 (interactive)
20605 (cond
20606 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20607 (t (call-interactively 'org-insert-heading))))
20609 (defun org-find-visible ()
20610 (let ((s (point)))
20611 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20612 (get-char-property s 'invisible)))
20614 (defun org-find-invisible ()
20615 (let ((s (point)))
20616 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20617 (not (get-char-property s 'invisible))))
20620 (defun org-copy-visible (beg end)
20621 "Copy the visible parts of the region."
20622 (interactive "r")
20623 (let ((result ""))
20624 (while (/= beg end)
20625 (when (get-char-property beg 'invisible)
20626 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20627 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20628 (setq result (concat result (buffer-substring beg next)))
20629 (setq beg next)))
20630 (kill-new result)))
20632 (defun org-copy-special ()
20633 "Copy region in table or copy current subtree.
20634 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20635 context. See the individual commands for more information."
20636 (interactive)
20637 (call-interactively
20638 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20640 (defun org-cut-special ()
20641 "Cut region in table or cut current subtree.
20642 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20643 context. See the individual commands for more information."
20644 (interactive)
20645 (call-interactively
20646 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20648 (defun org-paste-special (arg)
20649 "Paste rectangular region into table, or past subtree relative to level.
20650 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20651 See the individual commands for more information."
20652 (interactive "P")
20653 (if (org-at-table-p)
20654 (org-table-paste-rectangle)
20655 (org-paste-subtree arg)))
20657 (defun org-edit-special (&optional arg)
20658 "Call a special editor for the element at point.
20659 When at a table, call the formula editor with `org-table-edit-formulas'.
20660 When in a source code block, call `org-edit-src-code'.
20661 When in a fixed-width region, call `org-edit-fixed-width-region'.
20662 When in an export block, call `org-edit-export-block'.
20663 When in a LaTeX environment, call `org-edit-latex-environment'.
20664 When at an #+INCLUDE keyword, visit the included file.
20665 When at a footnote reference, call `org-edit-footnote-reference'
20666 On a link, call `ffap' to visit the link at point.
20667 Otherwise, return a user error."
20668 (interactive "P")
20669 (let ((element (org-element-at-point)))
20670 (barf-if-buffer-read-only)
20671 (pcase (org-element-type element)
20672 (`src-block
20673 (if (not arg) (org-edit-src-code)
20674 (let* ((info (org-babel-get-src-block-info))
20675 (lang (nth 0 info))
20676 (params (nth 2 info))
20677 (session (cdr (assq :session params))))
20678 (if (not session) (org-edit-src-code)
20679 ;; At a src-block with a session and function called with
20680 ;; an ARG: switch to the buffer related to the inferior
20681 ;; process.
20682 (switch-to-buffer
20683 (funcall (intern (concat "org-babel-prep-session:" lang))
20684 session params))))))
20685 (`keyword
20686 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20687 (org-open-link-from-string
20688 (format "[[%s]]"
20689 (expand-file-name
20690 (let ((value (org-element-property :value element)))
20691 (cond ((org-file-url-p value)
20692 (user-error "The file is specified as a URL, cannot be edited"))
20693 ((not (org-string-nw-p value))
20694 (user-error "No file to edit"))
20695 ((string-match "\\`\"\\(.*?\\)\"" value)
20696 (match-string 1 value))
20697 ((string-match "\\`[^ \t\"]\\S-*" value)
20698 (match-string 0 value))
20699 (t (user-error "No valid file specified")))))))
20700 (user-error "No special environment to edit here")))
20701 (`table
20702 (if (eq (org-element-property :type element) 'table.el)
20703 (org-edit-table.el)
20704 (call-interactively 'org-table-edit-formulas)))
20705 ;; Only Org tables contain `table-row' type elements.
20706 (`table-row (call-interactively 'org-table-edit-formulas))
20707 (`example-block (org-edit-src-code))
20708 (`export-block (org-edit-export-block))
20709 (`fixed-width (org-edit-fixed-width-region))
20710 (`latex-environment (org-edit-latex-environment))
20712 ;; No notable element at point. Though, we may be at a link or
20713 ;; a footnote reference, which are objects. Thus, scan deeper.
20714 (let ((context (org-element-context element)))
20715 (pcase (org-element-type context)
20716 (`footnote-reference (org-edit-footnote-reference))
20717 (`inline-src-block (org-edit-inline-src-code))
20718 (`link (call-interactively #'ffap))
20719 (_ (user-error "No special environment to edit here"))))))))
20721 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20722 (defun org-ctrl-c-ctrl-c (&optional arg)
20723 "Set tags in headline, or update according to changed information at point.
20725 This command does many different things, depending on context:
20727 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20728 this is what we do.
20730 - If the cursor is on a statistics cookie, update it.
20732 - If the cursor is in a headline, prompt for tags and insert them
20733 into the current line, aligned to `org-tags-column'. When called
20734 with prefix arg, realign all tags in the current buffer.
20736 - If the cursor is in one of the special #+KEYWORD lines, this
20737 triggers scanning the buffer for these lines and updating the
20738 information.
20740 - If the cursor is inside a table, realign the table. This command
20741 works even if the automatic table editor has been turned off.
20743 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20744 the entire table.
20746 - If the cursor is at a footnote reference or definition, jump to
20747 the corresponding definition or references, respectively.
20749 - If the cursor is a the beginning of a dynamic block, update it.
20751 - If the current buffer is a capture buffer, close note and file it.
20753 - If the cursor is on a <<<target>>>, update radio targets and
20754 corresponding links in this buffer.
20756 - If the cursor is on a numbered item in a plain list, renumber the
20757 ordered list.
20759 - If the cursor is on a checkbox, toggle it.
20761 - If the cursor is on a code block, evaluate it. The variable
20762 `org-confirm-babel-evaluate' can be used to control prompting
20763 before code block evaluation, by default every code block
20764 evaluation requires confirmation. Code block evaluation can be
20765 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20766 (interactive "P")
20767 (cond
20768 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20769 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20770 (org-remove-occur-highlights)
20771 (message "Temporary highlights/overlays removed from current buffer"))
20772 ((and (local-variable-p 'org-finish-function)
20773 (fboundp org-finish-function))
20774 (funcall org-finish-function))
20775 ((org-babel-hash-at-point))
20776 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20778 (let* ((context
20779 (org-element-lineage
20780 (org-element-context)
20781 ;; Limit to supported contexts.
20782 '(babel-call clock dynamic-block footnote-definition
20783 footnote-reference inline-babel-call inline-src-block
20784 inlinetask item keyword node-property paragraph
20785 plain-list property-drawer radio-target src-block
20786 statistics-cookie table table-cell table-row
20787 timestamp)
20789 (type (org-element-type context)))
20790 ;; For convenience: at the first line of a paragraph on the same
20791 ;; line as an item, apply function on that item instead.
20792 (when (eq type 'paragraph)
20793 (let ((parent (org-element-property :parent context)))
20794 (when (and (eq (org-element-type parent) 'item)
20795 (= (line-beginning-position)
20796 (org-element-property :begin parent)))
20797 (setq context parent)
20798 (setq type 'item))))
20799 ;; Act according to type of element or object at point.
20801 ;; Do nothing on a blank line, except if it is contained in
20802 ;; a src block. Hence, we first check if point is in such
20803 ;; a block and then if it is at a blank line.
20804 (pcase type
20805 ((or `inline-src-block `src-block)
20806 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20807 (org-babel-eval-wipe-error-buffer)
20808 (org-babel-execute-src-block
20809 current-prefix-arg (org-babel-get-src-block-info nil context))))
20810 ((guard (org-match-line "[ \t]*$"))
20811 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20812 (user-error
20813 (substitute-command-keys
20814 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20815 ((or `babel-call `inline-babel-call)
20816 (let ((info (org-babel-lob-get-info context)))
20817 (when info (org-babel-execute-src-block nil info))))
20818 (`clock (org-clock-update-time-maybe))
20819 (`dynamic-block
20820 (save-excursion
20821 (goto-char (org-element-property :post-affiliated context))
20822 (org-update-dblock)))
20823 (`footnote-definition
20824 (goto-char (org-element-property :post-affiliated context))
20825 (call-interactively 'org-footnote-action))
20826 (`footnote-reference (call-interactively #'org-footnote-action))
20827 ((or `headline `inlinetask)
20828 (save-excursion (goto-char (org-element-property :begin context))
20829 (call-interactively #'org-set-tags)))
20830 (`item
20831 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20832 ;; unconditionally, whereas `C-u' will toggle its presence.
20833 ;; Without a universal argument, if the item has a checkbox,
20834 ;; toggle it. Otherwise repair the list.
20835 (let* ((box (org-element-property :checkbox context))
20836 (struct (org-element-property :structure context))
20837 (old-struct (copy-tree struct))
20838 (parents (org-list-parents-alist struct))
20839 (prevs (org-list-prevs-alist struct))
20840 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20841 (org-list-set-checkbox
20842 (org-element-property :begin context) struct
20843 (cond ((equal arg '(16)) "[-]")
20844 ((and (not box) (equal arg '(4))) "[ ]")
20845 ((or (not box) (equal arg '(4))) nil)
20846 ((eq box 'on) "[ ]")
20847 (t "[X]")))
20848 ;; Mimic `org-list-write-struct' but with grabbing a return
20849 ;; value from `org-list-struct-fix-box'.
20850 (org-list-struct-fix-ind struct parents 2)
20851 (org-list-struct-fix-item-end struct)
20852 (org-list-struct-fix-bul struct prevs)
20853 (org-list-struct-fix-ind struct parents)
20854 (let ((block-item
20855 (org-list-struct-fix-box struct parents prevs orderedp)))
20856 (if (and box (equal struct old-struct))
20857 (if (equal arg '(16))
20858 (message "Checkboxes already reset")
20859 (user-error "Cannot toggle this checkbox: %s"
20860 (if (eq box 'on)
20861 "all subitems checked"
20862 "unchecked subitems")))
20863 (org-list-struct-apply-struct struct old-struct)
20864 (org-update-checkbox-count-maybe))
20865 (when block-item
20866 (message "Checkboxes were removed due to empty box at line %d"
20867 (org-current-line block-item))))))
20868 (`keyword
20869 (let ((org-inhibit-startup-visibility-stuff t)
20870 (org-startup-align-all-tables nil))
20871 (when (boundp 'org-table-coordinate-overlays)
20872 (mapc #'delete-overlay org-table-coordinate-overlays)
20873 (setq org-table-coordinate-overlays nil))
20874 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20875 (message "Local setup has been refreshed"))
20876 (`plain-list
20877 ;; At a plain list, with a double C-u argument, set
20878 ;; checkboxes of each item to "[-]", whereas a single one
20879 ;; will toggle their presence according to the state of the
20880 ;; first item in the list. Without an argument, repair the
20881 ;; list.
20882 (let* ((begin (org-element-property :contents-begin context))
20883 (beginm (move-marker (make-marker) begin))
20884 (struct (org-element-property :structure context))
20885 (old-struct (copy-tree struct))
20886 (first-box (save-excursion
20887 (goto-char begin)
20888 (looking-at org-list-full-item-re)
20889 (match-string-no-properties 3)))
20890 (new-box (cond ((equal arg '(16)) "[-]")
20891 ((equal arg '(4)) (unless first-box "[ ]"))
20892 ((equal first-box "[X]") "[ ]")
20893 (t "[X]"))))
20894 (cond
20895 (arg
20896 (dolist (pos
20897 (org-list-get-all-items
20898 begin struct (org-list-prevs-alist struct)))
20899 (org-list-set-checkbox pos struct new-box)))
20900 ((and first-box (eq (point) begin))
20901 ;; For convenience, when point is at bol on the first
20902 ;; item of the list and no argument is provided, simply
20903 ;; toggle checkbox of that item, if any.
20904 (org-list-set-checkbox begin struct new-box)))
20905 (org-list-write-struct
20906 struct (org-list-parents-alist struct) old-struct)
20907 (org-update-checkbox-count-maybe)
20908 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20909 ((or `property-drawer `node-property)
20910 (call-interactively #'org-property-action))
20911 (`radio-target
20912 (call-interactively #'org-update-radio-target-regexp))
20913 (`statistics-cookie
20914 (call-interactively #'org-update-statistics-cookies))
20915 ((or `table `table-cell `table-row)
20916 ;; At a table, recalculate every field and align it. Also
20917 ;; send the table if necessary. If the table has
20918 ;; a `table.el' type, just give up. At a table row or cell,
20919 ;; maybe recalculate line but always align table.
20920 (if (eq (org-element-property :type context) 'table.el)
20921 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20922 Use `\\[org-edit-special]' to edit table.el tables"))
20923 (if (or (eq type 'table)
20924 ;; Check if point is at a TBLFM line.
20925 (and (eq type 'table-row)
20926 (= (point) (org-element-property :end context))))
20927 (save-excursion
20928 (if (org-at-TBLFM-p)
20929 (progn (require 'org-table)
20930 (org-table-calc-current-TBLFM))
20931 (goto-char (org-element-property :contents-begin context))
20932 (org-call-with-arg 'org-table-recalculate (or arg t))
20933 (orgtbl-send-table 'maybe)))
20934 (org-table-maybe-eval-formula)
20935 (cond (arg (call-interactively #'org-table-recalculate))
20936 ((org-table-maybe-recalculate-line))
20937 (t (org-table-align))))))
20938 (`timestamp (org-timestamp-change 0 'day))
20939 ((and `nil (guard (org-at-heading-p)))
20940 ;; When point is on an unsupported object type, we can miss
20941 ;; the fact that it also is at a heading. Handle it here.
20942 (call-interactively #'org-set-tags))
20943 ((guard
20944 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20946 (user-error
20947 (substitute-command-keys
20948 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20950 (defun org-mode-restart ()
20951 (interactive)
20952 (let ((indent-status (bound-and-true-p org-indent-mode)))
20953 (funcall major-mode)
20954 (hack-local-variables)
20955 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20956 (org-indent-mode -1))
20957 (org-reset-file-cache))
20958 (message "%s restarted" major-mode))
20960 (defun org-kill-note-or-show-branches ()
20961 "Abort storing current note, or call `outline-show-branches'."
20962 (interactive)
20963 (if (not org-finish-function)
20964 (progn
20965 (outline-hide-subtree)
20966 (call-interactively 'outline-show-branches))
20967 (let ((org-note-abort t))
20968 (funcall org-finish-function))))
20970 (defun org-delete-indentation (&optional arg)
20971 "Join current line to previous and fix whitespace at join.
20973 If previous line is a headline add to headline title. Otherwise
20974 the function calls `delete-indentation'.
20976 With a non-nil optional argument, join it to the following one."
20977 (interactive "*P")
20978 (if (save-excursion
20979 (beginning-of-line (if arg 1 0))
20980 (let ((case-fold-search nil))
20981 (looking-at org-complex-heading-regexp)))
20982 ;; At headline.
20983 (let ((tags-column (when (match-beginning 5)
20984 (save-excursion (goto-char (match-beginning 5))
20985 (current-column))))
20986 (string (concat " " (progn (when arg (forward-line 1))
20987 (org-trim (delete-and-extract-region
20988 (line-beginning-position)
20989 (line-end-position)))))))
20990 (unless (bobp) (delete-region (point) (1- (point))))
20991 (goto-char (or (match-end 4)
20992 (match-beginning 5)
20993 (match-end 0)))
20994 (skip-chars-backward " \t")
20995 (save-excursion (insert string))
20996 ;; Adjust alignment of tags.
20997 (cond
20998 ((not tags-column)) ;no tags
20999 (org-auto-align-tags (org-set-tags nil t))
21000 (t (org--align-tags-here tags-column)))) ;preserve tags column
21001 (delete-indentation arg)))
21003 (defun org-open-line (n)
21004 "Insert a new row in tables, call `open-line' elsewhere.
21005 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21006 As a special case, when a document starts with a table, allow to
21007 call `open-line' on the very first character."
21008 (interactive "*p")
21009 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21010 (org-table-insert-row)
21011 (open-line n)))
21013 (defun org-return (&optional indent)
21014 "Goto next table row or insert a newline.
21016 Calls `org-table-next-row' or `newline', depending on context.
21018 When optional INDENT argument is non-nil, call
21019 `newline-and-indent' instead of `newline'.
21021 When `org-return-follows-link' is non-nil and point is on
21022 a timestamp or a link, call `org-open-at-point'. However, it
21023 will not happen if point is in a table or on a \"dead\"
21024 object (e.g., within a comment). In these case, you need to use
21025 `org-open-at-point' directly."
21026 (interactive)
21027 (let ((context (if org-return-follows-link (org-element-context)
21028 (org-element-at-point))))
21029 (cond
21030 ;; In a table, call `org-table-next-row'.
21031 ((or (and (eq (org-element-type context) 'table)
21032 (>= (point) (org-element-property :contents-begin context))
21033 (< (point) (org-element-property :contents-end context)))
21034 (org-element-lineage context '(table-row table-cell) t))
21035 (org-table-justify-field-maybe)
21036 (call-interactively #'org-table-next-row))
21037 ;; On a link or a timestamp, call `org-open-at-point' if
21038 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21039 ;; locations, e.g., in a comment, as `org-open-at-point'.
21040 ((and org-return-follows-link
21041 (or (org-in-regexp org-ts-regexp-both nil t)
21042 (org-in-regexp org-tsr-regexp-both nil t)
21043 (org-in-regexp org-any-link-re nil t)))
21044 (call-interactively #'org-open-at-point))
21045 ;; Insert newline in heading, but preserve tags.
21046 ((and (not (bolp))
21047 (save-excursion (beginning-of-line)
21048 (let ((case-fold-search nil))
21049 (looking-at org-complex-heading-regexp))))
21050 ;; At headline. Split line. However, if point is on keyword,
21051 ;; priority cookie or tags, do not break any of them: add
21052 ;; a newline after the headline instead.
21053 (let ((tags-column (and (match-beginning 5)
21054 (save-excursion (goto-char (match-beginning 5))
21055 (current-column))))
21056 (string
21057 (when (and (match-end 4) (org-point-in-group (point) 4))
21058 (delete-and-extract-region (point) (match-end 4)))))
21059 ;; Adjust tag alignment.
21060 (cond
21061 ((not (and tags-column string)))
21062 (org-auto-align-tags (org-set-tags nil t))
21063 (t (org--align-tags-here tags-column))) ;preserve tags column
21064 (end-of-line)
21065 (org-show-entry)
21066 (if indent (newline-and-indent) (newline))
21067 (when string (save-excursion (insert (org-trim string))))))
21068 ;; In a list, make sure indenting keeps trailing text within.
21069 ((and indent
21070 (not (eolp))
21071 (org-element-lineage context '(item)))
21072 (let ((trailing-data
21073 (delete-and-extract-region (point) (line-end-position))))
21074 (newline-and-indent)
21075 (save-excursion (insert trailing-data))))
21076 (t (if indent (newline-and-indent) (newline))))))
21078 (defun org-return-indent ()
21079 "Goto next table row or insert a newline and indent.
21080 Calls `org-table-next-row' or `newline-and-indent', depending on
21081 context. See the individual commands for more information."
21082 (interactive)
21083 (org-return t))
21085 (defun org-ctrl-c-star ()
21086 "Compute table, or change heading status of lines.
21087 Calls `org-table-recalculate' or `org-toggle-heading',
21088 depending on context."
21089 (interactive)
21090 (cond
21091 ((org-at-table-p)
21092 (call-interactively 'org-table-recalculate))
21094 ;; Convert all lines in region to list items
21095 (call-interactively 'org-toggle-heading))))
21097 (defun org-ctrl-c-minus ()
21098 "Insert separator line in table or modify bullet status of line.
21099 Also turns a plain line or a region of lines into list items.
21100 Calls `org-table-insert-hline', `org-toggle-item', or
21101 `org-cycle-list-bullet', depending on context."
21102 (interactive)
21103 (cond
21104 ((org-at-table-p)
21105 (call-interactively 'org-table-insert-hline))
21106 ((org-region-active-p)
21107 (call-interactively 'org-toggle-item))
21108 ((org-in-item-p)
21109 (call-interactively 'org-cycle-list-bullet))
21111 (call-interactively 'org-toggle-item))))
21113 (defun org-toggle-heading (&optional nstars)
21114 "Convert headings to normal text, or items or text to headings.
21115 If there is no active region, only convert the current line.
21117 With a `\\[universal-argument]' prefix, convert the whole list at
21118 point into heading.
21120 In a region:
21122 - If the first non blank line is a headline, remove the stars
21123 from all headlines in the region.
21125 - If it is a normal line, turn each and every normal line (i.e.,
21126 not an heading or an item) in the region into headings. If you
21127 want to convert only the first line of this region, use one
21128 universal prefix argument.
21130 - If it is a plain list item, turn all plain list items into headings.
21132 When converting a line into a heading, the number of stars is chosen
21133 such that the lines become children of the current entry. However,
21134 when a numeric prefix argument is given, its value determines the
21135 number of stars to add."
21136 (interactive "P")
21137 (let ((skip-blanks
21138 (function
21139 ;; Return beginning of first non-blank line, starting from
21140 ;; line at POS.
21141 (lambda (pos)
21142 (save-excursion
21143 (goto-char pos)
21144 (while (org-at-comment-p) (forward-line))
21145 (skip-chars-forward " \r\t\n")
21146 (point-at-bol)))))
21147 beg end toggled)
21148 ;; Determine boundaries of changes. If a universal prefix has
21149 ;; been given, put the list in a region. If region ends at a bol,
21150 ;; do not consider the last line to be in the region.
21152 (when (and current-prefix-arg (org-at-item-p))
21153 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21154 (org-mark-element))
21156 (if (org-region-active-p)
21157 (setq beg (funcall skip-blanks (region-beginning))
21158 end (copy-marker (save-excursion
21159 (goto-char (region-end))
21160 (if (bolp) (point) (point-at-eol)))))
21161 (setq beg (funcall skip-blanks (point-at-bol))
21162 end (copy-marker (point-at-eol))))
21163 ;; Ensure inline tasks don't count as headings.
21164 (org-with-limited-levels
21165 (save-excursion
21166 (goto-char beg)
21167 (cond
21168 ;; Case 1. Started at an heading: de-star headings.
21169 ((org-at-heading-p)
21170 (while (< (point) end)
21171 (when (org-at-heading-p t)
21172 (looking-at org-outline-regexp) (replace-match "")
21173 (setq toggled t))
21174 (forward-line)))
21175 ;; Case 2. Started at an item: change items into headlines.
21176 ;; One star will be added by `org-list-to-subtree'.
21177 ((org-at-item-p)
21178 (while (< (point) end)
21179 (when (org-at-item-p)
21180 ;; Pay attention to cases when region ends before list.
21181 (let* ((struct (org-list-struct))
21182 (list-end
21183 (min (org-list-get-bottom-point struct) (1+ end))))
21184 (save-restriction
21185 (narrow-to-region (point) list-end)
21186 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21187 (setq toggled t))
21188 (forward-line)))
21189 ;; Case 3. Started at normal text: make every line an heading,
21190 ;; skipping headlines and items.
21191 (t (let* ((stars
21192 (make-string
21193 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21194 (add-stars
21195 (cond (nstars "") ; stars from prefix only
21196 ((equal stars "") "*") ; before first heading
21197 (org-odd-levels-only "**") ; inside heading, odd
21198 (t "*"))) ; inside heading, oddeven
21199 (rpl (concat stars add-stars " "))
21200 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21201 (while (< (point) (if (equal nstars '(4)) lend end))
21202 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21203 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21204 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21205 (forward-line)))))))
21206 (unless toggled (message "Cannot toggle heading from here"))))
21208 (defun org-meta-return (&optional arg)
21209 "Insert a new heading or wrap a region in a table.
21210 Calls `org-insert-heading', `org-insert-item' or
21211 `org-table-wrap-region', depending on context. When called with
21212 an argument, unconditionally call `org-insert-heading'."
21213 (interactive "P")
21214 (org-check-before-invisible-edit 'insert)
21215 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21216 (call-interactively (cond (arg #'org-insert-heading)
21217 ((org-at-table-p) #'org-table-wrap-region)
21218 ((org-in-item-p) #'org-insert-item)
21219 (t #'org-insert-heading)))))
21221 ;;; Menu entries
21223 (defsubst org-in-subtree-not-table-p ()
21224 "Are we in a subtree and not in a table?"
21225 (and (not (org-before-first-heading-p))
21226 (not (org-at-table-p))))
21228 ;; Define the Org mode menus
21229 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21230 '("Tbl"
21231 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21232 ["Next Field" org-cycle (org-at-table-p)]
21233 ["Previous Field" org-shifttab (org-at-table-p)]
21234 ["Next Row" org-return (org-at-table-p)]
21235 "--"
21236 ["Blank Field" org-table-blank-field (org-at-table-p)]
21237 ["Edit Field" org-table-edit-field (org-at-table-p)]
21238 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21239 "--"
21240 ("Column"
21241 ["Move Column Left" org-metaleft (org-at-table-p)]
21242 ["Move Column Right" org-metaright (org-at-table-p)]
21243 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21244 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21245 ("Row"
21246 ["Move Row Up" org-metaup (org-at-table-p)]
21247 ["Move Row Down" org-metadown (org-at-table-p)]
21248 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21249 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21250 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21251 "--"
21252 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21253 ("Rectangle"
21254 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21255 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21256 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21257 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21258 "--"
21259 ("Calculate"
21260 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21261 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21262 ["Edit Formulas" org-edit-special (org-at-table-p)]
21263 "--"
21264 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21265 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21266 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21267 "--"
21268 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21269 "--"
21270 ["Sum Column/Rectangle" org-table-sum
21271 (or (org-at-table-p) (org-region-active-p))]
21272 ["Which Column?" org-table-current-column (org-at-table-p)])
21273 ["Debug Formulas"
21274 org-table-toggle-formula-debugger
21275 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21276 ["Show Col/Row Numbers"
21277 org-table-toggle-coordinate-overlays
21278 :style toggle
21279 :selected (bound-and-true-p org-table-overlay-coordinates)]
21280 "--"
21281 ["Create" org-table-create (not (org-at-table-p))]
21282 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21283 ["Import from File" org-table-import (not (org-at-table-p))]
21284 ["Export to File" org-table-export (org-at-table-p)]
21285 "--"
21286 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21287 "--"
21288 ("Plot"
21289 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21290 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21292 (easy-menu-define org-org-menu org-mode-map "Org menu"
21293 '("Org"
21294 ("Show/Hide"
21295 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21296 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21297 ["Sparse Tree..." org-sparse-tree t]
21298 ["Reveal Context" org-reveal t]
21299 ["Show All" outline-show-all t]
21300 "--"
21301 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21302 "--"
21303 ["New Heading" org-insert-heading t]
21304 ("Navigate Headings"
21305 ["Up" outline-up-heading t]
21306 ["Next" outline-next-visible-heading t]
21307 ["Previous" outline-previous-visible-heading t]
21308 ["Next Same Level" outline-forward-same-level t]
21309 ["Previous Same Level" outline-backward-same-level t]
21310 "--"
21311 ["Jump" org-goto t])
21312 ("Edit Structure"
21313 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21314 "--"
21315 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21316 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21317 "--"
21318 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21319 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21320 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21321 "--"
21322 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21323 "--"
21324 ["Copy visible text" org-copy-visible t]
21325 "--"
21326 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21327 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21328 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21329 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21330 "--"
21331 ["Sort Region/Children" org-sort t]
21332 "--"
21333 ["Convert to odd levels" org-convert-to-odd-levels t]
21334 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21335 ("Editing"
21336 ["Emphasis..." org-emphasize t]
21337 ["Edit Source Example" org-edit-special t]
21338 "--"
21339 ["Footnote new/jump" org-footnote-action t]
21340 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21341 ("Archive"
21342 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21343 "--"
21344 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21345 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21346 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21348 "--"
21349 ("Hyperlinks"
21350 ["Store Link (Global)" org-store-link t]
21351 ["Find existing link to here" org-occur-link-in-agenda-files t]
21352 ["Insert Link" org-insert-link t]
21353 ["Follow Link" org-open-at-point t]
21354 "--"
21355 ["Next link" org-next-link t]
21356 ["Previous link" org-previous-link t]
21357 "--"
21358 ["Descriptive Links"
21359 org-toggle-link-display
21360 :style radio
21361 :selected org-descriptive-links
21363 ["Literal Links"
21364 org-toggle-link-display
21365 :style radio
21366 :selected (not org-descriptive-links)])
21367 "--"
21368 ("TODO Lists"
21369 ["TODO/DONE/-" org-todo t]
21370 ("Select keyword"
21371 ["Next keyword" org-shiftright (org-at-heading-p)]
21372 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21373 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21374 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21375 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21376 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21377 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21378 "--"
21379 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21380 :selected org-enforce-todo-dependencies :style toggle :active t]
21381 "Settings for tree at point"
21382 ["Do Children sequentially" org-toggle-ordered-property :style radio
21383 :selected (org-entry-get nil "ORDERED")
21384 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21385 ["Do Children parallel" org-toggle-ordered-property :style radio
21386 :selected (not (org-entry-get nil "ORDERED"))
21387 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21388 "--"
21389 ["Set Priority" org-priority t]
21390 ["Priority Up" org-shiftup t]
21391 ["Priority Down" org-shiftdown t]
21392 "--"
21393 ["Get news from all feeds" org-feed-update-all t]
21394 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21395 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21396 ("TAGS and Properties"
21397 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21398 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21399 "--"
21400 ["Set property" org-set-property (not (org-before-first-heading-p))]
21401 ["Column view of properties" org-columns t]
21402 ["Insert Column View DBlock" org-columns-insert-dblock t])
21403 ("Dates and Scheduling"
21404 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21405 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21406 ("Change Date"
21407 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21408 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21409 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21410 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21411 ["Compute Time Range" org-evaluate-time-range t]
21412 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21413 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21414 "--"
21415 ["Custom time format" org-toggle-time-stamp-overlays
21416 :style radio :selected org-display-custom-times]
21417 "--"
21418 ["Goto Calendar" org-goto-calendar t]
21419 ["Date from Calendar" org-date-from-calendar t]
21420 "--"
21421 ["Start/Restart Timer" org-timer-start t]
21422 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21423 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21424 ["Insert Timer String" org-timer t]
21425 ["Insert Timer Item" org-timer-item t])
21426 ("Logging work"
21427 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21428 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21429 ["Clock out" org-clock-out t]
21430 ["Clock cancel" org-clock-cancel t]
21431 "--"
21432 ["Mark as default task" org-clock-mark-default-task t]
21433 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21434 ["Goto running clock" org-clock-goto t]
21435 "--"
21436 ["Display times" org-clock-display t]
21437 ["Create clock table" org-clock-report t]
21438 "--"
21439 ["Record DONE time"
21440 (progn (setq org-log-done (not org-log-done))
21441 (message "Switching to %s will %s record a timestamp"
21442 (car org-done-keywords)
21443 (if org-log-done "automatically" "not")))
21444 :style toggle :selected org-log-done])
21445 "--"
21446 ["Agenda Command..." org-agenda t]
21447 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21448 ("File List for Agenda")
21449 ("Special views current file"
21450 ["TODO Tree" org-show-todo-tree t]
21451 ["Check Deadlines" org-check-deadlines t]
21452 ["Tags/Property tree" org-match-sparse-tree t])
21453 "--"
21454 ["Export/Publish..." org-export-dispatch t]
21455 ("LaTeX"
21456 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21457 :selected org-cdlatex-mode]
21458 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21459 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21460 ["Modify math symbol" org-cdlatex-math-modify
21461 (org-inside-LaTeX-fragment-p)]
21462 ["Insert citation" org-reftex-citation t])
21463 "--"
21464 ("MobileOrg"
21465 ["Push Files and Views" org-mobile-push t]
21466 ["Get Captured and Flagged" org-mobile-pull t]
21467 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21468 "--"
21469 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21470 "--"
21471 ("Documentation"
21472 ["Show Version" org-version t]
21473 ["Info Documentation" org-info t])
21474 ("Customize"
21475 ["Browse Org Group" org-customize t]
21476 "--"
21477 ["Expand This Menu" org-create-customize-menu
21478 (fboundp 'customize-menu-create)])
21479 ["Send bug report" org-submit-bug-report t]
21480 "--"
21481 ("Refresh/Reload"
21482 ["Refresh setup current buffer" org-mode-restart t]
21483 ["Reload Org (after update)" org-reload t]
21484 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21487 (defun org-info (&optional node)
21488 "Read documentation for Org in the info system.
21489 With optional NODE, go directly to that node."
21490 (interactive)
21491 (info (format "(org)%s" (or node ""))))
21493 ;;;###autoload
21494 (defun org-submit-bug-report ()
21495 "Submit a bug report on Org via mail.
21497 Don't hesitate to report any problems or inaccurate documentation.
21499 If you don't have setup sending mail from (X)Emacs, please copy the
21500 output buffer into your mail program, as it gives us important
21501 information about your Org version and configuration."
21502 (interactive)
21503 (require 'reporter)
21504 (defvar reporter-prompt-for-summary-p)
21505 (org-load-modules-maybe)
21506 (org-require-autoloaded-modules)
21507 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21508 (reporter-submit-bug-report
21509 "emacs-orgmode@gnu.org"
21510 (org-version nil 'full)
21511 (let (list)
21512 (save-window-excursion
21513 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21514 (delete-other-windows)
21515 (erase-buffer)
21516 (insert "You are about to submit a bug report to the Org mailing list.
21518 We would like to add your full Org and Outline configuration to the
21519 bug report. This greatly simplifies the work of the maintainer and
21520 other experts on the mailing list.
21522 HOWEVER, some variables you have customized may contain private
21523 information. The names of customers, colleagues, or friends, might
21524 appear in the form of file names, tags, todo states, or search strings.
21525 If you answer yes to the prompt, you might want to check and remove
21526 such private information before sending the email.")
21527 (add-text-properties (point-min) (point-max) '(face org-warning))
21528 (when (yes-or-no-p "Include your Org configuration ")
21529 (mapatoms
21530 (lambda (v)
21531 (and (boundp v)
21532 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21533 (or (and (symbol-value v)
21534 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21535 (and
21536 (get v 'custom-type) (get v 'standard-value)
21537 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21538 (push v list)))))
21539 (kill-buffer (get-buffer "*Warn about privacy*"))
21540 list))
21541 nil nil
21542 "Remember to cover the basics, that is, what you expected to happen and
21543 what in fact did happen. You don't know how to make a good report? See
21545 http://orgmode.org/manual/Feedback.html#Feedback
21547 Your bug report will be posted to the Org mailing list.
21548 ------------------------------------------------------------------------")
21549 (save-excursion
21550 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21551 (replace-match "\\1Bug: \\3 [\\2]")))))
21554 (defun org-install-agenda-files-menu ()
21555 (let ((bl (buffer-list)))
21556 (save-excursion
21557 (while bl
21558 (set-buffer (pop bl))
21559 (when (derived-mode-p 'org-mode) (setq bl nil)))
21560 (when (derived-mode-p 'org-mode)
21561 (easy-menu-change
21562 '("Org") "File List for Agenda"
21563 (append
21564 (list
21565 ["Edit File List" (org-edit-agenda-file-list) t]
21566 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21567 ["Remove Current File from List" org-remove-file t]
21568 ["Cycle through agenda files" org-cycle-agenda-files t]
21569 ["Occur in all agenda files" org-occur-in-agenda-files t]
21570 "--")
21571 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21573 ;;;; Documentation
21575 (defun org-require-autoloaded-modules ()
21576 (interactive)
21577 (mapc #'require
21578 '(org-agenda org-archive org-attach org-clock org-colview org-id
21579 org-table org-timer)))
21581 ;;;###autoload
21582 (defun org-reload (&optional uncompiled)
21583 "Reload all org lisp files.
21584 With prefix arg UNCOMPILED, load the uncompiled versions."
21585 (interactive "P")
21586 (require 'loadhist)
21587 (let* ((org-dir (org-find-library-dir "org"))
21588 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21589 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21590 (remove-re (format "\\`%s\\'"
21591 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21592 (feats (delete-dups
21593 (mapcar 'file-name-sans-extension
21594 (mapcar 'file-name-nondirectory
21595 (delq nil
21596 (mapcar 'feature-file
21597 features))))))
21598 (lfeat (append
21599 (sort
21600 (setq feats
21601 (delq nil (mapcar
21602 (lambda (f)
21603 (if (and (string-match feature-re f)
21604 (not (string-match remove-re f)))
21605 f nil))
21606 feats)))
21607 'string-lessp)
21608 (list "org-version" "org")))
21609 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21610 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21611 load-uncore load-misses)
21612 (setq load-misses
21613 (delq 't
21614 (mapcar (lambda (f)
21615 (or (org-load-noerror-mustsuffix (concat org-dir f))
21616 (and (string= org-dir contrib-dir)
21617 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21618 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21619 (add-to-list 'load-uncore f 'append)
21622 lfeat)))
21623 (when load-uncore
21624 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21625 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21626 (if load-misses
21627 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21628 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21629 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21631 ;;;###autoload
21632 (defun org-customize ()
21633 "Call the customize function with org as argument."
21634 (interactive)
21635 (org-load-modules-maybe)
21636 (org-require-autoloaded-modules)
21637 (customize-browse 'org))
21639 (defun org-create-customize-menu ()
21640 "Create a full customization menu for Org mode, insert it into the menu."
21641 (interactive)
21642 (org-load-modules-maybe)
21643 (org-require-autoloaded-modules)
21644 (if (fboundp 'customize-menu-create)
21645 (progn
21646 (easy-menu-change
21647 '("Org") "Customize"
21648 `(["Browse Org group" org-customize t]
21649 "--"
21650 ,(customize-menu-create 'org)
21651 ["Set" Custom-set t]
21652 ["Save" Custom-save t]
21653 ["Reset to Current" Custom-reset-current t]
21654 ["Reset to Saved" Custom-reset-saved t]
21655 ["Reset to Standard Settings" Custom-reset-standard t]))
21656 (message "\"Org\"-menu now contains full customization menu"))
21657 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21659 ;;;; Miscellaneous stuff
21661 ;;; Generally useful functions
21663 (defun org-get-at-eol (property n)
21664 "Get text property PROPERTY at the end of line less N characters."
21665 (get-text-property (- (point-at-eol) n) property))
21667 (defun org-find-text-property-in-string (prop s)
21668 "Return the first non-nil value of property PROP in string S."
21669 (or (get-text-property 0 prop s)
21670 (get-text-property (or (next-single-property-change 0 prop s) 0)
21671 prop s)))
21673 (defun org-display-warning (message)
21674 "Display the given MESSAGE as a warning."
21675 (display-warning 'org message :warning))
21677 (defun org-eval (form)
21678 "Eval FORM and return result."
21679 (condition-case error
21680 (eval form)
21681 (error (format "%%![Error: %s]" error))))
21683 (defun org-in-clocktable-p ()
21684 "Check if the cursor is in a clocktable."
21685 (let ((pos (point)) start)
21686 (save-excursion
21687 (end-of-line 1)
21688 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21689 (setq start (match-beginning 0))
21690 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21691 (>= (match-end 0) pos)
21692 start))))
21694 (defun org-in-verbatim-emphasis ()
21695 (save-match-data
21696 (and (org-in-regexp org-verbatim-re 2)
21697 (>= (point) (match-beginning 3))
21698 (<= (point) (match-end 4)))))
21700 (defun org-overlay-display (ovl text &optional face evap)
21701 "Make overlay OVL display TEXT with face FACE."
21702 (overlay-put ovl 'display text)
21703 (if face (overlay-put ovl 'face face))
21704 (if evap (overlay-put ovl 'evaporate t)))
21706 (defun org-overlay-before-string (ovl text &optional face evap)
21707 "Make overlay OVL display TEXT with face FACE."
21708 (if face (org-add-props text nil 'face face))
21709 (overlay-put ovl 'before-string text)
21710 (if evap (overlay-put ovl 'evaporate t)))
21712 (defun org-find-overlays (prop &optional pos delete)
21713 "Find all overlays specifying PROP at POS or point.
21714 If DELETE is non-nil, delete all those overlays."
21715 (let (found)
21716 (dolist (ov (overlays-at (or pos (point))) found)
21717 (cond ((not (overlay-get ov prop)))
21718 (delete (delete-overlay ov))
21719 (t (push ov found))))))
21721 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21722 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21723 (if (and marker (marker-buffer marker)
21724 (buffer-live-p (marker-buffer marker)))
21725 (progn
21726 (pop-to-buffer-same-window (marker-buffer marker))
21727 (when (or (> marker (point-max)) (< marker (point-min)))
21728 (widen))
21729 (goto-char marker)
21730 (org-show-context 'org-goto))
21731 (if bookmark
21732 (bookmark-jump bookmark)
21733 (error "Cannot find location"))))
21735 (defun org-quote-csv-field (s)
21736 "Quote field for inclusion in CSV material."
21737 (if (string-match "[\",]" s)
21738 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21741 (defun org-force-self-insert (N)
21742 "Needed to enforce self-insert under remapping."
21743 (interactive "p")
21744 (self-insert-command N))
21746 (defun org-shorten-string (s maxlength)
21747 "Shorten string S so that it is no longer than MAXLENGTH characters.
21748 If the string is shorter or has length MAXLENGTH, just return the
21749 original string. If it is longer, the functions finds a space in the
21750 string, breaks this string off at that locations and adds three dots
21751 as ellipsis. Including the ellipsis, the string will not be longer
21752 than MAXLENGTH. If finding a good breaking point in the string does
21753 not work, the string is just chopped off in the middle of a word
21754 if necessary."
21755 (if (<= (length s) maxlength)
21757 (let* ((n (max (- maxlength 4) 1))
21758 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21759 (if (string-match re s)
21760 (concat (match-string 1 s) "...")
21761 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21763 (defun org-get-indentation (&optional line)
21764 "Get the indentation of the current line, interpreting tabs.
21765 When LINE is given, assume it represents a line and compute its indentation."
21766 (if line
21767 (when (string-match "^ *" (org-remove-tabs line))
21768 (match-end 0))
21769 (save-excursion
21770 (beginning-of-line 1)
21771 (skip-chars-forward " \t")
21772 (current-column))))
21774 (defun org-get-string-indentation (s)
21775 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21776 (let ((n -1) (i 0) (w tab-width) c)
21777 (catch 'exit
21778 (while (< (setq n (1+ n)) (length s))
21779 (setq c (aref s n))
21780 (cond ((= c ?\ ) (setq i (1+ i)))
21781 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21782 (t (throw 'exit t)))))
21785 (defun org-remove-tabs (s &optional width)
21786 "Replace tabulators in S with spaces.
21787 Assumes that s is a single line, starting in column 0."
21788 (setq width (or width tab-width))
21789 (while (string-match "\t" s)
21790 (setq s (replace-match
21791 (make-string
21792 (- (* width (/ (+ (match-beginning 0) width) width))
21793 (match-beginning 0)) ?\ )
21794 t t s)))
21797 (defun org-fix-indentation (line ind)
21798 "Fix indentation in LINE.
21799 IND is a cons cell with target and minimum indentation.
21800 If the current indentation in LINE is smaller than the minimum,
21801 leave it alone. If it is larger than ind, set it to the target."
21802 (let* ((l (org-remove-tabs line))
21803 (i (org-get-indentation l))
21804 (i1 (car ind)) (i2 (cdr ind)))
21805 (when (>= i i2) (setq l (substring line i2)))
21806 (if (> i1 0)
21807 (concat (make-string i1 ?\ ) l)
21808 l)))
21810 (defun org-remove-indentation (code &optional n)
21811 "Remove maximum common indentation in string CODE and return it.
21812 N may optionally be the number of columns to remove. Return CODE
21813 as-is if removal failed."
21814 (with-temp-buffer
21815 (insert code)
21816 (if (org-do-remove-indentation n) (buffer-string) code)))
21818 (defun org-do-remove-indentation (&optional n)
21819 "Remove the maximum common indentation from the buffer.
21820 When optional argument N is a positive integer, remove exactly
21821 that much characters from indentation, if possible. Return nil
21822 if it fails."
21823 (catch :exit
21824 (goto-char (point-min))
21825 ;; Find maximum common indentation, if not specified.
21826 (let ((n (or n
21827 (let ((min-ind (point-max)))
21828 (save-excursion
21829 (while (re-search-forward "^[ \t]*\\S-" nil t)
21830 (let ((ind (1- (current-column))))
21831 (if (zerop ind) (throw :exit nil)
21832 (setq min-ind (min min-ind ind))))))
21833 min-ind))))
21834 (if (zerop n) (throw :exit nil)
21835 ;; Remove exactly N indentation, but give up if not possible.
21836 (while (not (eobp))
21837 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21838 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21839 ((< ind n) (throw :exit nil))
21840 (t (indent-line-to (- ind n))))
21841 (forward-line)))
21842 ;; Signal success.
21843 t))))
21845 (defun org-fill-template (template alist)
21846 "Find each %key of ALIST in TEMPLATE and replace it."
21847 (let ((case-fold-search nil))
21848 (dolist (entry (sort (copy-sequence alist)
21849 (lambda (a b) (< (length (car a)) (length (car b))))))
21850 (setq template
21851 (replace-regexp-in-string
21852 (concat "%" (regexp-quote (car entry)))
21853 (or (cdr entry) "") template t t)))
21854 template))
21856 (defun org-base-buffer (buffer)
21857 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21858 (if (not buffer)
21859 buffer
21860 (or (buffer-base-buffer buffer)
21861 buffer)))
21863 (defun org-wrap (string &optional width lines)
21864 "Wrap string to either a number of lines, or a width in characters.
21865 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21866 that costs. If there is a word longer than WIDTH, the text is actually
21867 wrapped to the length of that word.
21868 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21869 many lines, whatever width that takes.
21870 The return value is a list of lines, without newlines at the end."
21871 (let* ((words (split-string string))
21872 (maxword (apply 'max (mapcar 'org-string-width words)))
21873 w ll)
21874 (cond (width
21875 (org-do-wrap words (max maxword width)))
21876 (lines
21877 (setq w maxword)
21878 (setq ll (org-do-wrap words maxword))
21879 (if (<= (length ll) lines)
21881 (setq ll words)
21882 (while (> (length ll) lines)
21883 (setq w (1+ w))
21884 (setq ll (org-do-wrap words w)))
21885 ll))
21886 (t (error "Cannot wrap this")))))
21888 (defun org-do-wrap (words width)
21889 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21890 (let (lines line)
21891 (while words
21892 (setq line (pop words))
21893 (while (and words (< (+ (length line) (length (car words))) width))
21894 (setq line (concat line " " (pop words))))
21895 (setq lines (push line lines)))
21896 (nreverse lines)))
21898 (defun org-quote-vert (s)
21899 "Replace \"|\" with \"\\vert\"."
21900 (while (string-match "|" s)
21901 (setq s (replace-match "\\vert" t t s)))
21904 (defun org-uuidgen-p (s)
21905 "Is S an ID created by UUIDGEN?"
21906 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21908 (defun org-in-src-block-p (&optional inside)
21909 "Whether point is in a code source block.
21910 When INSIDE is non-nil, don't consider we are within a src block
21911 when point is at #+BEGIN_SRC or #+END_SRC."
21912 (let ((case-fold-search t))
21913 (or (and (eq (get-char-property (point) 'src-block) t))
21914 (and (not inside)
21915 (save-match-data
21916 (save-excursion
21917 (beginning-of-line)
21918 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21920 (defun org-context ()
21921 "Return a list of contexts of the current cursor position.
21922 If several contexts apply, all are returned.
21923 Each context entry is a list with a symbol naming the context, and
21924 two positions indicating start and end of the context. Possible
21925 contexts are:
21927 :headline anywhere in a headline
21928 :headline-stars on the leading stars in a headline
21929 :todo-keyword on a TODO keyword (including DONE) in a headline
21930 :tags on the TAGS in a headline
21931 :priority on the priority cookie in a headline
21932 :item on the first line of a plain list item
21933 :item-bullet on the bullet/number of a plain list item
21934 :checkbox on the checkbox in a plain list item
21935 :table in an Org table
21936 :table-special on a special filed in a table
21937 :table-table in a table.el table
21938 :clocktable in a clocktable
21939 :src-block in a source block
21940 :link on a hyperlink
21941 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21942 :target on a <<target>>
21943 :radio-target on a <<<radio-target>>>
21944 :latex-fragment on a LaTeX fragment
21945 :latex-preview on a LaTeX fragment with overlaid preview image
21947 This function expects the position to be visible because it uses font-lock
21948 faces as a help to recognize the following contexts: :table-special, :link,
21949 and :keyword."
21950 (let* ((f (get-text-property (point) 'face))
21951 (faces (if (listp f) f (list f)))
21952 (case-fold-search t)
21953 (p (point)) clist o)
21954 ;; First the large context
21955 (cond
21956 ((org-at-heading-p t)
21957 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21958 (when (progn
21959 (beginning-of-line 1)
21960 (looking-at org-todo-line-tags-regexp))
21961 (push (org-point-in-group p 1 :headline-stars) clist)
21962 (push (org-point-in-group p 2 :todo-keyword) clist)
21963 (push (org-point-in-group p 4 :tags) clist))
21964 (goto-char p)
21965 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21966 (when (looking-at "\\[#[A-Z0-9]\\]")
21967 (push (org-point-in-group p 0 :priority) clist)))
21969 ((org-at-item-p)
21970 (push (org-point-in-group p 2 :item-bullet) clist)
21971 (push (list :item (point-at-bol)
21972 (save-excursion (org-end-of-item) (point)))
21973 clist)
21974 (and (org-at-item-checkbox-p)
21975 (push (org-point-in-group p 0 :checkbox) clist)))
21977 ((org-at-table-p)
21978 (push (list :table (org-table-begin) (org-table-end)) clist)
21979 (when (memq 'org-formula faces)
21980 (push (list :table-special
21981 (previous-single-property-change p 'face)
21982 (next-single-property-change p 'face)) clist)))
21983 ((org-at-table-p 'any)
21984 (push (list :table-table) clist)))
21985 (goto-char p)
21987 (let ((case-fold-search t))
21988 ;; New the "medium" contexts: clocktables, source blocks
21989 (cond ((org-in-clocktable-p)
21990 (push (list :clocktable
21991 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21992 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21993 (match-beginning 1))
21994 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21995 (match-end 0))) clist))
21996 ((org-in-src-block-p)
21997 (push (list :src-block
21998 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21999 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22000 (match-beginning 1))
22001 (and (search-forward "#+END_SRC" nil t)
22002 (match-beginning 0))) clist))))
22003 (goto-char p)
22005 ;; Now the small context
22006 (cond
22007 ((org-at-timestamp-p)
22008 (push (org-point-in-group p 0 :timestamp) clist))
22009 ((memq 'org-link faces)
22010 (push (list :link
22011 (previous-single-property-change p 'face)
22012 (next-single-property-change p 'face)) clist))
22013 ((memq 'org-special-keyword faces)
22014 (push (list :keyword
22015 (previous-single-property-change p 'face)
22016 (next-single-property-change p 'face)) clist))
22017 ((org-at-target-p)
22018 (push (org-point-in-group p 0 :target) clist)
22019 (goto-char (1- (match-beginning 0)))
22020 (when (looking-at org-radio-target-regexp)
22021 (push (org-point-in-group p 0 :radio-target) clist))
22022 (goto-char p))
22023 ((setq o (cl-some
22024 (lambda (o)
22025 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22027 (overlays-at (point))))
22028 (push (list :latex-fragment
22029 (overlay-start o) (overlay-end o)) clist)
22030 (push (list :latex-preview
22031 (overlay-start o) (overlay-end o)) clist))
22032 ((org-inside-LaTeX-fragment-p)
22033 ;; FIXME: positions wrong.
22034 (push (list :latex-fragment (point) (point)) clist)))
22036 (setq clist (nreverse (delq nil clist)))
22037 clist))
22039 (defun org-in-regexp (regexp &optional nlines visually)
22040 "Check if point is inside a match of REGEXP.
22042 Normally only the current line is checked, but you can include
22043 NLINES extra lines around point into the search. If VISUALLY is
22044 set, require that the cursor is not after the match but really
22045 on, so that the block visually is on the match.
22047 Return nil or a cons cell (BEG . END) where BEG and END are,
22048 respectively, the positions at the beginning and the end of the
22049 match."
22050 (catch :exit
22051 (let ((pos (point))
22052 (eol (line-end-position (if nlines (1+ nlines) 1))))
22053 (save-excursion
22054 (beginning-of-line (- 1 (or nlines 0)))
22055 (while (and (re-search-forward regexp eol t)
22056 (<= (match-beginning 0) pos))
22057 (let ((end (match-end 0)))
22058 (when (or (> end pos) (and (= end pos) (not visually)))
22059 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22061 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22062 "Non-nil when point is between matches of START-RE and END-RE.
22064 Also return a non-nil value when point is on one of the matches.
22066 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22067 buffer positions. Default values are the positions of headlines
22068 surrounding the point.
22070 The functions returns a cons cell whose car (resp. cdr) is the
22071 position before START-RE (resp. after END-RE)."
22072 (save-match-data
22073 (let ((pos (point))
22074 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22075 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22076 beg end)
22077 (save-excursion
22078 ;; Point is on a block when on START-RE or if START-RE can be
22079 ;; found before it...
22080 (and (or (org-in-regexp start-re)
22081 (re-search-backward start-re limit-up t))
22082 (setq beg (match-beginning 0))
22083 ;; ... and END-RE after it...
22084 (goto-char (match-end 0))
22085 (re-search-forward end-re limit-down t)
22086 (> (setq end (match-end 0)) pos)
22087 ;; ... without another START-RE in-between.
22088 (goto-char (match-beginning 0))
22089 (not (re-search-backward start-re (1+ beg) t))
22090 ;; Return value.
22091 (cons beg end))))))
22093 (defun org-in-block-p (names)
22094 "Non-nil when point belongs to a block whose name belongs to NAMES.
22096 NAMES is a list of strings containing names of blocks.
22098 Return first block name matched, or nil. Beware that in case of
22099 nested blocks, the returned name may not belong to the closest
22100 block from point."
22101 (save-match-data
22102 (catch 'exit
22103 (let ((case-fold-search t)
22104 (lim-up (save-excursion (outline-previous-heading)))
22105 (lim-down (save-excursion (outline-next-heading))))
22106 (dolist (name names)
22107 (let ((n (regexp-quote name)))
22108 (when (org-between-regexps-p
22109 (concat "^[ \t]*#\\+begin_" n)
22110 (concat "^[ \t]*#\\+end_" n)
22111 lim-up lim-down)
22112 (throw 'exit n)))))
22113 nil)))
22115 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22116 "Call `multi-occur' with buffers for all agenda files."
22117 (interactive "sOrg-files matching: ")
22118 (let* ((files (org-agenda-files))
22119 (tnames (mapcar #'file-truename files))
22120 (extra org-agenda-text-search-extra-files))
22121 (when (eq (car extra) 'agenda-archives)
22122 (setq extra (cdr extra))
22123 (setq files (org-add-archive-files files)))
22124 (dolist (f extra)
22125 (unless (member (file-truename f) tnames)
22126 (unless (member f files) (setq files (append files (list f))))
22127 (setq tnames (append tnames (list (file-truename f))))))
22128 (multi-occur
22129 (mapcar (lambda (x)
22130 (with-current-buffer
22131 ;; FIXME: Why not just (find-file-noselect x)?
22132 ;; Is it to avoid the "revert buffer" prompt?
22133 (or (get-file-buffer x) (find-file-noselect x))
22134 (widen)
22135 (current-buffer)))
22136 files)
22137 regexp)))
22139 (add-hook 'occur-mode-find-occurrence-hook
22140 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22142 (defun org-occur-link-in-agenda-files ()
22143 "Create a link and search for it in the agendas.
22144 The link is not stored in `org-stored-links', it is just created
22145 for the search purpose."
22146 (interactive)
22147 (let ((link (condition-case nil
22148 (org-store-link nil)
22149 (error "Unable to create a link to here"))))
22150 (org-occur-in-agenda-files (regexp-quote link))))
22152 (defun org-reverse-string (string)
22153 "Return the reverse of STRING."
22154 (apply 'string (reverse (string-to-list string))))
22156 ;; defsubst org-uniquify must be defined before first use
22158 (defun org-uniquify-alist (alist)
22159 "Merge elements of ALIST with the same key.
22161 For example, in this alist:
22163 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22164 => \\='((a 1 3) (b 2))
22166 merge (a 1) and (a 3) into (a 1 3).
22168 The function returns the new ALIST."
22169 (let (rtn)
22170 (dolist (e alist rtn)
22171 (let (n)
22172 (if (not (assoc (car e) rtn))
22173 (push e rtn)
22174 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22175 (setq rtn (assq-delete-all (car e) rtn))
22176 (push n rtn))))))
22178 (defun org-delete-all (elts list)
22179 "Remove all elements in ELTS from LIST.
22180 Comparison is done with `equal'. It is a destructive operation
22181 that may remove elements by altering the list structure."
22182 (while elts
22183 (setq list (delete (pop elts) list)))
22184 list)
22186 (defun org-back-over-empty-lines ()
22187 "Move backwards over whitespace, to the beginning of the first empty line.
22188 Returns the number of empty lines passed."
22189 (let ((pos (point)))
22190 (if (cdr (assq 'heading org-blank-before-new-entry))
22191 (skip-chars-backward " \t\n\r")
22192 (unless (eobp)
22193 (forward-line -1)))
22194 (beginning-of-line 2)
22195 (goto-char (min (point) pos))
22196 (count-lines (point) pos)))
22198 (defun org-skip-whitespace ()
22199 (skip-chars-forward " \t\n\r"))
22201 (defun org-point-in-group (point group &optional context)
22202 "Check if POINT is in match-group GROUP.
22203 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22204 match. If the match group does not exist or point is not inside it,
22205 return nil."
22206 (and (match-beginning group)
22207 (>= point (match-beginning group))
22208 (<= point (match-end group))
22209 (if context
22210 (list context (match-beginning group) (match-end group))
22211 t)))
22213 (defun org-switch-to-buffer-other-window (&rest args)
22214 "Switch to buffer in a second window on the current frame.
22215 In particular, do not allow pop-up frames.
22216 Returns the newly created buffer."
22217 (org-no-popups
22218 (apply 'switch-to-buffer-other-window args)))
22220 (defun org-combine-plists (&rest plists)
22221 "Create a single property list from all plists in PLISTS.
22222 The process starts by copying the first list, and then setting properties
22223 from the other lists. Settings in the last list are the most significant
22224 ones and overrule settings in the other lists."
22225 (let ((rtn (copy-sequence (pop plists)))
22226 p v ls)
22227 (while plists
22228 (setq ls (pop plists))
22229 (while ls
22230 (setq p (pop ls) v (pop ls))
22231 (setq rtn (plist-put rtn p v))))
22232 rtn))
22234 (defun org-replace-escapes (string table)
22235 "Replace %-escapes in STRING with values in TABLE.
22236 TABLE is an association list with keys like \"%a\" and string values.
22237 The sequences in STRING may contain normal field width and padding information,
22238 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22239 so values can contain further %-escapes if they are define later in TABLE."
22240 (let ((tbl (copy-alist table))
22241 (case-fold-search nil)
22242 (pchg 0)
22243 re rpl)
22244 (dolist (e tbl)
22245 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22246 (when (and (cdr e) (string-match re (cdr e)))
22247 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22248 (safe "SREF"))
22249 (add-text-properties 0 3 (list 'sref sref) safe)
22250 (setcdr e (replace-match safe t t (cdr e)))))
22251 (while (string-match re string)
22252 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22253 (cdr e)))
22254 (setq string (replace-match rpl t t string))))
22255 (while (setq pchg (next-property-change pchg string))
22256 (let ((sref (get-text-property pchg 'sref string)))
22257 (when (and sref (string-match "SREF" string pchg))
22258 (setq string (replace-match sref t t string)))))
22259 string))
22261 (defun org-find-base-buffer-visiting (file)
22262 "Like `find-buffer-visiting' but always return the base buffer and
22263 not an indirect buffer."
22264 (let ((buf (or (get-file-buffer file)
22265 (find-buffer-visiting file))))
22266 (if buf
22267 (or (buffer-base-buffer buf) buf)
22268 nil)))
22270 ;;; TODO: Only called once, from ox-odt which should probably use
22271 ;;; org-export-inline-image-p or something.
22272 (defun org-file-image-p (file)
22273 "Return non-nil if FILE is an image."
22274 (save-match-data
22275 (string-match (image-file-name-regexp) file)))
22277 (defun org-get-cursor-date (&optional with-time)
22278 "Return the date at cursor in as a time.
22279 This works in the calendar and in the agenda, anywhere else it just
22280 returns the current time.
22281 If WITH-TIME is non-nil, returns the time of the event at point (in
22282 the agenda) or the current time of the day."
22283 (let (date day defd tp hod mod)
22284 (when with-time
22285 (setq tp (get-text-property (point) 'time))
22286 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22287 (setq hod (string-to-number (match-string 1 tp))
22288 mod (string-to-number (match-string 2 tp))))
22289 (or tp (let ((now (decode-time)))
22290 (setq hod (nth 2 now)
22291 mod (nth 1 now)))))
22292 (cond
22293 ((eq major-mode 'calendar-mode)
22294 (setq date (calendar-cursor-to-date)
22295 defd (encode-time 0 (or mod 0) (or hod 0)
22296 (nth 1 date) (nth 0 date) (nth 2 date))))
22297 ((eq major-mode 'org-agenda-mode)
22298 (setq day (get-text-property (point) 'day))
22299 (when day
22300 (setq date (calendar-gregorian-from-absolute day)
22301 defd (encode-time 0 (or mod 0) (or hod 0)
22302 (nth 1 date) (nth 0 date) (nth 2 date))))))
22303 (or defd (current-time))))
22305 (defun org-mark-subtree (&optional up)
22306 "Mark the current subtree.
22307 This puts point at the start of the current subtree, and mark at
22308 the end. If a numeric prefix UP is given, move up into the
22309 hierarchy of headlines by UP levels before marking the subtree."
22310 (interactive "P")
22311 (org-with-limited-levels
22312 (cond ((org-at-heading-p) (beginning-of-line))
22313 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22314 (t (outline-previous-visible-heading 1))))
22315 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22316 (if (called-interactively-p 'any)
22317 (call-interactively 'org-mark-element)
22318 (org-mark-element)))
22320 (defun org-file-newer-than-p (file time)
22321 "Non-nil if FILE is newer than TIME.
22322 FILE is a filename, as a string, TIME is a list of integers, as
22323 returned by, e.g., `current-time'."
22324 (and (file-exists-p file)
22325 ;; Only compare times up to whole seconds as some file-systems
22326 ;; (e.g. HFS+) do not retain any finer granularity. As
22327 ;; a consequence, make sure we return non-nil when the two
22328 ;; times are equal.
22329 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22330 (cl-subseq time 0 2)))))
22332 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22333 "Compile a SOURCE file using PROCESS.
22335 PROCESS is either a function or a list of shell commands, as
22336 strings. EXT is a file extension, without the leading dot, as
22337 a string. It is used to check if the process actually succeeded.
22339 PROCESS must create a file with the same base name and directory
22340 as SOURCE, but ending with EXT. The function then returns its
22341 filename. Otherwise, it raises an error. The error message can
22342 then be refined by providing string ERR-MSG, which is appended to
22343 the standard message.
22345 If PROCESS is a function, it is called with a single argument:
22346 the SOURCE file.
22348 If it is a list of commands, each of them is called using
22349 `shell-command'. By default, in each command, %b, %f, %F, %o and
22350 %O are replaced with, respectively, SOURCE base name, name, full
22351 name, directory and absolute output file name. It is possible,
22352 however, to use more place-holders by specifying them in optional
22353 argument SPEC, as an alist following the pattern
22355 (CHARACTER . REPLACEMENT-STRING).
22357 When PROCESS is a list of commands, optional argument LOG-BUF can
22358 be set to a buffer or a buffer name. `shell-command' then uses
22359 it for output."
22360 (let* ((base-name (file-name-base source))
22361 (full-name (file-truename source))
22362 (out-dir (or (file-name-directory source) "./"))
22363 (output (expand-file-name (concat base-name "." ext) out-dir))
22364 (time (current-time))
22365 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22366 (save-window-excursion
22367 (pcase process
22368 ((pred functionp) (funcall process (shell-quote-argument source)))
22369 ((pred consp)
22370 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22371 (spec (append spec
22372 `((?b . ,(shell-quote-argument base-name))
22373 (?f . ,(shell-quote-argument source))
22374 (?F . ,(shell-quote-argument full-name))
22375 (?o . ,(shell-quote-argument out-dir))
22376 (?O . ,(shell-quote-argument output))))))
22377 (dolist (command process)
22378 (shell-command (format-spec command spec) log-buf))
22379 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22380 (_ (error "No valid command to process %S%s" source err-msg))))
22381 ;; Check for process failure. Output file is expected to be
22382 ;; located in the same directory as SOURCE.
22383 (unless (org-file-newer-than-p output time)
22384 (error (format "File %S wasn't produced%s" output err-msg)))
22385 output))
22387 ;;; Indentation
22389 (defvar org-element-greater-elements)
22390 (defun org--get-expected-indentation (element contentsp)
22391 "Expected indentation column for current line, according to ELEMENT.
22392 ELEMENT is an element containing point. CONTENTSP is non-nil
22393 when indentation is to be computed according to contents of
22394 ELEMENT."
22395 (let ((type (org-element-type element))
22396 (start (org-element-property :begin element))
22397 (post-affiliated (org-element-property :post-affiliated element)))
22398 (org-with-wide-buffer
22399 (cond
22400 (contentsp
22401 (cl-case type
22402 ((diary-sexp footnote-definition) 0)
22403 ((headline inlinetask nil)
22404 (if (not org-adapt-indentation) 0
22405 (let ((level (org-current-level)))
22406 (if level (1+ level) 0))))
22407 ((item plain-list) (org-list-item-body-column post-affiliated))
22409 (goto-char start)
22410 (org-get-indentation))))
22411 ((memq type '(headline inlinetask nil))
22412 (if (org-match-line "[ \t]*$")
22413 (org--get-expected-indentation element t)
22415 ((memq type '(diary-sexp footnote-definition)) 0)
22416 ;; First paragraph of a footnote definition or an item.
22417 ;; Indent like parent.
22418 ((< (line-beginning-position) start)
22419 (org--get-expected-indentation
22420 (org-element-property :parent element) t))
22421 ;; At first line: indent according to previous sibling, if any,
22422 ;; ignoring footnote definitions and inline tasks, or parent's
22423 ;; contents.
22424 ((= (line-beginning-position) start)
22425 (catch 'exit
22426 (while t
22427 (if (= (point-min) start) (throw 'exit 0)
22428 (goto-char (1- start))
22429 (let* ((previous (org-element-at-point))
22430 (parent previous))
22431 (while (and parent (<= (org-element-property :end parent) start))
22432 (setq previous parent
22433 parent (org-element-property :parent parent)))
22434 (cond
22435 ((not previous) (throw 'exit 0))
22436 ((> (org-element-property :end previous) start)
22437 (throw 'exit (org--get-expected-indentation previous t)))
22438 ((memq (org-element-type previous)
22439 '(footnote-definition inlinetask))
22440 (setq start (org-element-property :begin previous)))
22441 (t (goto-char (org-element-property :begin previous))
22442 (throw 'exit
22443 (if (bolp) (org-get-indentation)
22444 ;; At first paragraph in an item or
22445 ;; a footnote definition.
22446 (org--get-expected-indentation
22447 (org-element-property :parent previous) t))))))))))
22448 ;; Otherwise, move to the first non-blank line above.
22450 (beginning-of-line)
22451 (let ((pos (point)))
22452 (skip-chars-backward " \r\t\n")
22453 (cond
22454 ;; Two blank lines end a footnote definition or a plain
22455 ;; list. When we indent an empty line after them, the
22456 ;; containing list or footnote definition is over, so it
22457 ;; qualifies as a previous sibling. Therefore, we indent
22458 ;; like its first line.
22459 ((and (memq type '(footnote-definition plain-list))
22460 (> (count-lines (point) pos) 2))
22461 (goto-char start)
22462 (org-get-indentation))
22463 ;; Line above is the first one of a paragraph at the
22464 ;; beginning of an item or a footnote definition. Indent
22465 ;; like parent.
22466 ((< (line-beginning-position) start)
22467 (org--get-expected-indentation
22468 (org-element-property :parent element) t))
22469 ;; Line above is the beginning of an element, i.e., point
22470 ;; was originally on the blank lines between element's start
22471 ;; and contents.
22472 ((= (line-beginning-position) post-affiliated)
22473 (org--get-expected-indentation element t))
22474 ;; POS is after contents in a greater element. Indent like
22475 ;; the beginning of the element.
22476 ((and (memq type org-element-greater-elements)
22477 (let ((cend (org-element-property :contents-end element)))
22478 (and cend (<= cend pos))))
22479 ;; As a special case, if point is at the end of a footnote
22480 ;; definition or an item, indent like the very last element
22481 ;; within. If that last element is an item, indent like
22482 ;; its contents.
22483 (if (memq type '(footnote-definition item plain-list))
22484 (let ((last (org-element-at-point)))
22485 (goto-char pos)
22486 (org--get-expected-indentation
22487 last (eq (org-element-type last) 'item)))
22488 (goto-char start)
22489 (org-get-indentation)))
22490 ;; In any other case, indent like the current line.
22491 (t (org-get-indentation)))))))))
22493 (defun org--align-node-property ()
22494 "Align node property at point.
22495 Alignment is done according to `org-property-format', which see."
22496 (when (save-excursion
22497 (beginning-of-line)
22498 (looking-at org-property-re))
22499 (replace-match
22500 (concat (match-string 4)
22501 (org-trim
22502 (format org-property-format (match-string 1) (match-string 3))))
22503 t t)))
22505 (defun org-indent-line ()
22506 "Indent line depending on context.
22508 Indentation is done according to the following rules:
22510 - Footnote definitions, diary sexps, headlines and inline tasks
22511 have to start at column 0.
22513 - On the very first line of an element, consider, in order, the
22514 next rules until one matches:
22516 1. If there's a sibling element before, ignoring footnote
22517 definitions and inline tasks, indent like its first line.
22519 2. If element has a parent, indent like its contents. More
22520 precisely, if parent is an item, indent after the
22521 description part, if any, or the bullet (see
22522 `org-list-description-max-indent'). Else, indent like
22523 parent's first line.
22525 3. Otherwise, indent relatively to current level, if
22526 `org-adapt-indentation' is non-nil, or to left margin.
22528 - On a blank line at the end of an element, indent according to
22529 the type of the element. More precisely
22531 1. If element is a plain list, an item, or a footnote
22532 definition, indent like the very last element within.
22534 2. If element is a paragraph, indent like its last non blank
22535 line.
22537 3. Otherwise, indent like its very first line.
22539 - In the code part of a source block, use language major mode
22540 to indent current line if `org-src-tab-acts-natively' is
22541 non-nil. If it is nil, do nothing.
22543 - Otherwise, indent like the first non-blank line above.
22545 The function doesn't indent an item as it could break the whole
22546 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22547 `\\[org-shiftmetaright]'.
22549 Also align node properties according to `org-property-format'."
22550 (interactive)
22551 (cond
22552 (orgstruct-is-++
22553 (let ((indent-line-function
22554 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22555 (indent-according-to-mode)))
22556 ((org-at-heading-p) 'noindent)
22558 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22559 (type (org-element-type element)))
22560 (cond ((and (memq type '(plain-list item))
22561 (= (line-beginning-position)
22562 (org-element-property :post-affiliated element)))
22563 'noindent)
22564 ((and (eq type 'latex-environment)
22565 (>= (point) (org-element-property :post-affiliated element))
22566 (< (point) (org-with-wide-buffer
22567 (goto-char (org-element-property :end element))
22568 (skip-chars-backward " \r\t\n")
22569 (line-beginning-position 2))))
22570 'noindent)
22571 ((and (eq type 'src-block)
22572 org-src-tab-acts-natively
22573 (> (line-beginning-position)
22574 (org-element-property :post-affiliated element))
22575 (< (line-beginning-position)
22576 (org-with-wide-buffer
22577 (goto-char (org-element-property :end element))
22578 (skip-chars-backward " \r\t\n")
22579 (line-beginning-position))))
22580 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22582 (let ((column (org--get-expected-indentation element nil)))
22583 ;; Preserve current column.
22584 (if (<= (current-column) (current-indentation))
22585 (indent-line-to column)
22586 (save-excursion (indent-line-to column))))
22587 ;; Align node property. Also preserve current column.
22588 (when (eq type 'node-property)
22589 (let ((column (current-column)))
22590 (org--align-node-property)
22591 (org-move-to-column column)))))))))
22593 (defun org-indent-region (start end)
22594 "Indent each non-blank line in the region.
22595 Called from a program, START and END specify the region to
22596 indent. The function will not indent contents of example blocks,
22597 verse blocks and export blocks as leading white spaces are
22598 assumed to be significant there."
22599 (interactive "r")
22600 (save-excursion
22601 (goto-char start)
22602 (skip-chars-forward " \r\t\n")
22603 (unless (eobp) (beginning-of-line))
22604 (let ((indent-to
22605 (lambda (ind pos)
22606 ;; Set IND as indentation for all lines between point and
22607 ;; POS. Blank lines are ignored. Leave point after POS
22608 ;; once done.
22609 (let ((limit (copy-marker pos)))
22610 (while (< (point) limit)
22611 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22612 (forward-line))
22613 (set-marker limit nil))))
22614 (end (copy-marker end)))
22615 (while (< (point) end)
22616 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22617 (let* ((element (org-element-at-point))
22618 (type (org-element-type element))
22619 (element-end (copy-marker (org-element-property :end element)))
22620 (ind (org--get-expected-indentation element nil)))
22621 (cond
22622 ;; Element indented as a single block. Example blocks
22623 ;; preserving indentation are a special case since the
22624 ;; "contents" must not be indented whereas the block
22625 ;; boundaries can.
22626 ((or (memq type '(export-block latex-environment))
22627 (and (eq type 'example-block)
22628 (not
22629 (or org-src-preserve-indentation
22630 (org-element-property :preserve-indent element)))))
22631 (let ((offset (- ind (org-get-indentation))))
22632 (unless (zerop offset)
22633 (indent-rigidly (org-element-property :begin element)
22634 (org-element-property :end element)
22635 offset)))
22636 (goto-char element-end))
22637 ;; Elements indented line wise. Be sure to exclude
22638 ;; example blocks (preserving indentation) and source
22639 ;; blocks from this category as they are treated
22640 ;; specially later.
22641 ((or (memq type '(paragraph table table-row))
22642 (not (or (org-element-property :contents-begin element)
22643 (memq type '(example-block src-block)))))
22644 (when (eq type 'node-property)
22645 (org--align-node-property)
22646 (beginning-of-line))
22647 (funcall indent-to ind (min element-end end)))
22648 ;; Elements consisting of three parts: before the
22649 ;; contents, the contents, and after the contents. The
22650 ;; contents are treated specially, according to the
22651 ;; element type, or not indented at all. Other parts are
22652 ;; indented as a single block.
22654 (let* ((post (copy-marker
22655 (org-element-property :post-affiliated element)))
22656 (cbeg
22657 (copy-marker
22658 (cond
22659 ((not (org-element-property :contents-begin element))
22660 ;; Fake contents for source blocks.
22661 (org-with-wide-buffer
22662 (goto-char post)
22663 (line-beginning-position 2)))
22664 ((memq type '(footnote-definition item plain-list))
22665 ;; Contents in these elements could start on
22666 ;; the same line as the beginning of the
22667 ;; element. Make sure we start indenting
22668 ;; from the second line.
22669 (org-with-wide-buffer
22670 (goto-char post)
22671 (end-of-line)
22672 (skip-chars-forward " \r\t\n")
22673 (if (eobp) (point) (line-beginning-position))))
22674 (t (org-element-property :contents-begin element)))))
22675 (cend (copy-marker
22676 (or (org-element-property :contents-end element)
22677 ;; Fake contents for source blocks.
22678 (org-with-wide-buffer
22679 (goto-char element-end)
22680 (skip-chars-backward " \r\t\n")
22681 (line-beginning-position)))
22682 t)))
22683 ;; Do not change items indentation individually as it
22684 ;; might break the list as a whole. On the other
22685 ;; hand, when at a plain list, indent it as a whole.
22686 (cond ((eq type 'plain-list)
22687 (let ((offset (- ind (org-get-indentation))))
22688 (unless (zerop offset)
22689 (indent-rigidly (org-element-property :begin element)
22690 (org-element-property :end element)
22691 offset))
22692 (goto-char cbeg)))
22693 ((eq type 'item) (goto-char cbeg))
22694 (t (funcall indent-to ind (min cbeg end))))
22695 (when (< (point) end)
22696 (cl-case type
22697 ((example-block verse-block))
22698 (src-block
22699 ;; In a source block, indent source code
22700 ;; according to language major mode, but only if
22701 ;; `org-src-tab-acts-natively' is non-nil.
22702 (when (and (< (point) end) org-src-tab-acts-natively)
22703 (ignore-errors
22704 (org-babel-do-in-edit-buffer
22705 (indent-region (point-min) (point-max))))))
22706 (t (org-indent-region (point) (min cend end))))
22707 (goto-char (min cend end))
22708 (when (< (point) end)
22709 (funcall indent-to ind (min element-end end))))
22710 (set-marker post nil)
22711 (set-marker cbeg nil)
22712 (set-marker cend nil))))
22713 (set-marker element-end nil))))
22714 (set-marker end nil))))
22716 (defun org-indent-drawer ()
22717 "Indent the drawer at point."
22718 (interactive)
22719 (unless (save-excursion
22720 (beginning-of-line)
22721 (looking-at-p org-drawer-regexp))
22722 (user-error "Not at a drawer"))
22723 (let ((element (org-element-at-point)))
22724 (unless (memq (org-element-type element) '(drawer property-drawer))
22725 (user-error "Not at a drawer"))
22726 (org-with-wide-buffer
22727 (org-indent-region (org-element-property :begin element)
22728 (org-element-property :end element))))
22729 (message "Drawer at point indented"))
22731 (defun org-indent-block ()
22732 "Indent the block at point."
22733 (interactive)
22734 (unless (save-excursion
22735 (beginning-of-line)
22736 (let ((case-fold-search t))
22737 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22738 (user-error "Not at a block"))
22739 (let ((element (org-element-at-point)))
22740 (unless (memq (org-element-type element)
22741 '(comment-block center-block dynamic-block example-block
22742 export-block quote-block special-block
22743 src-block verse-block))
22744 (user-error "Not at a block"))
22745 (org-with-wide-buffer
22746 (org-indent-region (org-element-property :begin element)
22747 (org-element-property :end element))))
22748 (message "Block at point indented"))
22751 ;;; Filling
22753 ;; We use our own fill-paragraph and auto-fill functions.
22755 ;; `org-fill-paragraph' relies on adaptive filling and context
22756 ;; checking. Appropriate `fill-prefix' is computed with
22757 ;; `org-adaptive-fill-function'.
22759 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22760 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22761 ;; `org-adaptive-fill-function' value. Internally,
22762 ;; `org-comment-line-break-function' breaks the line.
22764 ;; `org-setup-filling' installs filling and auto-filling related
22765 ;; variables during `org-mode' initialization.
22767 (defvar org-element-paragraph-separate) ; org-element.el
22768 (defun org-setup-filling ()
22769 (require 'org-element)
22770 ;; Prevent auto-fill from inserting unwanted new items.
22771 (when (boundp 'fill-nobreak-predicate)
22772 (setq-local
22773 fill-nobreak-predicate
22774 (org-uniquify
22775 (append fill-nobreak-predicate
22776 '(org-fill-line-break-nobreak-p
22777 org-fill-n-macro-as-item-nobreak-p
22778 org-fill-paragraph-with-timestamp-nobreak-p)))))
22779 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22780 (setq-local paragraph-start paragraph-ending)
22781 (setq-local paragraph-separate paragraph-ending))
22782 (setq-local fill-paragraph-function 'org-fill-paragraph)
22783 (setq-local auto-fill-inhibit-regexp nil)
22784 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22785 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22786 (setq-local comment-line-break-function 'org-comment-line-break-function))
22788 (defun org-fill-line-break-nobreak-p ()
22789 "Non-nil when a new line at point would create an Org line break."
22790 (save-excursion
22791 (skip-chars-backward "[ \t]")
22792 (skip-chars-backward "\\\\")
22793 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22795 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22796 "Non-nil when a new line at point would split a timestamp."
22797 (and (org-at-timestamp-p 'lax)
22798 (not (looking-at org-ts-regexp-both))))
22800 (defun org-fill-n-macro-as-item-nobreak-p ()
22801 "Non-nil when a new line at point would create a new list."
22802 ;; During export, a "n" macro followed by a dot or a closing
22803 ;; parenthesis can end up being parsed as a new list item.
22804 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22806 (declare-function message-in-body-p "message" ())
22807 (defvar orgtbl-line-start-regexp) ; From org-table.el
22808 (defun org-adaptive-fill-function ()
22809 "Compute a fill prefix for the current line.
22810 Return fill prefix, as a string, or nil if current line isn't
22811 meant to be filled. For convenience, if `adaptive-fill-regexp'
22812 matches in paragraphs or comments, use it."
22813 (catch 'exit
22814 (when (derived-mode-p 'message-mode)
22815 (save-excursion
22816 (beginning-of-line)
22817 (cond ((not (message-in-body-p)) (throw 'exit nil))
22818 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22819 ((looking-at message-cite-prefix-regexp)
22820 (throw 'exit (match-string-no-properties 0)))
22821 ((looking-at org-outline-regexp)
22822 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22823 (org-with-wide-buffer
22824 (unless (org-at-heading-p)
22825 (let* ((p (line-beginning-position))
22826 (element (save-excursion
22827 (beginning-of-line)
22828 (org-element-at-point)))
22829 (type (org-element-type element))
22830 (post-affiliated (org-element-property :post-affiliated element)))
22831 (unless (< p post-affiliated)
22832 (cl-case type
22833 (comment
22834 (save-excursion
22835 (beginning-of-line)
22836 (looking-at "[ \t]*")
22837 (concat (match-string 0) "# ")))
22838 (footnote-definition "")
22839 ((item plain-list)
22840 (make-string (org-list-item-body-column post-affiliated) ?\s))
22841 (paragraph
22842 ;; Fill prefix is usually the same as the current line,
22843 ;; unless the paragraph is at the beginning of an item.
22844 (let ((parent (org-element-property :parent element)))
22845 (save-excursion
22846 (beginning-of-line)
22847 (cond ((eq (org-element-type parent) 'item)
22848 (make-string (org-list-item-body-column
22849 (org-element-property :begin parent))
22850 ?\s))
22851 ((and adaptive-fill-regexp
22852 ;; Locally disable
22853 ;; `adaptive-fill-function' to let
22854 ;; `fill-context-prefix' handle
22855 ;; `adaptive-fill-regexp' variable.
22856 (let (adaptive-fill-function)
22857 (fill-context-prefix
22858 post-affiliated
22859 (org-element-property :end element)))))
22860 ((looking-at "[ \t]+") (match-string 0))
22861 (t "")))))
22862 (comment-block
22863 ;; Only fill contents if P is within block boundaries.
22864 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22865 (forward-line)
22866 (point)))
22867 (cend (save-excursion
22868 (goto-char (org-element-property :end element))
22869 (skip-chars-backward " \r\t\n")
22870 (line-beginning-position))))
22871 (when (and (>= p cbeg) (< p cend))
22872 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22873 (match-string 0)
22874 "")))))))))))
22876 (declare-function message-goto-body "message" ())
22877 (defvar message-cite-prefix-regexp) ; From message.el
22879 (defun org-fill-element (&optional justify)
22880 "Fill element at point, when applicable.
22882 This function only applies to comment blocks, comments, example
22883 blocks and paragraphs. Also, as a special case, re-align table
22884 when point is at one.
22886 If JUSTIFY is non-nil (interactively, with prefix argument),
22887 justify as well. If `sentence-end-double-space' is non-nil, then
22888 period followed by one space does not end a sentence, so don't
22889 break a line there. The variable `fill-column' controls the
22890 width for filling.
22892 For convenience, when point is at a plain list, an item or
22893 a footnote definition, try to fill the first paragraph within."
22894 (with-syntax-table org-mode-transpose-word-syntax-table
22895 ;; Move to end of line in order to get the first paragraph within
22896 ;; a plain list or a footnote definition.
22897 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22898 ;; First check if point is in a blank line at the beginning of
22899 ;; the buffer. In that case, ignore filling.
22900 (cl-case (org-element-type element)
22901 ;; Use major mode filling function is src blocks.
22902 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22903 ;; Align Org tables, leave table.el tables as-is.
22904 (table-row (org-table-align) t)
22905 (table
22906 (when (eq (org-element-property :type element) 'org)
22907 (save-excursion
22908 (goto-char (org-element-property :post-affiliated element))
22909 (org-table-align)))
22911 (paragraph
22912 ;; Paragraphs may contain `line-break' type objects.
22913 (let ((beg (max (point-min)
22914 (org-element-property :contents-begin element)))
22915 (end (min (point-max)
22916 (org-element-property :contents-end element))))
22917 ;; Do nothing if point is at an affiliated keyword.
22918 (if (< (line-end-position) beg) t
22919 (when (derived-mode-p 'message-mode)
22920 ;; In `message-mode', do not fill following citation
22921 ;; in current paragraph nor text before message body.
22922 (let ((body-start (save-excursion (message-goto-body))))
22923 (when body-start (setq beg (max body-start beg))))
22924 (when (save-excursion
22925 (re-search-forward
22926 (concat "^" message-cite-prefix-regexp) end t))
22927 (setq end (match-beginning 0))))
22928 ;; Fill paragraph, taking line breaks into account.
22929 (save-excursion
22930 (goto-char beg)
22931 (let ((cuts (list beg)))
22932 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22933 (when (eq 'line-break
22934 (org-element-type
22935 (save-excursion (backward-char)
22936 (org-element-context))))
22937 (push (point) cuts)))
22938 (dolist (c (delq end cuts))
22939 (fill-region-as-paragraph c end justify)
22940 (setq end c))))
22941 t)))
22942 ;; Contents of `comment-block' type elements should be
22943 ;; filled as plain text, but only if point is within block
22944 ;; markers.
22945 (comment-block
22946 (let* ((case-fold-search t)
22947 (beg (save-excursion
22948 (goto-char (org-element-property :begin element))
22949 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22950 (forward-line)
22951 (point)))
22952 (end (save-excursion
22953 (goto-char (org-element-property :end element))
22954 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22955 (line-beginning-position))))
22956 (if (or (< (point) beg) (> (point) end)) t
22957 (fill-region-as-paragraph
22958 (save-excursion (end-of-line)
22959 (re-search-backward "^[ \t]*$" beg 'move)
22960 (line-beginning-position))
22961 (save-excursion (beginning-of-line)
22962 (re-search-forward "^[ \t]*$" end 'move)
22963 (line-beginning-position))
22964 justify))))
22965 ;; Fill comments.
22966 (comment
22967 (let ((begin (org-element-property :post-affiliated element))
22968 (end (org-element-property :end element)))
22969 (when (and (>= (point) begin) (<= (point) end))
22970 (let ((begin (save-excursion
22971 (end-of-line)
22972 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22973 (progn (forward-line) (point))
22974 begin)))
22975 (end (save-excursion
22976 (end-of-line)
22977 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22978 (1- (line-beginning-position))
22979 (skip-chars-backward " \r\t\n")
22980 (line-end-position)))))
22981 ;; Do not fill comments when at a blank line.
22982 (when (> end begin)
22983 (let ((fill-prefix
22984 (save-excursion
22985 (beginning-of-line)
22986 (looking-at "[ \t]*#")
22987 (let ((comment-prefix (match-string 0)))
22988 (goto-char (match-end 0))
22989 (if (looking-at adaptive-fill-regexp)
22990 (concat comment-prefix (match-string 0))
22991 (concat comment-prefix " "))))))
22992 (save-excursion
22993 (fill-region-as-paragraph begin end justify))))))
22995 ;; Ignore every other element.
22996 (otherwise t)))))
22998 (defun org-fill-paragraph (&optional justify region)
22999 "Fill element at point, when applicable.
23001 This function only applies to comment blocks, comments, example
23002 blocks and paragraphs. Also, as a special case, re-align table
23003 when point is at one.
23005 For convenience, when point is at a plain list, an item or
23006 a footnote definition, try to fill the first paragraph within.
23008 If JUSTIFY is non-nil (interactively, with prefix argument),
23009 justify as well. If `sentence-end-double-space' is non-nil, then
23010 period followed by one space does not end a sentence, so don't
23011 break a line there. The variable `fill-column' controls the
23012 width for filling.
23014 The REGION argument is non-nil if called interactively; in that
23015 case, if Transient Mark mode is enabled and the mark is active,
23016 fill each of the elements in the active region, instead of just
23017 filling the current element."
23018 (interactive (progn
23019 (barf-if-buffer-read-only)
23020 (list (if current-prefix-arg 'full) t)))
23021 (cond
23022 ((and (derived-mode-p 'message-mode)
23023 (or (not (message-in-body-p))
23024 (save-excursion (move-beginning-of-line 1)
23025 (looking-at message-cite-prefix-regexp))))
23026 ;; First ensure filling is correct in message-mode.
23027 (let ((fill-paragraph-function
23028 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23029 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23030 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23031 (paragraph-separate
23032 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23033 (fill-paragraph nil)))
23034 ((and region transient-mark-mode mark-active
23035 (not (eq (region-beginning) (region-end))))
23036 (let ((origin (point-marker))
23037 (start (region-beginning)))
23038 (unwind-protect
23039 (progn
23040 (goto-char (region-end))
23041 (while (> (point) start)
23042 (org-backward-paragraph)
23043 (org-fill-element justify)))
23044 (goto-char origin)
23045 (set-marker origin nil))))
23046 (t (org-fill-element justify))))
23047 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23049 (defun org-auto-fill-function ()
23050 "Auto-fill function."
23051 ;; Check if auto-filling is meaningful.
23052 (let ((fc (current-fill-column)))
23053 (when (and fc (> (current-column) fc))
23054 (let* ((fill-prefix (org-adaptive-fill-function))
23055 ;; Enforce empty fill prefix, if required. Otherwise, it
23056 ;; will be computed again.
23057 (adaptive-fill-mode (not (equal fill-prefix ""))))
23058 (when fill-prefix (do-auto-fill))))))
23060 (defun org-comment-line-break-function (&optional soft)
23061 "Break line at point and indent, continuing comment if within one.
23062 The inserted newline is marked hard if variable
23063 `use-hard-newlines' is true, unless optional argument SOFT is
23064 non-nil."
23065 (if soft (insert-and-inherit ?\n) (newline 1))
23066 (save-excursion (forward-char -1) (delete-horizontal-space))
23067 (delete-horizontal-space)
23068 (indent-to-left-margin)
23069 (insert-before-markers-and-inherit fill-prefix))
23072 ;;; Fixed Width Areas
23074 (defun org-toggle-fixed-width ()
23075 "Toggle fixed-width markup.
23077 Add or remove fixed-width markup on current line, whenever it
23078 makes sense. Return an error otherwise.
23080 If a region is active and if it contains only fixed-width areas
23081 or blank lines, remove all fixed-width markup in it. If the
23082 region contains anything else, convert all non-fixed-width lines
23083 to fixed-width ones.
23085 Blank lines at the end of the region are ignored unless the
23086 region only contains such lines."
23087 (interactive)
23088 (if (not (org-region-active-p))
23089 ;; No region:
23091 ;; Remove fixed width marker only in a fixed-with element.
23093 ;; Add fixed width maker in paragraphs, in blank lines after
23094 ;; elements or at the beginning of a headline or an inlinetask,
23095 ;; and before any one-line elements (e.g., a clock).
23096 (progn
23097 (beginning-of-line)
23098 (let* ((element (org-element-at-point))
23099 (type (org-element-type element)))
23100 (cond
23101 ((and (eq type 'fixed-width)
23102 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23103 (replace-match
23104 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23105 ((and (memq type '(babel-call clock comment diary-sexp headline
23106 horizontal-rule keyword paragraph
23107 planning))
23108 (<= (org-element-property :post-affiliated element) (point)))
23109 (skip-chars-forward " \t")
23110 (insert ": "))
23111 ((and (looking-at-p "[ \t]*$")
23112 (or (eq type 'inlinetask)
23113 (save-excursion
23114 (skip-chars-forward " \r\t\n")
23115 (<= (org-element-property :end element) (point)))))
23116 (delete-region (point) (line-end-position))
23117 (org-indent-line)
23118 (insert ": "))
23119 (t (user-error "Cannot insert a fixed-width line here")))))
23120 ;; Region active.
23121 (let* ((begin (save-excursion
23122 (goto-char (region-beginning))
23123 (line-beginning-position)))
23124 (end (copy-marker
23125 (save-excursion
23126 (goto-char (region-end))
23127 (unless (eolp) (beginning-of-line))
23128 (if (save-excursion (re-search-backward "\\S-" begin t))
23129 (progn (skip-chars-backward " \r\t\n") (point))
23130 (point)))))
23131 (all-fixed-width-p
23132 (catch 'not-all-p
23133 (save-excursion
23134 (goto-char begin)
23135 (skip-chars-forward " \r\t\n")
23136 (when (eobp) (throw 'not-all-p nil))
23137 (while (< (point) end)
23138 (let ((element (org-element-at-point)))
23139 (if (eq (org-element-type element) 'fixed-width)
23140 (goto-char (org-element-property :end element))
23141 (throw 'not-all-p nil))))
23142 t))))
23143 (if all-fixed-width-p
23144 (save-excursion
23145 (goto-char begin)
23146 (while (< (point) end)
23147 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23148 (replace-match
23149 "" nil nil nil
23150 (if (= (line-end-position) (match-end 0)) 0 1)))
23151 (forward-line)))
23152 (let ((min-ind (point-max)))
23153 ;; Find minimum indentation across all lines.
23154 (save-excursion
23155 (goto-char begin)
23156 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23157 (setq min-ind 0)
23158 (catch 'zerop
23159 (while (< (point) end)
23160 (unless (looking-at-p "[ \t]*$")
23161 (let ((ind (org-get-indentation)))
23162 (setq min-ind (min min-ind ind))
23163 (when (zerop ind) (throw 'zerop t))))
23164 (forward-line)))))
23165 ;; Loop over all lines and add fixed-width markup everywhere
23166 ;; but in fixed-width lines.
23167 (save-excursion
23168 (goto-char begin)
23169 (while (< (point) end)
23170 (cond
23171 ((org-at-heading-p)
23172 (insert ": ")
23173 (forward-line)
23174 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23175 (insert ":")
23176 (forward-line)))
23177 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23178 (let* ((element (org-element-at-point))
23179 (element-end (org-element-property :end element)))
23180 (if (eq (org-element-type element) 'fixed-width)
23181 (progn (goto-char element-end)
23182 (skip-chars-backward " \r\t\n")
23183 (forward-line))
23184 (let ((limit (min end element-end)))
23185 (while (< (point) limit)
23186 (org-move-to-column min-ind t)
23187 (insert ": ")
23188 (forward-line))))))
23190 (org-move-to-column min-ind t)
23191 (insert ": ")
23192 (forward-line)))))))
23193 (set-marker end nil))))
23196 ;;; Comments
23198 ;; Org comments syntax is quite complex. It requires the entire line
23199 ;; to be just a comment. Also, even with the right syntax at the
23200 ;; beginning of line, some elements (e.g., verse-block or
23201 ;; example-block) don't accept comments. Usual Emacs comment commands
23202 ;; cannot cope with those requirements. Therefore, Org replaces them.
23204 ;; Org still relies on `comment-dwim', but cannot trust
23205 ;; `comment-only-p'. So, `comment-region-function' and
23206 ;; `uncomment-region-function' both point
23207 ;; to`org-comment-or-uncomment-region'. Eventually,
23208 ;; `org-insert-comment' takes care of insertion of comments at the
23209 ;; beginning of line.
23211 ;; `org-setup-comments-handling' install comments related variables
23212 ;; during `org-mode' initialization.
23214 (defun org-setup-comments-handling ()
23215 (interactive)
23216 (setq-local comment-use-syntax nil)
23217 (setq-local comment-start "# ")
23218 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23219 (setq-local comment-insert-comment-function 'org-insert-comment)
23220 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23221 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23223 (defun org-insert-comment ()
23224 "Insert an empty comment above current line.
23225 If the line is empty, insert comment at its beginning. When
23226 point is within a source block, comment according to the related
23227 major mode."
23228 (if (let ((element (org-element-at-point)))
23229 (and (eq (org-element-type element) 'src-block)
23230 (< (save-excursion
23231 (goto-char (org-element-property :post-affiliated element))
23232 (line-end-position))
23233 (point))
23234 (> (save-excursion
23235 (goto-char (org-element-property :end element))
23236 (skip-chars-backward " \r\t\n")
23237 (line-beginning-position))
23238 (point))))
23239 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23240 (beginning-of-line)
23241 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23242 (open-line 1))
23243 (org-indent-line)
23244 (insert "# ")))
23246 (defvar comment-empty-lines) ; From newcomment.el.
23247 (defun org-comment-or-uncomment-region (beg end &rest _)
23248 "Comment or uncomment each non-blank line in the region.
23249 Uncomment each non-blank line between BEG and END if it only
23250 contains commented lines. Otherwise, comment them. If region is
23251 strictly within a source block, use appropriate comment syntax."
23252 (if (let ((element (org-element-at-point)))
23253 (and (eq (org-element-type element) 'src-block)
23254 (< (save-excursion
23255 (goto-char (org-element-property :post-affiliated element))
23256 (line-end-position))
23257 beg)
23258 (>= (save-excursion
23259 (goto-char (org-element-property :end element))
23260 (skip-chars-backward " \r\t\n")
23261 (line-beginning-position))
23262 end)))
23263 ;; Translate region boundaries for the Org buffer to the source
23264 ;; buffer.
23265 (let ((offset (- end beg)))
23266 (save-excursion
23267 (goto-char beg)
23268 (org-babel-do-in-edit-buffer
23269 (comment-or-uncomment-region (point) (+ offset (point))))))
23270 (save-restriction
23271 ;; Restrict region
23272 (narrow-to-region (save-excursion (goto-char beg)
23273 (skip-chars-forward " \r\t\n" end)
23274 (line-beginning-position))
23275 (save-excursion (goto-char end)
23276 (skip-chars-backward " \r\t\n" beg)
23277 (line-end-position)))
23278 (let ((uncommentp
23279 ;; UNCOMMENTP is non-nil when every non blank line between
23280 ;; BEG and END is a comment.
23281 (save-excursion
23282 (goto-char (point-min))
23283 (while (and (not (eobp))
23284 (let ((element (org-element-at-point)))
23285 (and (eq (org-element-type element) 'comment)
23286 (goto-char (min (point-max)
23287 (org-element-property
23288 :end element)))))))
23289 (eobp))))
23290 (if uncommentp
23291 ;; Only blank lines and comments in region: uncomment it.
23292 (save-excursion
23293 (goto-char (point-min))
23294 (while (not (eobp))
23295 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23296 (replace-match "" nil nil nil 1))
23297 (forward-line)))
23298 ;; Comment each line in region.
23299 (let ((min-indent (point-max)))
23300 ;; First find the minimum indentation across all lines.
23301 (save-excursion
23302 (goto-char (point-min))
23303 (while (and (not (eobp)) (not (zerop min-indent)))
23304 (unless (looking-at "[ \t]*$")
23305 (setq min-indent (min min-indent (current-indentation))))
23306 (forward-line)))
23307 ;; Then loop over all lines.
23308 (save-excursion
23309 (goto-char (point-min))
23310 (while (not (eobp))
23311 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23312 ;; Don't get fooled by invisible text (e.g. link path)
23313 ;; when moving to column MIN-INDENT.
23314 (let ((buffer-invisibility-spec nil))
23315 (org-move-to-column min-indent t))
23316 (insert comment-start))
23317 (forward-line)))))))))
23319 (defun org-comment-dwim (_arg)
23320 "Call `comment-dwim' within a source edit buffer if needed."
23321 (interactive "*P")
23322 (if (org-in-src-block-p)
23323 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23324 (call-interactively 'comment-dwim)))
23327 ;;; Timestamps API
23329 ;; This section contains tools to operate on timestamp objects, as
23330 ;; returned by, e.g. `org-element-context'.
23332 (defun org-timestamp--to-internal-time (timestamp &optional end)
23333 "Encode TIMESTAMP object into Emacs internal time.
23334 Use end of date range or time range when END is non-nil."
23335 (apply #'encode-time
23336 (cons 0
23337 (mapcar
23338 (lambda (prop) (or (org-element-property prop timestamp) 0))
23339 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23340 '(:minute-start :hour-start :day-start :month-start
23341 :year-start))))))
23343 (defun org-timestamp-has-time-p (timestamp)
23344 "Non-nil when TIMESTAMP has a time specified."
23345 (org-element-property :hour-start timestamp))
23347 (defun org-timestamp-format (timestamp format &optional end utc)
23348 "Format a TIMESTAMP object into a string.
23350 FORMAT is a format specifier to be passed to
23351 `format-time-string'.
23353 When optional argument END is non-nil, use end of date-range or
23354 time-range, if possible.
23356 When optional argument UTC is non-nil, time will be expressed as
23357 Universal Time."
23358 (format-time-string
23359 format (org-timestamp--to-internal-time timestamp end)
23360 (and utc t)))
23362 (defun org-timestamp-split-range (timestamp &optional end)
23363 "Extract a TIMESTAMP object from a date or time range.
23365 END, when non-nil, means extract the end of the range.
23366 Otherwise, extract its start.
23368 Return a new timestamp object."
23369 (let ((type (org-element-property :type timestamp)))
23370 (if (memq type '(active inactive diary)) timestamp
23371 (let ((split-ts (org-element-copy timestamp)))
23372 ;; Set new type.
23373 (org-element-put-property
23374 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23375 ;; Copy start properties over end properties if END is
23376 ;; non-nil. Otherwise, copy end properties over `start' ones.
23377 (let ((p-alist '((:minute-start . :minute-end)
23378 (:hour-start . :hour-end)
23379 (:day-start . :day-end)
23380 (:month-start . :month-end)
23381 (:year-start . :year-end))))
23382 (dolist (p-cell p-alist)
23383 (org-element-put-property
23384 split-ts
23385 (funcall (if end #'car #'cdr) p-cell)
23386 (org-element-property
23387 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23388 ;; Eventually refresh `:raw-value'.
23389 (org-element-put-property split-ts :raw-value nil)
23390 (org-element-put-property
23391 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23393 (defun org-timestamp-translate (timestamp &optional boundary)
23394 "Translate TIMESTAMP object to custom format.
23396 Format string is defined in `org-time-stamp-custom-formats',
23397 which see.
23399 When optional argument BOUNDARY is non-nil, it is either the
23400 symbol `start' or `end'. In this case, only translate the
23401 starting or ending part of TIMESTAMP if it is a date or time
23402 range. Otherwise, translate both parts.
23404 Return timestamp as-is if `org-display-custom-times' is nil or if
23405 it has a `diary' type."
23406 (let ((type (org-element-property :type timestamp)))
23407 (if (or (not org-display-custom-times) (eq type 'diary))
23408 (org-element-interpret-data timestamp)
23409 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23410 org-time-stamp-custom-formats)))
23411 (if (and (not boundary) (memq type '(active-range inactive-range)))
23412 (concat (org-timestamp-format timestamp fmt)
23413 "--"
23414 (org-timestamp-format timestamp fmt t))
23415 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23419 ;;; Other stuff.
23421 (defvar reftex-docstruct-symbol)
23422 (defvar org--rds)
23424 (defun org-reftex-citation ()
23425 "Use reftex-citation to insert a citation into the buffer.
23426 This looks for a line like
23428 #+BIBLIOGRAPHY: foo plain option:-d
23430 and derives from it that foo.bib is the bibliography file relevant
23431 for this document. It then installs the necessary environment for RefTeX
23432 to work in this buffer and calls `reftex-citation' to insert a citation
23433 into the buffer.
23435 Export of such citations to both LaTeX and HTML is handled by the contributed
23436 package ox-bibtex by Taru Karttunen."
23437 (interactive)
23438 (let ((reftex-docstruct-symbol 'org--rds)
23439 org--rds bib)
23440 (org-with-wide-buffer
23441 (let ((case-fold-search t)
23442 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23443 (if (not (save-excursion
23444 (or (re-search-forward re nil t)
23445 (re-search-backward re nil t))))
23446 (user-error "No bibliography defined in file")
23447 (setq bib (concat (match-string 1) ".bib")
23448 org--rds (list (list 'bib bib))))))
23449 (call-interactively 'reftex-citation)))
23451 ;;;; Functions extending outline functionality
23453 (defun org-beginning-of-line (&optional n)
23454 "Go to the beginning of the current visible line.
23456 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23457 tags on the first attempt, and only move to after the tags when
23458 the cursor is already beyond the end of the headline.
23460 With argument N not nil or 1, move forward N - 1 lines first."
23461 (interactive "^p")
23462 (let ((origin (point))
23463 (special (pcase org-special-ctrl-a/e
23464 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23465 deactivate-mark)
23466 ;; First move to a visible line.
23467 (if (bound-and-true-p visual-line-mode)
23468 (beginning-of-visual-line n)
23469 (move-beginning-of-line n)
23470 ;; `move-beginning-of-line' may leave point after invisible
23471 ;; characters if line starts with such of these (e.g., with
23472 ;; a link at column 0). Really move to the beginning of the
23473 ;; current visible line.
23474 (beginning-of-line))
23475 (cond
23476 ;; No special behavior. Point is already at the beginning of
23477 ;; a line, logical or visual.
23478 ((not special))
23479 ;; `beginning-of-visual-line' left point before logical beginning
23480 ;; of line: point is at the beginning of a visual line. Bail
23481 ;; out.
23482 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23483 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23484 ;; At a headline, special position is before the title, but
23485 ;; after any TODO keyword or priority cookie.
23486 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23487 (line-end-position)))
23488 (bol (point)))
23489 (if (eq special 'reversed)
23490 (when (and (= origin bol) (eq last-command this-command))
23491 (goto-char refpos))
23492 (when (or (> origin refpos) (= origin bol))
23493 (goto-char refpos)))))
23494 ((and (looking-at org-list-full-item-re)
23495 (memq (org-element-type (save-match-data (org-element-at-point)))
23496 '(item plain-list)))
23497 ;; Set special position at first white space character after
23498 ;; bullet, and check-box, if any.
23499 (let ((after-bullet
23500 (let ((box (match-end 3)))
23501 (cond ((not box) (match-end 1))
23502 ((eq (char-after box) ?\s) (1+ box))
23503 (t box)))))
23504 (if (eq special 'reversed)
23505 (when (and (= (point) origin) (eq last-command this-command))
23506 (goto-char after-bullet))
23507 (when (or (> origin after-bullet) (= (point) origin))
23508 (goto-char after-bullet)))))
23509 ;; No special context. Point is already at beginning of line.
23510 (t nil))))
23512 (defun org-end-of-line (&optional n)
23513 "Go to the end of the line, but before ellipsis, if any.
23515 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23516 tags on the first attempt, and only move to after the tags when
23517 the cursor is already beyond the end of the headline.
23519 With argument N not nil or 1, move forward N - 1 lines first."
23520 (interactive "^p")
23521 (let ((origin (point))
23522 (special (pcase org-special-ctrl-a/e
23523 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23524 deactivate-mark)
23525 ;; First move to a visible line.
23526 (if (bound-and-true-p visual-line-mode)
23527 (beginning-of-visual-line n)
23528 (move-beginning-of-line n))
23529 (cond
23530 ;; At a headline, with tags.
23531 ((and special
23532 (save-excursion
23533 (beginning-of-line)
23534 (let ((case-fold-search nil))
23535 (looking-at org-complex-heading-regexp)))
23536 (match-end 5))
23537 (let ((tags (save-excursion
23538 (goto-char (match-beginning 5))
23539 (skip-chars-backward " \t")
23540 (point)))
23541 (visual-end (and (bound-and-true-p visual-line-mode)
23542 (save-excursion
23543 (end-of-visual-line)
23544 (point)))))
23545 ;; If `end-of-visual-line' brings us before end of line or
23546 ;; even tags, i.e., the headline spans over multiple visual
23547 ;; lines, move there.
23548 (cond ((and visual-end
23549 (< visual-end tags)
23550 (<= origin visual-end))
23551 (goto-char visual-end))
23552 ((eq special 'reversed)
23553 (if (and (= origin (line-end-position))
23554 (eq this-command last-command))
23555 (goto-char tags)
23556 (end-of-line)))
23558 (if (or (< origin tags) (= origin (line-end-position)))
23559 (goto-char tags)
23560 (end-of-line))))))
23561 ((bound-and-true-p visual-line-mode)
23562 (let ((bol (line-beginning-position)))
23563 (end-of-visual-line)
23564 ;; If `end-of-visual-line' gets us past the ellipsis at the
23565 ;; end of a line, backtrack and use `end-of-line' instead.
23566 (when (/= bol (line-beginning-position))
23567 (goto-char bol)
23568 (end-of-line))))
23569 (t (end-of-line)))))
23571 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23572 (define-key org-mode-map "\C-e" 'org-end-of-line)
23574 (defun org-backward-sentence (&optional _arg)
23575 "Go to beginning of sentence, or beginning of table field.
23576 This will call `backward-sentence' or `org-table-beginning-of-field',
23577 depending on context."
23578 (interactive)
23579 (let* ((element (org-element-at-point))
23580 (contents-begin (org-element-property :contents-begin element))
23581 (table (org-element-lineage element '(table) t)))
23582 (if (and table
23583 (> (point) contents-begin)
23584 (<= (point) (org-element-property :contents-end table)))
23585 (call-interactively #'org-table-beginning-of-field)
23586 (save-restriction
23587 (when (and contents-begin
23588 (< (point-min) contents-begin)
23589 (> (point) contents-begin))
23590 (narrow-to-region contents-begin
23591 (org-element-property :contents-end element)))
23592 (call-interactively #'backward-sentence)))))
23594 (defun org-forward-sentence (&optional _arg)
23595 "Go to end of sentence, or end of table field.
23596 This will call `forward-sentence' or `org-table-end-of-field',
23597 depending on context."
23598 (interactive)
23599 (if (and (org-at-heading-p)
23600 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23601 (save-restriction
23602 (narrow-to-region (line-beginning-position) (line-end-position))
23603 (call-interactively #'forward-sentence))
23604 (let* ((element (org-element-at-point))
23605 (contents-end (org-element-property :contents-end element))
23606 (table (org-element-lineage element '(table) t)))
23607 (if (and table
23608 (>= (point) (org-element-property :contents-begin table))
23609 (< (point) contents-end))
23610 (call-interactively #'org-table-end-of-field)
23611 (save-restriction
23612 (when (and contents-end
23613 (> (point-max) contents-end)
23614 ;; Skip blank lines between elements.
23615 (< (org-element-property :end element)
23616 (save-excursion (goto-char contents-end)
23617 (skip-chars-forward " \r\t\n"))))
23618 (narrow-to-region (org-element-property :contents-begin element)
23619 contents-end))
23620 (call-interactively #'forward-sentence))))))
23622 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23623 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23625 (defun org-kill-line (&optional _arg)
23626 "Kill line, to tags or end of line."
23627 (interactive)
23628 (cond
23629 ((or (not org-special-ctrl-k)
23630 (bolp)
23631 (not (org-at-heading-p)))
23632 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23633 org-ctrl-k-protect-subtree
23634 (or (eq org-ctrl-k-protect-subtree 'error)
23635 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23636 (user-error "C-k aborted as it would kill a hidden subtree"))
23637 (call-interactively
23638 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23639 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23640 (kill-region (point) (match-beginning 1))
23641 (org-set-tags nil t))
23642 (t (kill-region (point) (point-at-eol)))))
23644 (define-key org-mode-map "\C-k" 'org-kill-line)
23646 (defun org-yank (&optional arg)
23647 "Yank. If the kill is a subtree, treat it specially.
23648 This command will look at the current kill and check if is a single
23649 subtree, or a series of subtrees[1]. If it passes the test, and if the
23650 cursor is at the beginning of a line or after the stars of a currently
23651 empty headline, then the yank is handled specially. How exactly depends
23652 on the value of the following variables.
23654 `org-yank-folded-subtrees'
23655 By default, this variable is non-nil, which results in
23656 subtree(s) being folded after insertion, except if doing so
23657 would swallow text after the yanked text.
23659 `org-yank-adjusted-subtrees'
23660 When non-nil (the default value is nil), the subtree will be
23661 promoted or demoted in order to fit into the local outline tree
23662 structure, which means that the level will be adjusted so that it
23663 becomes the smaller one of the two *visible* surrounding headings.
23665 Any prefix to this command will cause `yank' to be called directly with
23666 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23667 will just
23668 plainly yank the text as it is.
23670 \[1] The test checks if the first non-white line is a heading
23671 and if there are no other headings with fewer stars."
23672 (interactive "P")
23673 (org-yank-generic 'yank arg))
23675 (defun org-yank-generic (command arg)
23676 "Perform some yank-like command.
23678 This function implements the behavior described in the `org-yank'
23679 documentation. However, it has been generalized to work for any
23680 interactive command with similar behavior."
23682 ;; pretend to be command COMMAND
23683 (setq this-command command)
23685 (if arg
23686 (call-interactively command)
23688 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23689 (and (org-kill-is-subtree-p)
23690 (or (bolp)
23691 (and (looking-at "[ \t]*$")
23692 (string-match
23693 "\\`\\*+\\'"
23694 (buffer-substring (point-at-bol) (point)))))))
23695 swallowp)
23696 (cond
23697 ((and subtreep org-yank-folded-subtrees)
23698 (let ((beg (point))
23699 end)
23700 (if (and subtreep org-yank-adjusted-subtrees)
23701 (org-paste-subtree nil nil 'for-yank)
23702 (call-interactively command))
23704 (setq end (point))
23705 (goto-char beg)
23706 (when (and (bolp) subtreep
23707 (not (setq swallowp
23708 (org-yank-folding-would-swallow-text beg end))))
23709 (org-with-limited-levels
23710 (or (looking-at org-outline-regexp)
23711 (re-search-forward org-outline-regexp-bol end t))
23712 (while (and (< (point) end) (looking-at org-outline-regexp))
23713 (outline-hide-subtree)
23714 (org-cycle-show-empty-lines 'folded)
23715 (condition-case nil
23716 (outline-forward-same-level 1)
23717 (error (goto-char end))))))
23718 (when swallowp
23719 (message
23720 "Inserted text not folded because that would swallow text"))
23722 (goto-char end)
23723 (skip-chars-forward " \t\n\r")
23724 (beginning-of-line 1)
23725 (push-mark beg 'nomsg)))
23726 ((and subtreep org-yank-adjusted-subtrees)
23727 (let ((beg (point-at-bol)))
23728 (org-paste-subtree nil nil 'for-yank)
23729 (push-mark beg 'nomsg)))
23731 (call-interactively command))))))
23733 (defun org-yank-folding-would-swallow-text (beg end)
23734 "Would hide-subtree at BEG swallow any text after END?"
23735 (let (level)
23736 (org-with-limited-levels
23737 (save-excursion
23738 (goto-char beg)
23739 (when (or (looking-at org-outline-regexp)
23740 (re-search-forward org-outline-regexp-bol end t))
23741 (setq level (org-outline-level)))
23742 (goto-char end)
23743 (skip-chars-forward " \t\r\n\v\f")
23744 (not (or (eobp)
23745 (and (bolp) (looking-at-p org-outline-regexp)
23746 (<= (org-outline-level) level))))))))
23748 (define-key org-mode-map "\C-y" 'org-yank)
23750 (defun org-truely-invisible-p ()
23751 "Check if point is at a character currently not visible.
23752 This version does not only check the character property, but also
23753 `visible-mode'."
23754 (unless (bound-and-true-p visible-mode)
23755 (org-invisible-p)))
23757 (defun org-invisible-p2 ()
23758 "Check if point is at a character currently not visible.
23760 If the point is at EOL (and not at the beginning of a buffer too),
23761 move it back by one char before doing this check."
23762 (save-excursion
23763 (when (and (eolp) (not (bobp)))
23764 (backward-char 1))
23765 (org-invisible-p)))
23767 (defun org-back-to-heading (&optional invisible-ok)
23768 "Call `outline-back-to-heading', but provide a better error message."
23769 (condition-case nil
23770 (outline-back-to-heading invisible-ok)
23771 (error (error "Before first headline at position %d in buffer %s"
23772 (point) (current-buffer)))))
23774 (defun org-before-first-heading-p ()
23775 "Before first heading?"
23776 (save-excursion
23777 (end-of-line)
23778 (null (re-search-backward org-outline-regexp-bol nil t))))
23780 (defun org-at-heading-p (&optional ignored)
23781 (outline-on-heading-p t))
23783 (defun org-in-commented-heading-p (&optional no-inheritance)
23784 "Non-nil if point is under a commented heading.
23785 This function also checks ancestors of the current headline,
23786 unless optional argument NO-INHERITANCE is non-nil."
23787 (cond
23788 ((org-before-first-heading-p) nil)
23789 ((let ((headline (nth 4 (org-heading-components))))
23790 (and headline
23791 (let ((case-fold-search nil))
23792 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23793 headline)))))
23794 (no-inheritance nil)
23796 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23798 (defun org-at-comment-p nil
23799 "Is cursor in a commented line?"
23800 (save-excursion
23801 (save-match-data
23802 (beginning-of-line)
23803 (looking-at "^[ \t]*# "))))
23805 (defun org-at-drawer-p nil
23806 "Is cursor at a drawer keyword?"
23807 (save-excursion
23808 (move-beginning-of-line 1)
23809 (looking-at org-drawer-regexp)))
23811 (defun org-at-block-p nil
23812 "Is cursor at a block keyword?"
23813 (save-excursion
23814 (move-beginning-of-line 1)
23815 (looking-at org-block-regexp)))
23817 (defun org-point-at-end-of-empty-headline ()
23818 "If point is at the end of an empty headline, return t, else nil.
23819 If the heading only contains a TODO keyword, it is still still considered
23820 empty."
23821 (let ((case-fold-search nil))
23822 (and (looking-at "[ \t]*$")
23823 org-todo-line-regexp
23824 (save-excursion
23825 (beginning-of-line)
23826 (looking-at org-todo-line-regexp)
23827 (string= (match-string 3) "")))))
23829 (defun org-at-heading-or-item-p ()
23830 (or (org-at-heading-p) (org-at-item-p)))
23832 (defun org-at-target-p ()
23833 (or (org-in-regexp org-radio-target-regexp)
23834 (org-in-regexp org-target-regexp)))
23835 ;; Compatibility alias with Org versions < 7.8.03
23836 (defalias 'org-on-target-p 'org-at-target-p)
23838 (defun org-up-heading-all (arg)
23839 "Move to the heading line of which the present line is a subheading.
23840 This function considers both visible and invisible heading lines.
23841 With argument, move up ARG levels."
23842 (outline-up-heading arg t))
23844 (defun org-up-heading-safe ()
23845 "Move to the heading line of which the present line is a subheading.
23846 This version will not throw an error. It will return the level of the
23847 headline found, or nil if no higher level is found.
23849 Also, this function will be a lot faster than `outline-up-heading',
23850 because it relies on stars being the outline starters. This can really
23851 make a significant difference in outlines with very many siblings."
23852 (when (ignore-errors (org-back-to-heading t))
23853 (let ((level-up (1- (funcall outline-level))))
23854 (and (> level-up 0)
23855 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23856 (funcall outline-level)))))
23858 (defun org-first-sibling-p ()
23859 "Is this heading the first child of its parents?"
23860 (interactive)
23861 (let ((re org-outline-regexp-bol)
23862 level l)
23863 (unless (org-at-heading-p t)
23864 (user-error "Not at a heading"))
23865 (setq level (funcall outline-level))
23866 (save-excursion
23867 (if (not (re-search-backward re nil t))
23869 (setq l (funcall outline-level))
23870 (< l level)))))
23872 (defun org-goto-sibling (&optional previous)
23873 "Goto the next sibling, even if it is invisible.
23874 When PREVIOUS is set, go to the previous sibling instead. Returns t
23875 when a sibling was found. When none is found, return nil and don't
23876 move point."
23877 (let ((fun (if previous 're-search-backward 're-search-forward))
23878 (pos (point))
23879 (re org-outline-regexp-bol)
23880 level l)
23881 (when (ignore-errors (org-back-to-heading t))
23882 (setq level (funcall outline-level))
23883 (catch 'exit
23884 (or previous (forward-char 1))
23885 (while (funcall fun re nil t)
23886 (setq l (funcall outline-level))
23887 (when (< l level) (goto-char pos) (throw 'exit nil))
23888 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23889 (goto-char pos)
23890 nil))))
23892 (defun org-show-siblings ()
23893 "Show all siblings of the current headline."
23894 (save-excursion
23895 (while (org-goto-sibling) (org-flag-heading nil)))
23896 (save-excursion
23897 (while (org-goto-sibling 'previous)
23898 (org-flag-heading nil))))
23900 (defun org-goto-first-child ()
23901 "Goto the first child, even if it is invisible.
23902 Return t when a child was found. Otherwise don't move point and
23903 return nil."
23904 (let (level (pos (point)) (re org-outline-regexp-bol))
23905 (when (ignore-errors (org-back-to-heading t))
23906 (setq level (outline-level))
23907 (forward-char 1)
23908 (if (and (re-search-forward re nil t) (> (outline-level) level))
23909 (progn (goto-char (match-beginning 0)) t)
23910 (goto-char pos) nil))))
23912 (defun org-show-hidden-entry ()
23913 "Show an entry where even the heading is hidden."
23914 (save-excursion
23915 (org-show-entry)))
23917 (defun org-flag-heading (flag &optional entry)
23918 "Flag the current heading. FLAG non-nil means make invisible.
23919 When ENTRY is non-nil, show the entire entry."
23920 (save-excursion
23921 (org-back-to-heading t)
23922 ;; Check if we should show the entire entry
23923 (if entry
23924 (progn
23925 (org-show-entry)
23926 (save-excursion
23927 (and (outline-next-heading)
23928 (org-flag-heading nil))))
23929 (outline-flag-region (max (point-min) (1- (point)))
23930 (save-excursion (outline-end-of-heading) (point))
23931 flag))))
23933 (defun org-get-next-sibling ()
23934 "Move to next heading of the same level, and return point.
23935 If there is no such heading, return nil.
23936 This is like outline-next-sibling, but invisible headings are ok."
23937 (let ((level (funcall outline-level)))
23938 (outline-next-heading)
23939 (while (and (not (eobp)) (> (funcall outline-level) level))
23940 (outline-next-heading))
23941 (unless (or (eobp) (< (funcall outline-level) level))
23942 (point))))
23944 (defun org-get-last-sibling ()
23945 "Move to previous heading of the same level, and return point.
23946 If there is no such heading, return nil."
23947 (let ((opoint (point))
23948 (level (funcall outline-level)))
23949 (outline-previous-heading)
23950 (when (and (/= (point) opoint) (outline-on-heading-p t))
23951 (while (and (> (funcall outline-level) level)
23952 (not (bobp)))
23953 (outline-previous-heading))
23954 (unless (< (funcall outline-level) level)
23955 (point)))))
23957 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23958 "Goto to the end of a subtree."
23959 ;; This contains an exact copy of the original function, but it uses
23960 ;; `org-back-to-heading', to make it work also in invisible
23961 ;; trees. And is uses an invisible-ok argument.
23962 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23963 ;; Furthermore, when used inside Org, finding the end of a large subtree
23964 ;; with many children and grandchildren etc, this can be much faster
23965 ;; than the outline version.
23966 (org-back-to-heading invisible-ok)
23967 (let ((first t)
23968 (level (funcall outline-level)))
23969 (if (and (derived-mode-p 'org-mode) (< level 1000))
23970 ;; A true heading (not a plain list item), in Org
23971 ;; This means we can easily find the end by looking
23972 ;; only for the right number of stars. Using a regexp to do
23973 ;; this is so much faster than using a Lisp loop.
23974 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23975 (forward-char 1)
23976 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23977 ;; something else, do it the slow way
23978 (while (and (not (eobp))
23979 (or first (> (funcall outline-level) level)))
23980 (setq first nil)
23981 (outline-next-heading)))
23982 (unless to-heading
23983 (when (memq (preceding-char) '(?\n ?\^M))
23984 ;; Go to end of line before heading
23985 (forward-char -1)
23986 (when (memq (preceding-char) '(?\n ?\^M))
23987 ;; leave blank line before heading
23988 (forward-char -1)))))
23989 (point))
23991 (defun org-end-of-meta-data (&optional full)
23992 "Skip planning line and properties drawer in current entry.
23993 When optional argument FULL is non-nil, also skip empty lines,
23994 clocking lines and regular drawers at the beginning of the
23995 entry."
23996 (org-back-to-heading t)
23997 (forward-line)
23998 (when (looking-at-p org-planning-line-re) (forward-line))
23999 (when (looking-at org-property-drawer-re)
24000 (goto-char (match-end 0))
24001 (forward-line))
24002 (when (and full (not (org-at-heading-p)))
24003 (catch 'exit
24004 (let ((end (save-excursion (outline-next-heading) (point)))
24005 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24006 (while (not (eobp))
24007 (cond ((looking-at-p org-drawer-regexp)
24008 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24009 (forward-line)
24010 (throw 'exit t)))
24011 ((looking-at-p re) (forward-line))
24012 (t (throw 'exit t))))))))
24014 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24015 "Move forward to the ARG'th subheading at same level as this one.
24016 Stop at the first and last subheadings of a superior heading.
24017 Normally this only looks at visible headings, but when INVISIBLE-OK is
24018 non-nil it will also look at invisible ones."
24019 (interactive "p")
24020 (let ((backward? (and arg (< arg 0))))
24021 (if (org-before-first-heading-p)
24022 (if backward? (goto-char (point-min)) (outline-next-heading))
24023 (org-back-to-heading invisible-ok)
24024 (unless backward? (end-of-line)) ;do not match current headline
24025 (let ((level (- (match-end 0) (match-beginning 0) 1))
24026 (f (if backward? #'re-search-backward #'re-search-forward))
24027 (count (if arg (abs arg) 1))
24028 (result (point)))
24029 (while (and (> count 0)
24030 (funcall f org-outline-regexp-bol nil 'move))
24031 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24032 (cond ((< l level) (setq count 0))
24033 ((and (= l level)
24034 (or invisible-ok
24035 (not (org-invisible-p
24036 (line-beginning-position)))))
24037 (cl-decf count)
24038 (when (= l level) (setq result (point)))))))
24039 (goto-char result))
24040 (beginning-of-line))))
24042 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24043 "Move backward to the ARG'th subheading at same level as this one.
24044 Stop at the first and last subheadings of a superior heading."
24045 (interactive "p")
24046 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24048 (defun org-next-visible-heading (arg)
24049 "Move to the next visible heading.
24051 This function wraps `outline-next-visible-heading' with
24052 `org-with-limited-levels' in order to skip over inline tasks and
24053 respect customization of `org-odd-levels-only'."
24054 (interactive "p")
24055 (org-with-limited-levels
24056 (outline-next-visible-heading arg)))
24058 (defun org-previous-visible-heading (arg)
24059 "Move to the previous visible heading.
24061 This function wraps `outline-previous-visible-heading' with
24062 `org-with-limited-levels' in order to skip over inline tasks and
24063 respect customization of `org-odd-levels-only'."
24064 (interactive "p")
24065 (org-with-limited-levels
24066 (outline-previous-visible-heading arg)))
24068 (defun org-next-block (arg &optional backward block-regexp)
24069 "Jump to the next block.
24071 With a prefix argument ARG, jump forward ARG many blocks.
24073 When BACKWARD is non-nil, jump to the previous block.
24075 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24076 Match data is set according to this regexp when the function
24077 returns.
24079 Return point at beginning of the opening line of found block.
24080 Throw an error if no block is found."
24081 (interactive "p")
24082 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24083 (case-fold-search t)
24084 (search-fn (if backward #'re-search-backward #'re-search-forward))
24085 (count (or arg 1))
24086 (origin (point))
24087 last-element)
24088 (if backward (beginning-of-line) (end-of-line))
24089 (while (and (> count 0) (funcall search-fn re nil t))
24090 (let ((element (save-excursion
24091 (goto-char (match-beginning 0))
24092 (save-match-data (org-element-at-point)))))
24093 (when (and (memq (org-element-type element)
24094 '(center-block comment-block dynamic-block
24095 example-block export-block quote-block
24096 special-block src-block verse-block))
24097 (<= (match-beginning 0)
24098 (org-element-property :post-affiliated element)))
24099 (setq last-element element)
24100 (cl-decf count))))
24101 (if (= count 0)
24102 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24103 (save-match-data (org-show-context)))
24104 (goto-char origin)
24105 (user-error "No %s code blocks" (if backward "previous" "further")))))
24107 (defun org-previous-block (arg &optional block-regexp)
24108 "Jump to the previous block.
24109 With a prefix argument ARG, jump backward ARG many source blocks.
24110 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24111 (interactive "p")
24112 (org-next-block arg t block-regexp))
24114 (defun org-forward-paragraph ()
24115 "Move forward to beginning of next paragraph or equivalent.
24117 The function moves point to the beginning of the next visible
24118 structural element, which can be a paragraph, a table, a list
24119 item, etc. It also provides some special moves for convenience:
24121 - On an affiliated keyword, jump to the beginning of the
24122 relative element.
24123 - On an item or a footnote definition, move to the second
24124 element inside, if any.
24125 - On a table or a property drawer, jump after it.
24126 - On a verse or source block, stop after blank lines."
24127 (interactive)
24128 (unless (eobp)
24129 (let* ((deactivate-mark nil)
24130 (element (org-element-at-point))
24131 (type (org-element-type element))
24132 (post-affiliated (org-element-property :post-affiliated element))
24133 (contents-begin (org-element-property :contents-begin element))
24134 (contents-end (org-element-property :contents-end element))
24135 (end (let ((end (org-element-property :end element)) (parent element))
24136 (while (and (setq parent (org-element-property :parent parent))
24137 (= (org-element-property :contents-end parent) end))
24138 (setq end (org-element-property :end parent)))
24139 end)))
24140 (cond ((not element)
24141 (skip-chars-forward " \r\t\n")
24142 (or (eobp) (beginning-of-line)))
24143 ;; On affiliated keywords, move to element's beginning.
24144 ((< (point) post-affiliated)
24145 (goto-char post-affiliated))
24146 ;; At a table row, move to the end of the table. Similarly,
24147 ;; at a node property, move to the end of the property
24148 ;; drawer.
24149 ((memq type '(node-property table-row))
24150 (goto-char (org-element-property
24151 :end (org-element-property :parent element))))
24152 ((memq type '(property-drawer table)) (goto-char end))
24153 ;; Consider blank lines as separators in verse and source
24154 ;; blocks to ease editing.
24155 ((memq type '(src-block verse-block))
24156 (when (eq type 'src-block)
24157 (setq contents-end
24158 (save-excursion (goto-char end)
24159 (skip-chars-backward " \r\t\n")
24160 (line-beginning-position))))
24161 (beginning-of-line)
24162 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24163 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24164 (goto-char end)
24165 (skip-chars-forward " \r\t\n")
24166 (if (= (point) contents-end) (goto-char end)
24167 (beginning-of-line))))
24168 ;; With no contents, just skip element.
24169 ((not contents-begin) (goto-char end))
24170 ;; If contents are invisible, skip the element altogether.
24171 ((org-invisible-p (line-end-position))
24172 (cl-case type
24173 (headline
24174 (org-with-limited-levels (outline-next-visible-heading 1)))
24175 ;; At a plain list, make sure we move to the next item
24176 ;; instead of skipping the whole list.
24177 (plain-list (forward-char)
24178 (org-forward-paragraph))
24179 (otherwise (goto-char end))))
24180 ((>= (point) contents-end) (goto-char end))
24181 ((>= (point) contents-begin)
24182 ;; This can only happen on paragraphs and plain lists.
24183 (cl-case type
24184 (paragraph (goto-char end))
24185 ;; At a plain list, try to move to second element in
24186 ;; first item, if possible.
24187 (plain-list (end-of-line)
24188 (org-forward-paragraph))))
24189 ;; When contents start on the middle of a line (e.g. in
24190 ;; items and footnote definitions), try to reach first
24191 ;; element starting after current line.
24192 ((> (line-end-position) contents-begin)
24193 (end-of-line)
24194 (org-forward-paragraph))
24195 (t (goto-char contents-begin))))))
24197 (defun org-backward-paragraph ()
24198 "Move backward to start of previous paragraph or equivalent.
24200 The function moves point to the beginning of the current
24201 structural element, which can be a paragraph, a table, a list
24202 item, etc., or to the beginning of the previous visible one if
24203 point is already there. It also provides some special moves for
24204 convenience:
24206 - On an affiliated keyword, jump to the first one.
24207 - On a table or a property drawer, move to its beginning.
24208 - On comment, example, export, src and verse blocks, stop
24209 before blank lines."
24210 (interactive)
24211 (unless (bobp)
24212 (let* ((deactivate-mark nil)
24213 (element (org-element-at-point))
24214 (type (org-element-type element))
24215 (contents-end (org-element-property :contents-end element))
24216 (post-affiliated (org-element-property :post-affiliated element))
24217 (begin (org-element-property :begin element))
24218 (special? ;blocks handled specially
24219 (memq type '(comment-block example-block export-block src-block
24220 verse-block)))
24221 (contents-begin
24222 (if special?
24223 ;; These types have no proper contents. Fake line
24224 ;; below the block opening line as contents beginning.
24225 (save-excursion (goto-char begin) (line-beginning-position 2))
24226 (org-element-property :contents-begin element))))
24227 (cond
24228 ((not element) (goto-char (point-min)))
24229 ((= (point) begin)
24230 (backward-char)
24231 (org-backward-paragraph))
24232 ((<= (point) post-affiliated) (goto-char begin))
24233 ((memq type '(node-property table-row))
24234 (goto-char (org-element-property
24235 :post-affiliated (org-element-property :parent element))))
24236 ((memq type '(property-drawer table)) (goto-char begin))
24237 (special?
24238 (if (<= (point) contents-begin) (goto-char post-affiliated)
24239 ;; Inside a verse block, see blank lines as paragraph
24240 ;; separators.
24241 (let ((origin (point)))
24242 (skip-chars-backward " \r\t\n" contents-begin)
24243 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24244 (skip-chars-forward " \r\t\n" origin)
24245 (if (= (point) origin) (goto-char contents-begin)
24246 (beginning-of-line))))))
24247 ((eq type 'paragraph)
24248 (goto-char contents-begin)
24249 ;; When at first paragraph in an item or a footnote definition,
24250 ;; move directly to beginning of line.
24251 (let ((parent-contents
24252 (org-element-property
24253 :contents-begin (org-element-property :parent element))))
24254 (when (and parent-contents (= parent-contents contents-begin))
24255 (beginning-of-line))))
24256 ;; At the end of a greater element, move to the beginning of the
24257 ;; last element within.
24258 ((>= (point) contents-end)
24259 (goto-char (1- contents-end))
24260 (org-backward-paragraph))
24261 (t (goto-char (or post-affiliated begin))))
24262 ;; Ensure we never leave point invisible.
24263 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24265 (defun org-forward-element ()
24266 "Move forward by one element.
24267 Move to the next element at the same level, when possible."
24268 (interactive)
24269 (cond ((eobp) (user-error "Cannot move further down"))
24270 ((org-with-limited-levels (org-at-heading-p))
24271 (let ((origin (point)))
24272 (goto-char (org-end-of-subtree nil t))
24273 (unless (org-with-limited-levels (org-at-heading-p))
24274 (goto-char origin)
24275 (user-error "Cannot move further down"))))
24277 (let* ((elem (org-element-at-point))
24278 (end (org-element-property :end elem))
24279 (parent (org-element-property :parent elem)))
24280 (cond ((and parent (= (org-element-property :contents-end parent) end))
24281 (goto-char (org-element-property :end parent)))
24282 ((integer-or-marker-p end) (goto-char end))
24283 (t (message "No element at point")))))))
24285 (defun org-backward-element ()
24286 "Move backward by one element.
24287 Move to the previous element at the same level, when possible."
24288 (interactive)
24289 (cond ((bobp) (user-error "Cannot move further up"))
24290 ((org-with-limited-levels (org-at-heading-p))
24291 ;; At a headline, move to the previous one, if any, or stay
24292 ;; here.
24293 (let ((origin (point)))
24294 (org-with-limited-levels (org-backward-heading-same-level 1))
24295 ;; When current headline has no sibling above, move to its
24296 ;; parent.
24297 (when (= (point) origin)
24298 (or (org-with-limited-levels (org-up-heading-safe))
24299 (progn (goto-char origin)
24300 (user-error "Cannot move further up"))))))
24302 (let* ((elem (org-element-at-point))
24303 (beg (org-element-property :begin elem)))
24304 (cond
24305 ;; Move to beginning of current element if point isn't
24306 ;; there already.
24307 ((null beg) (message "No element at point"))
24308 ((/= (point) beg) (goto-char beg))
24309 (t (goto-char beg)
24310 (skip-chars-backward " \r\t\n")
24311 (unless (bobp)
24312 (let ((prev (org-element-at-point)))
24313 (goto-char (org-element-property :begin prev))
24314 (while (and (setq prev (org-element-property :parent prev))
24315 (<= (org-element-property :end prev) beg))
24316 (goto-char (org-element-property :begin prev)))))))))))
24318 (defun org-up-element ()
24319 "Move to upper element."
24320 (interactive)
24321 (if (org-with-limited-levels (org-at-heading-p))
24322 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24323 (let* ((elem (org-element-at-point))
24324 (parent (org-element-property :parent elem)))
24325 (if parent (goto-char (org-element-property :begin parent))
24326 (if (org-with-limited-levels (org-before-first-heading-p))
24327 (user-error "No surrounding element")
24328 (org-with-limited-levels (org-back-to-heading)))))))
24330 (defun org-down-element ()
24331 "Move to inner element."
24332 (interactive)
24333 (let ((element (org-element-at-point)))
24334 (cond
24335 ((memq (org-element-type element) '(plain-list table))
24336 (goto-char (org-element-property :contents-begin element))
24337 (forward-char))
24338 ((memq (org-element-type element) org-element-greater-elements)
24339 ;; If contents are hidden, first disclose them.
24340 (when (org-invisible-p (line-end-position)) (org-cycle))
24341 (goto-char (or (org-element-property :contents-begin element)
24342 (user-error "No content for this element"))))
24343 (t (user-error "No inner element")))))
24345 (defun org-drag-element-backward ()
24346 "Move backward element at point."
24347 (interactive)
24348 (let ((elem (or (org-element-at-point)
24349 (user-error "No element at point"))))
24350 (if (eq (org-element-type elem) 'headline)
24351 ;; Preserve point when moving a whole tree, even if point was
24352 ;; on blank lines below the headline.
24353 (let ((offset (skip-chars-backward " \t\n")))
24354 (unwind-protect (org-move-subtree-up)
24355 (forward-char (- offset))))
24356 (let ((prev-elem
24357 (save-excursion
24358 (goto-char (org-element-property :begin elem))
24359 (skip-chars-backward " \r\t\n")
24360 (unless (bobp)
24361 (let* ((beg (org-element-property :begin elem))
24362 (prev (org-element-at-point))
24363 (up prev))
24364 (while (and (setq up (org-element-property :parent up))
24365 (<= (org-element-property :end up) beg))
24366 (setq prev up))
24367 prev)))))
24368 ;; Error out if no previous element or previous element is
24369 ;; a parent of the current one.
24370 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24371 (user-error "Cannot drag element backward")
24372 (let ((pos (point)))
24373 (org-element-swap-A-B prev-elem elem)
24374 (goto-char (+ (org-element-property :begin prev-elem)
24375 (- pos (org-element-property :begin elem))))))))))
24377 (defun org-drag-element-forward ()
24378 "Move forward element at point."
24379 (interactive)
24380 (let* ((pos (point))
24381 (elem (or (org-element-at-point)
24382 (user-error "No element at point"))))
24383 (when (= (point-max) (org-element-property :end elem))
24384 (user-error "Cannot drag element forward"))
24385 (goto-char (org-element-property :end elem))
24386 (let ((next-elem (org-element-at-point)))
24387 (when (or (org-element-nested-p elem next-elem)
24388 (and (eq (org-element-type next-elem) 'headline)
24389 (not (eq (org-element-type elem) 'headline))))
24390 (goto-char pos)
24391 (user-error "Cannot drag element forward"))
24392 ;; Compute new position of point: it's shifted by NEXT-ELEM
24393 ;; body's length (without final blanks) and by the length of
24394 ;; blanks between ELEM and NEXT-ELEM.
24395 (let ((size-next (- (save-excursion
24396 (goto-char (org-element-property :end next-elem))
24397 (skip-chars-backward " \r\t\n")
24398 (forward-line)
24399 ;; Small correction if buffer doesn't end
24400 ;; with a newline character.
24401 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24402 (org-element-property :begin next-elem)))
24403 (size-blank (- (org-element-property :end elem)
24404 (save-excursion
24405 (goto-char (org-element-property :end elem))
24406 (skip-chars-backward " \r\t\n")
24407 (forward-line)
24408 (point)))))
24409 (org-element-swap-A-B elem next-elem)
24410 (goto-char (+ pos size-next size-blank))))))
24412 (defun org-drag-line-forward (arg)
24413 "Drag the line at point ARG lines forward."
24414 (interactive "p")
24415 (dotimes (_ (abs arg))
24416 (let ((c (current-column)))
24417 (if (< 0 arg)
24418 (progn
24419 (beginning-of-line 2)
24420 (transpose-lines 1)
24421 (beginning-of-line 0))
24422 (transpose-lines 1)
24423 (beginning-of-line -1))
24424 (org-move-to-column c))))
24426 (defun org-drag-line-backward (arg)
24427 "Drag the line at point ARG lines backward."
24428 (interactive "p")
24429 (org-drag-line-forward (- arg)))
24431 (defun org-mark-element ()
24432 "Put point at beginning of this element, mark at end.
24434 Interactively, if this command is repeated or (in Transient Mark
24435 mode) if the mark is active, it marks the next element after the
24436 ones already marked."
24437 (interactive)
24438 (let (deactivate-mark)
24439 (if (and (called-interactively-p 'any)
24440 (or (and (eq last-command this-command) (mark t))
24441 (and transient-mark-mode mark-active)))
24442 (set-mark
24443 (save-excursion
24444 (goto-char (mark))
24445 (goto-char (org-element-property :end (org-element-at-point)))))
24446 (let ((element (org-element-at-point)))
24447 (end-of-line)
24448 (push-mark (org-element-property :end element) t t)
24449 (goto-char (org-element-property :begin element))))))
24451 (defun org-narrow-to-element ()
24452 "Narrow buffer to current element."
24453 (interactive)
24454 (let ((elem (org-element-at-point)))
24455 (cond
24456 ((eq (car elem) 'headline)
24457 (narrow-to-region
24458 (org-element-property :begin elem)
24459 (org-element-property :end elem)))
24460 ((memq (car elem) org-element-greater-elements)
24461 (narrow-to-region
24462 (org-element-property :contents-begin elem)
24463 (org-element-property :contents-end elem)))
24465 (narrow-to-region
24466 (org-element-property :begin elem)
24467 (org-element-property :end elem))))))
24469 (defun org-transpose-element ()
24470 "Transpose current and previous elements, keeping blank lines between.
24471 Point is moved after both elements."
24472 (interactive)
24473 (org-skip-whitespace)
24474 (let ((end (org-element-property :end (org-element-at-point))))
24475 (org-drag-element-backward)
24476 (goto-char end)))
24478 (defun org-unindent-buffer ()
24479 "Un-indent the visible part of the buffer.
24480 Relative indentation (between items, inside blocks, etc.) isn't
24481 modified."
24482 (interactive)
24483 (unless (eq major-mode 'org-mode)
24484 (user-error "Cannot un-indent a buffer not in Org mode"))
24485 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24486 (unindent-tree
24487 (lambda (contents)
24488 (dolist (element (reverse contents))
24489 (if (memq (org-element-type element) '(headline section))
24490 (funcall unindent-tree (org-element-contents element))
24491 (save-excursion
24492 (save-restriction
24493 (narrow-to-region
24494 (org-element-property :begin element)
24495 (org-element-property :end element))
24496 (org-do-remove-indentation))))))))
24497 (funcall unindent-tree (org-element-contents parse-tree))))
24499 (defun org-show-children (&optional level)
24500 "Show all direct subheadings of this heading.
24501 Prefix arg LEVEL is how many levels below the current level
24502 should be shown. Default is enough to cause the following
24503 heading to appear."
24504 (interactive "p")
24505 ;; If `orgstruct-mode' is active, use the slower version.
24506 (if orgstruct-mode (call-interactively #'outline-show-children)
24507 (save-excursion
24508 (org-back-to-heading t)
24509 (let* ((current-level (funcall outline-level))
24510 (max-level (org-get-valid-level
24511 current-level
24512 (if level (prefix-numeric-value level) 1)))
24513 (end (save-excursion (org-end-of-subtree t t)))
24514 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24515 (past-first-child nil)
24516 ;; Make sure to skip inlinetasks.
24517 (re (format regexp-fmt
24518 current-level
24519 (cond
24520 ((not (featurep 'org-inlinetask)) "")
24521 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24523 (t (1- org-inlinetask-min-level))))))
24524 ;; Display parent heading.
24525 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24526 (forward-line)
24527 ;; Display children. First child may be deeper than expected
24528 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24529 ;; MAX-LEVEL accordingly.
24530 (while (re-search-forward re end t)
24531 (unless past-first-child
24532 (setq re (format regexp-fmt
24533 current-level
24534 (max (funcall outline-level) max-level)))
24535 (setq past-first-child t))
24536 (outline-flag-region
24537 (line-end-position 0) (line-end-position) nil))))))
24539 (defun org-show-subtree ()
24540 "Show everything after this heading at deeper levels."
24541 (interactive)
24542 (outline-flag-region
24543 (point)
24544 (save-excursion
24545 (org-end-of-subtree t t))
24546 nil))
24548 (defun org-show-entry ()
24549 "Show the body directly following this heading.
24550 Show the heading too, if it is currently invisible."
24551 (interactive)
24552 (save-excursion
24553 (ignore-errors
24554 (org-back-to-heading t)
24555 (outline-flag-region
24556 (max (point-min) (1- (point)))
24557 (save-excursion
24558 (if (re-search-forward
24559 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24560 (match-beginning 1)
24561 (point-max)))
24562 nil)
24563 (org-cycle-hide-drawers 'children))))
24565 (defun org-make-options-regexp (kwds &optional extra)
24566 "Make a regular expression for keyword lines.
24567 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24568 when non-nil, is a regexp matching keywords names."
24569 (concat "^[ \t]*#\\+\\("
24570 (regexp-opt kwds)
24571 (and extra (concat (and kwds "\\|") extra))
24572 "\\):[ \t]*\\(.*\\)"))
24574 ;;;; Integration with and fixes for other packages
24576 ;;; Imenu support
24578 (defvar-local org-imenu-markers nil
24579 "All markers currently used by Imenu.")
24581 (defun org-imenu-new-marker (&optional pos)
24582 "Return a new marker for use by Imenu, and remember the marker."
24583 (let ((m (make-marker)))
24584 (move-marker m (or pos (point)))
24585 (push m org-imenu-markers)
24588 (defun org-imenu-get-tree ()
24589 "Produce the index for Imenu."
24590 (dolist (x org-imenu-markers) (move-marker x nil))
24591 (setq org-imenu-markers nil)
24592 (let* ((case-fold-search nil)
24593 (n org-imenu-depth)
24594 (re (concat "^" (org-get-limited-outline-regexp)))
24595 (subs (make-vector (1+ n) nil))
24596 (last-level 0)
24597 m level head0 head)
24598 (org-with-wide-buffer
24599 (goto-char (point-max))
24600 (while (re-search-backward re nil t)
24601 (setq level (org-reduced-level (funcall outline-level)))
24602 (when (and (<= level n)
24603 (looking-at org-complex-heading-regexp)
24604 (setq head0 (match-string-no-properties 4)))
24605 (setq head (org-link-display-format head0)
24606 m (org-imenu-new-marker))
24607 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24608 (if (>= level last-level)
24609 (push (cons head m) (aref subs level))
24610 (push (cons head (aref subs (1+ level))) (aref subs level))
24611 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24612 (setq last-level level))))
24613 (aref subs 1)))
24615 (eval-after-load "imenu"
24616 '(progn
24617 (add-hook 'imenu-after-jump-hook
24618 (lambda ()
24619 (when (derived-mode-p 'org-mode)
24620 (org-show-context 'org-goto))))))
24622 (defun org-link-display-format (s)
24623 "Replace links in string S with their description.
24624 If there is no description, use the link target."
24625 (save-match-data
24626 (replace-regexp-in-string
24627 org-bracket-link-analytic-regexp
24628 (lambda (m)
24629 (if (match-end 5) (match-string 5 m)
24630 (concat (match-string 1 m) (match-string 3 m))))
24631 s nil t)))
24633 (defun org-toggle-link-display ()
24634 "Toggle the literal or descriptive display of links."
24635 (interactive)
24636 (if org-descriptive-links
24637 (progn (org-remove-from-invisibility-spec '(org-link))
24638 (org-restart-font-lock)
24639 (setq org-descriptive-links nil))
24640 (progn (add-to-invisibility-spec '(org-link))
24641 (org-restart-font-lock)
24642 (setq org-descriptive-links t))))
24644 ;; Speedbar support
24646 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24647 "Overlay marking the agenda restriction line in speedbar.")
24648 (overlay-put org-speedbar-restriction-lock-overlay
24649 'face 'org-agenda-restriction-lock)
24650 (overlay-put org-speedbar-restriction-lock-overlay
24651 'help-echo "Agendas are currently limited to this item.")
24652 (delete-overlay org-speedbar-restriction-lock-overlay)
24654 (defun org-speedbar-set-agenda-restriction ()
24655 "Restrict future agenda commands to the location at point in speedbar.
24656 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24657 (interactive)
24658 (require 'org-agenda)
24659 (let (p m tp np dir txt)
24660 (cond
24661 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24662 'org-imenu t))
24663 (setq m (get-text-property p 'org-imenu-marker))
24664 (with-current-buffer (marker-buffer m)
24665 (goto-char m)
24666 (org-agenda-set-restriction-lock 'subtree)))
24667 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24668 'speedbar-function 'speedbar-find-file))
24669 (setq tp (previous-single-property-change
24670 (1+ p) 'speedbar-function)
24671 np (next-single-property-change
24672 tp 'speedbar-function)
24673 dir (speedbar-line-directory)
24674 txt (buffer-substring-no-properties (or tp (point-min))
24675 (or np (point-max))))
24676 (with-current-buffer (find-file-noselect
24677 (let ((default-directory dir))
24678 (expand-file-name txt)))
24679 (unless (derived-mode-p 'org-mode)
24680 (user-error "Cannot restrict to non-Org mode file"))
24681 (org-agenda-set-restriction-lock 'file)))
24682 (t (user-error "Don't know how to restrict Org mode agenda")))
24683 (move-overlay org-speedbar-restriction-lock-overlay
24684 (point-at-bol) (point-at-eol))
24685 (setq current-prefix-arg nil)
24686 (org-agenda-maybe-redo)))
24688 (defvar speedbar-file-key-map)
24689 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24690 (eval-after-load "speedbar"
24691 '(progn
24692 (speedbar-add-supported-extension ".org")
24693 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24694 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24695 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24696 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24697 (add-hook 'speedbar-visiting-tag-hook
24698 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24700 ;;; Fixes and Hacks for problems with other packages
24702 (defun org--flyspell-object-check-p (element)
24703 "Non-nil when Flyspell can check object at point.
24704 ELEMENT is the element at point."
24705 (let ((object (save-excursion
24706 (when (looking-at-p "\\>") (backward-char))
24707 (org-element-context element))))
24708 (cl-case (org-element-type object)
24709 ;; Prevent checks in links due to keybinding conflict with
24710 ;; Flyspell.
24711 ((code entity export-snippet inline-babel-call
24712 inline-src-block line-break latex-fragment link macro
24713 statistics-cookie target timestamp verbatim)
24714 nil)
24715 (footnote-reference
24716 ;; Only in inline footnotes, within the definition.
24717 (and (eq (org-element-property :type object) 'inline)
24718 (< (save-excursion
24719 (goto-char (org-element-property :begin object))
24720 (search-forward ":" nil t 2))
24721 (point))))
24722 (otherwise t))))
24724 (defun org-mode-flyspell-verify ()
24725 "Function used for `flyspell-generic-check-word-predicate'."
24726 (if (org-at-heading-p)
24727 ;; At a headline or an inlinetask, check title only. This is
24728 ;; faster than relying on `org-element-at-point'.
24729 (and (save-excursion (beginning-of-line)
24730 (and (let ((case-fold-search t))
24731 (not (looking-at-p "\\*+ END[ \t]*$")))
24732 (let ((case-fold-search nil))
24733 (looking-at org-complex-heading-regexp))))
24734 (match-beginning 4)
24735 (>= (point) (match-beginning 4))
24736 (or (not (match-beginning 5))
24737 (< (point) (match-beginning 5))))
24738 (let* ((element (org-element-at-point))
24739 (post-affiliated (org-element-property :post-affiliated element)))
24740 (cond
24741 ;; Ignore checks in all affiliated keywords but captions.
24742 ((< (point) post-affiliated)
24743 (and (save-excursion
24744 (beginning-of-line)
24745 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24746 (> (point) (match-end 0))
24747 (org--flyspell-object-check-p element)))
24748 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24749 ((let ((log (org-log-into-drawer)))
24750 (and log
24751 (let ((drawer (org-element-lineage element '(drawer))))
24752 (and drawer
24753 (eq (compare-strings
24754 log nil nil
24755 (org-element-property :drawer-name drawer) nil nil t)
24756 t)))))
24757 nil)
24759 (cl-case (org-element-type element)
24760 ((comment quote-section) t)
24761 (comment-block
24762 ;; Allow checks between block markers, not on them.
24763 (and (> (line-beginning-position) post-affiliated)
24764 (save-excursion
24765 (end-of-line)
24766 (skip-chars-forward " \r\t\n")
24767 (< (point) (org-element-property :end element)))))
24768 ;; Arbitrary list of keywords where checks are meaningful.
24769 ;; Make sure point is on the value part of the element.
24770 (keyword
24771 (and (member (org-element-property :key element)
24772 '("DESCRIPTION" "TITLE"))
24773 (save-excursion
24774 (search-backward ":" (line-beginning-position) t))))
24775 ;; Check is globally allowed in paragraphs verse blocks and
24776 ;; table rows (after affiliated keywords) but some objects
24777 ;; must not be affected.
24778 ((paragraph table-row verse-block)
24779 (let ((cbeg (org-element-property :contents-begin element))
24780 (cend (org-element-property :contents-end element)))
24781 (and cbeg (>= (point) cbeg) (< (point) cend)
24782 (org--flyspell-object-check-p element))))))))))
24783 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24785 (defun org-remove-flyspell-overlays-in (beg end)
24786 "Remove flyspell overlays in region."
24787 (and (bound-and-true-p flyspell-mode)
24788 (fboundp 'flyspell-delete-region-overlays)
24789 (flyspell-delete-region-overlays beg end)))
24791 (defvar flyspell-delayed-commands)
24792 (eval-after-load "flyspell"
24793 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24795 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24796 (eval-after-load "bookmark"
24797 '(if (boundp 'bookmark-after-jump-hook)
24798 ;; We can use the hook
24799 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24800 ;; Hook not available, use advice
24801 (defadvice bookmark-jump (after org-make-visible activate)
24802 "Make the position visible."
24803 (org-bookmark-jump-unhide))))
24805 ;; Make sure saveplace shows the location if it was hidden
24806 (eval-after-load "saveplace"
24807 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24808 "Make the position visible."
24809 (org-bookmark-jump-unhide)))
24811 ;; Make sure ecb shows the location if it was hidden
24812 (eval-after-load "ecb"
24813 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24814 "Make hierarchy visible when jumping into location from ECB tree buffer."
24815 (when (derived-mode-p 'org-mode)
24816 (org-show-context))))
24818 (defun org-bookmark-jump-unhide ()
24819 "Unhide the current position, to show the bookmark location."
24820 (and (derived-mode-p 'org-mode)
24821 (or (org-invisible-p)
24822 (save-excursion (goto-char (max (point-min) (1- (point))))
24823 (org-invisible-p)))
24824 (org-show-context 'bookmark-jump)))
24826 (defun org-mark-jump-unhide ()
24827 "Make the point visible with `org-show-context' after jumping to the mark."
24828 (when (and (derived-mode-p 'org-mode)
24829 (org-invisible-p))
24830 (org-show-context 'mark-goto)))
24832 (eval-after-load "simple"
24833 '(defadvice pop-to-mark-command (after org-make-visible activate)
24834 "Make the point visible with `org-show-context'."
24835 (org-mark-jump-unhide)))
24837 (eval-after-load "simple"
24838 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24839 "Make the point visible with `org-show-context'."
24840 (org-mark-jump-unhide)))
24842 (eval-after-load "simple"
24843 '(defadvice pop-global-mark (after org-make-visible activate)
24844 "Make the point visible with `org-show-context'."
24845 (org-mark-jump-unhide)))
24847 ;; Make session.el ignore our circular variable
24848 (defvar session-globals-exclude)
24849 (eval-after-load "session"
24850 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24852 ;;;; Finish up
24854 (provide 'org)
24856 (run-hooks 'org-load-hook)
24858 ;;; org.el ends here