Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob621cc33f6f8149a67188d4c3972aac92ff029533
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function
133 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
134 (declare-function org-element-at-point "org-element" ())
135 (declare-function org-element-cache-refresh "org-element" (pos))
136 (declare-function org-element-cache-reset "org-element" (&optional all))
137 (declare-function org-element-contents "org-element" (element))
138 (declare-function org-element-context "org-element" (&optional element))
139 (declare-function org-element-copy "org-element" (datum))
140 (declare-function org-element-interpret-data "org-element" (data))
141 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
142 (declare-function org-element-link-parser "org-element" ())
143 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
144 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-put-property "org-element" (element property value))
147 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
148 (declare-function org-element-type "org-element" (element))
149 (declare-function org-element-update-syntax "org-element" ())
150 (declare-function org-id-find-id-file "org-id" (id))
151 (declare-function org-id-get-create "org-id" (&optional force))
152 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
153 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
154 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
155 (declare-function org-plot/gnuplot "org-plot" (&optional params))
156 (declare-function org-table-align "org-table" ())
157 (declare-function org-table-begin "org-table" (&optional table-type))
158 (declare-function org-table-beginning-of-field "org-table" (&optional n))
159 (declare-function org-table-blank-field "org-table" ())
160 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
161 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
162 (declare-function org-table-cut-region "org-table" (beg end))
163 (declare-function org-table-edit-field "org-table" (arg))
164 (declare-function org-table-end "org-table" (&optional table-type))
165 (declare-function org-table-end-of-field "org-table" (&optional n))
166 (declare-function org-table-insert-row "org-table" (&optional arg))
167 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
168 (declare-function org-table-maybe-eval-formula "org-table" ())
169 (declare-function org-table-maybe-recalculate-line "org-table" ())
170 (declare-function org-table-next-row "org-table" ())
171 (declare-function org-table-paste-rectangle "org-table" ())
172 (declare-function org-table-recalculate "org-table" (&optional all noalign))
173 (declare-function
174 org-table-sort-lines "org-table"
175 (&optional with-case sorting-type getkey-func compare-func interactive?))
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
180 (declare-function org-export-get-backend "ox" (name))
181 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
182 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
184 (defvar ffap-url-regexp) ;Silence byte-compiler
186 (defsubst org-uniquify (list)
187 "Non-destructively remove duplicate elements from LIST."
188 (let ((res (copy-sequence list))) (delete-dups res)))
190 (defsubst org-get-at-bol (property)
191 "Get text property PROPERTY at the beginning of line."
192 (get-text-property (point-at-bol) property))
194 (defsubst org-trim (s &optional keep-lead)
195 "Remove whitespace at the beginning and the end of string S.
196 When optional argument KEEP-LEAD is non-nil, removing blank lines
197 at the beginning of the string does not affect leading indentation."
198 (replace-regexp-in-string
199 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
200 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
202 ;; load languages based on value of `org-babel-load-languages'
203 (defvar org-babel-load-languages)
205 ;;;###autoload
206 (defun org-babel-do-load-languages (sym value)
207 "Load the languages defined in `org-babel-load-languages'."
208 (set-default sym value)
209 (dolist (pair org-babel-load-languages)
210 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
211 (if active
212 (require (intern (concat "ob-" lang)))
213 (funcall 'fmakunbound
214 (intern (concat "org-babel-execute:" lang)))
215 (funcall 'fmakunbound
216 (intern (concat "org-babel-expand-body:" lang)))))))
218 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
219 ;;;###autoload
220 (defun org-babel-load-file (file &optional compile)
221 "Load Emacs Lisp source code blocks in the Org FILE.
222 This function exports the source code using `org-babel-tangle'
223 and then loads the resulting file using `load-file'. With prefix
224 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
225 file to byte-code before it is loaded."
226 (interactive "fFile to load: \nP")
227 (let* ((age (lambda (file)
228 (float-time
229 (time-subtract (current-time)
230 (nth 5 (or (file-attributes (file-truename file))
231 (file-attributes file)))))))
232 (base-name (file-name-sans-extension file))
233 (exported-file (concat base-name ".el")))
234 ;; tangle if the Org file is newer than the elisp file
235 (unless (and (file-exists-p exported-file)
236 (> (funcall age file) (funcall age exported-file)))
237 ;; Tangle-file traversal returns reversed list of tangled files
238 ;; and we want to evaluate the first target.
239 (setq exported-file
240 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
248 (defcustom org-babel-load-languages '((emacs-lisp . t))
249 "Languages which can be evaluated in Org buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
268 (const :tag "Asymptote" asymptote)
269 (const :tag "Calc" calc)
270 (const :tag "Clojure" clojure)
271 (const :tag "CSS" css)
272 (const :tag "Ditaa" ditaa)
273 (const :tag "Dot" dot)
274 (const :tag "Emacs Lisp" emacs-lisp)
275 (const :tag "Forth" forth)
276 (const :tag "Fortran" fortran)
277 (const :tag "Gnuplot" gnuplot)
278 (const :tag "Haskell" haskell)
279 (const :tag "hledger" hledger)
280 (const :tag "IO" io)
281 (const :tag "J" J)
282 (const :tag "Java" java)
283 (const :tag "Javascript" js)
284 (const :tag "LaTeX" latex)
285 (const :tag "Ledger" ledger)
286 (const :tag "Lilypond" lilypond)
287 (const :tag "Lisp" lisp)
288 (const :tag "Makefile" makefile)
289 (const :tag "Maxima" maxima)
290 (const :tag "Matlab" matlab)
291 (const :tag "Mscgen" mscgen)
292 (const :tag "Ocaml" ocaml)
293 (const :tag "Octave" octave)
294 (const :tag "Org" org)
295 (const :tag "Perl" perl)
296 (const :tag "Pico Lisp" picolisp)
297 (const :tag "PlantUML" plantuml)
298 (const :tag "Python" python)
299 (const :tag "Ruby" ruby)
300 (const :tag "Sass" sass)
301 (const :tag "Scala" scala)
302 (const :tag "Scheme" scheme)
303 (const :tag "Screen" screen)
304 (const :tag "Shell Script" shell)
305 (const :tag "Shen" shen)
306 (const :tag "Sql" sql)
307 (const :tag "Sqlite" sqlite)
308 (const :tag "Stan" stan)
309 (const :tag "ebnf2ps" ebnf2ps))
310 :value-type (boolean :tag "Activate" :value t)))
312 ;;;; Customization variables
313 (defcustom org-clone-delete-id nil
314 "Remove ID property of clones of a subtree.
315 When non-nil, clones of a subtree don't inherit the ID property.
316 Otherwise they inherit the ID property with a new unique
317 identifier."
318 :type 'boolean
319 :version "24.1"
320 :group 'org-id)
322 ;;; Version
323 (org-check-version)
325 ;;;###autoload
326 (defun org-version (&optional here full message)
327 "Show the Org version.
328 Interactively, or when MESSAGE is non-nil, show it in echo area.
329 With prefix argument, or when HERE is non-nil, insert it at point.
330 In non-interactive uses, a reduced version string is output unless
331 FULL is given."
332 (interactive (list current-prefix-arg t (not current-prefix-arg)))
333 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
334 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
335 (load-suffixes (list ".el"))
336 (org-install-dir
337 (ignore-errors (org-find-library-dir "org-loaddefs"))))
338 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
339 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
340 (let* ((load-suffixes save-load-suffixes)
341 (release (org-release))
342 (git-version (org-git-version))
343 (version (format "Org mode version %s (%s @ %s)"
344 release
345 git-version
346 (if org-install-dir
347 (if (string= org-dir org-install-dir)
348 org-install-dir
349 (concat "mixed installation! "
350 org-install-dir
351 " and "
352 org-dir))
353 "org-loaddefs.el can not be found!")))
354 (version1 (if full version release)))
355 (when here (insert version1))
356 (when message (message "%s" version1))
357 version1)))
359 (defconst org-version (org-version))
362 ;;; Syntax Constants
364 ;;;; Block
366 (defconst org-block-regexp
367 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
368 "Regular expression for hiding blocks.")
370 (defconst org-dblock-start-re
371 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
372 "Matches the start line of a dynamic block, with parameters.")
374 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
375 "Matches the end of a dynamic block.")
377 ;;;; Clock and Planning
379 (defconst org-clock-string "CLOCK:"
380 "String used as prefix for timestamps clocking work hours on an item.")
382 (defvar org-closed-string "CLOSED:"
383 "String used as the prefix for timestamps logging closing a TODO entry.")
385 (defvar org-deadline-string "DEADLINE:"
386 "String to mark deadline entries.
387 \\<org-mode-map>
388 A deadline is this string, followed by a time stamp. It must be
389 a word, terminated by a colon. You can insert a schedule keyword
390 and a timestamp with `\\[org-deadline]'.")
392 (defvar org-scheduled-string "SCHEDULED:"
393 "String to mark scheduled TODO entries.
394 \\<org-mode-map>
395 A schedule is this string, followed by a time stamp. It must be
396 a word, terminated by a colon. You can insert a schedule keyword
397 and a timestamp with `\\[org-schedule]'.")
399 (defconst org-ds-keyword-length
400 (+ 2
401 (apply #'max
402 (mapcar #'length
403 (list org-deadline-string org-scheduled-string
404 org-clock-string org-closed-string))))
405 "Maximum length of the DEADLINE and SCHEDULED keywords.")
407 (defconst org-planning-line-re
408 (concat "^[ \t]*"
409 (regexp-opt
410 (list org-closed-string org-deadline-string org-scheduled-string)
412 "Matches a line with planning info.
413 Matched keyword is in group 1.")
415 (defconst org-clock-line-re
416 (concat "^[ \t]*" org-clock-string)
417 "Matches a line with clock info.")
419 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
420 "Matches the DEADLINE keyword.")
422 (defconst org-deadline-time-regexp
423 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
424 "Matches the DEADLINE keyword together with a time stamp.")
426 (defconst org-deadline-time-hour-regexp
427 (concat "\\<" org-deadline-string
428 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
429 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
431 (defconst org-deadline-line-regexp
432 (concat "\\<\\(" org-deadline-string "\\).*")
433 "Matches the DEADLINE keyword and the rest of the line.")
435 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
436 "Matches the SCHEDULED keyword.")
438 (defconst org-scheduled-time-regexp
439 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
440 "Matches the SCHEDULED keyword together with a time stamp.")
442 (defconst org-scheduled-time-hour-regexp
443 (concat "\\<" org-scheduled-string
444 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
445 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
447 (defconst org-closed-time-regexp
448 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
449 "Matches the CLOSED keyword together with a time stamp.")
451 (defconst org-keyword-time-regexp
452 (concat "\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string
455 org-clock-string)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 4 keywords, together with the time stamp.")
460 (defconst org-keyword-time-not-clock-regexp
461 (concat
462 "\\<"
463 (regexp-opt
464 (list org-scheduled-string org-deadline-string org-closed-string) t)
465 " *[[<]\\([^]>]+\\)[]>]")
466 "Matches any of the 3 keywords, together with the time stamp.")
468 (defconst org-maybe-keyword-time-regexp
469 (concat "\\(\\<"
470 (regexp-opt
471 (list org-scheduled-string org-deadline-string org-closed-string
472 org-clock-string)
474 "\\)?"
475 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
476 "\\|"
477 "<%%([^\r\n>]*>\\)")
478 "Matches a timestamp, possibly preceded by a keyword.")
480 (defconst org-all-time-keywords
481 (mapcar (lambda (w) (substring w 0 -1))
482 (list org-scheduled-string org-deadline-string
483 org-clock-string org-closed-string))
484 "List of time keywords.")
486 ;;;; Drawer
488 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
489 "Matches first or last line of a hidden block.
490 Group 1 contains drawer's name or \"END\".")
492 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
493 "Regular expression matching the first line of a property drawer.")
495 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
496 "Regular expression matching the last line of a property drawer.")
498 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
499 "Regular expression matching the first line of a clock drawer.")
501 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
502 "Regular expression matching the last line of a clock drawer.")
504 (defconst org-property-drawer-re
505 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
506 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
507 "[ \t]*:END:[ \t]*$")
508 "Matches an entire property drawer.")
510 (defconst org-clock-drawer-re
511 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
512 org-clock-drawer-end-re "\\)\n?")
513 "Matches an entire clock drawer.")
515 ;;;; Headline
517 (defconst org-heading-keyword-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline with some keyword.
520 This regexp will match the headline of any node which has the
521 exact keyword that is put into the format. The keyword isn't in
522 any group by default, but the stars and the body are.")
524 (defconst org-heading-keyword-maybe-regexp-format
525 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
526 "Printf format for a regexp matching a headline, possibly with some keyword.
527 This regexp can match any headline with the specified keyword, or
528 without a keyword. The keyword isn't in any group by default,
529 but the stars and the body are.")
531 (defconst org-archive-tag "ARCHIVE"
532 "The tag that marks a subtree as archived.
533 An archived subtree does not open during visibility cycling, and does
534 not contribute to the agenda listings.")
536 (eval-and-compile
537 (defconst org-comment-string "COMMENT"
538 "Entries starting with this keyword will never be exported.
539 \\<org-mode-map>
540 An entry can be toggled between COMMENT and normal with
541 `\\[org-toggle-comment]'."))
544 ;;;; LaTeX Environments and Fragments
546 (defconst org-latex-regexps
547 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
548 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
549 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
550 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
551 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
552 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
553 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
554 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
555 "Regular expressions for matching embedded LaTeX.")
557 ;;;; Node Property
559 (defconst org-effort-property "Effort"
560 "The property that is being used to keep track of effort estimates.
561 Effort estimates given in this property need to have the format H:MM.")
563 ;;;; Table
565 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
566 "Detect an org-type or table-type table.")
568 (defconst org-table-line-regexp "^[ \t]*|"
569 "Detect an org-type table line.")
571 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
572 "Detect an org-type table line.")
574 (defconst org-table-hline-regexp "^[ \t]*|-"
575 "Detect an org-type table hline.")
577 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
578 "Detect a table-type table hline.")
580 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
581 "Detect the first line outside a table when searching from within it.
582 This works for both table types.")
584 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
585 "Detect a #+TBLFM line.")
587 ;;;; Timestamp
589 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
590 "Regular expression for fast time stamp matching.")
592 (defconst org-ts-regexp-inactive
593 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
594 "Regular expression for fast inactive time stamp matching.")
596 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
597 "Regular expression for fast time stamp matching.")
599 (defconst org-ts-regexp0
600 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
601 "Regular expression matching time strings for analysis.
602 This one does not require the space after the date, so it can be used
603 on a string that terminates immediately after the date.")
605 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
606 "Regular expression matching time strings for analysis.")
608 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
609 "Regular expression matching time stamps, with groups.")
611 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
612 "Regular expression matching time stamps (also [..]), with groups.")
614 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
615 "Regular expression matching a time stamp range.")
617 (defconst org-tr-regexp-both
618 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
622 org-ts-regexp "\\)?")
623 "Regular expression matching a time stamp or time stamp range.")
625 (defconst org-tsr-regexp-both
626 (concat org-ts-regexp-both "\\(--?-?"
627 org-ts-regexp-both "\\)?")
628 "Regular expression matching a time stamp or time stamp range.
629 The time stamps may be either active or inactive.")
631 (defconst org-repeat-re
632 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
633 "Regular expression for specifying repeated events.
634 After a match, group 1 contains the repeat expression.")
636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
637 "Formats for `format-time-string' which are used for time stamps.")
640 ;;; The custom variables
642 (defgroup org nil
643 "Outline-based notes management and organizer."
644 :tag "Org"
645 :group 'outlines
646 :group 'calendar)
648 (defcustom org-mode-hook nil
649 "Mode hook for Org mode, run after the mode was turned on."
650 :group 'org
651 :type 'hook)
653 (defcustom org-load-hook nil
654 "Hook that is run after org.el has been loaded."
655 :group 'org
656 :type 'hook)
658 (defcustom org-log-buffer-setup-hook nil
659 "Hook that is run after an Org log buffer is created."
660 :group 'org
661 :version "24.1"
662 :type 'hook)
664 (defvar org-modules) ; defined below
665 (defvar org-modules-loaded nil
666 "Have the modules been loaded already?")
668 (defun org-load-modules-maybe (&optional force)
669 "Load all extensions listed in `org-modules'."
670 (when (or force (not org-modules-loaded))
671 (dolist (ext org-modules)
672 (condition-case nil (require ext)
673 (error (message "Problems while trying to load feature `%s'" ext))))
674 (setq org-modules-loaded t)))
676 (defun org-set-modules (var value)
677 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
678 (set var value)
679 (when (featurep 'org)
680 (org-load-modules-maybe 'force)
681 (org-element-cache-reset 'all)))
683 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
684 "Modules that should always be loaded together with org.el.
686 If a description starts with <C>, the file is not part of Emacs
687 and loading it will require that you have downloaded and properly
688 installed the Org mode distribution.
690 You can also use this system to load external packages (i.e. neither Org
691 core modules, nor modules from the CONTRIB directory). Just add symbols
692 to the end of the list. If the package is called org-xyz.el, then you need
693 to add the symbol `xyz', and the package must have a call to:
695 (provide \\='org-xyz)
697 For export specific modules, see also `org-export-backends'."
698 :group 'org
699 :set 'org-set-modules
700 :version "24.4"
701 :package-version '(Org . "8.0")
702 :type
703 '(set :greedy t
704 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
705 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
706 (const :tag " crypt: Encryption of subtrees" org-crypt)
707 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
708 (const :tag " docview: Links to doc-view buffers" org-docview)
709 (const :tag " eww: Store link to url of eww" org-eww)
710 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
711 (const :tag " habit: Track your consistency with habits" org-habit)
712 (const :tag " id: Global IDs for identifying entries" org-id)
713 (const :tag " info: Links to Info nodes" org-info)
714 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
715 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
716 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
717 (const :tag " mouse: Additional mouse support" org-mouse)
718 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
719 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
720 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
722 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
723 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
724 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
725 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
726 (const :tag "C collector: Collect properties into tables" org-collector)
727 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
728 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
729 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
730 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
731 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
732 (const :tag "C eval: Include command output as text" org-eval)
733 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
734 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
735 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
736 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
737 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
738 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
739 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
740 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
741 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
742 (const :tag "C man: Support for links to manpages in Org mode" org-man)
743 (const :tag "C mew: Links to Mew folders/messages" org-mew)
744 (const :tag "C mtags: Support for muse-like tags" org-mtags)
745 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
746 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
747 (const :tag "C registry: A registry for Org links" org-registry)
748 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
749 (const :tag "C secretary: Team management with org-mode" org-secretary)
750 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
751 (const :tag "C toc: Table of contents for Org buffer" org-toc)
752 (const :tag "C track: Keep up with Org mode development" org-track)
753 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
754 (const :tag "C vm: Links to VM folders/messages" org-vm)
755 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
756 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
757 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
759 (defvar org-export-registered-backends) ; From ox.el.
760 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
761 (declare-function org-export-backend-name "ox" (backend) t)
762 (defcustom org-export-backends '(ascii html icalendar latex odt)
763 "List of export back-ends that should be always available.
765 If a description starts with <C>, the file is not part of Emacs
766 and loading it will require that you have downloaded and properly
767 installed the Org mode distribution.
769 Unlike to `org-modules', libraries in this list will not be
770 loaded along with Org, but only once the export framework is
771 needed.
773 This variable needs to be set before org.el is loaded. If you
774 need to make a change while Emacs is running, use the customize
775 interface or run the following code, where VAL stands for the new
776 value of the variable, after updating it:
778 (progn
779 (setq org-export-registered-backends
780 (cl-remove-if-not
781 (lambda (backend)
782 (let ((name (org-export-backend-name backend)))
783 (or (memq name val)
784 (catch \\='parentp
785 (dolist (b val)
786 (and (org-export-derived-backend-p b name)
787 (throw \\='parentp t)))))))
788 org-export-registered-backends))
789 (let ((new-list (mapcar #\\='org-export-backend-name
790 org-export-registered-backends)))
791 (dolist (backend val)
792 (cond
793 ((not (load (format \"ox-%s\" backend) t t))
794 (message \"Problems while trying to load export back-end \\=`%s\\='\"
795 backend))
796 ((not (memq backend new-list)) (push backend new-list))))
797 (set-default \\='org-export-backends new-list)))
799 Adding a back-end to this list will also pull the back-end it
800 depends on, if any."
801 :group 'org
802 :group 'org-export
803 :version "26.1"
804 :package-version '(Org . "9.0")
805 :initialize 'custom-initialize-set
806 :set (lambda (var val)
807 (if (not (featurep 'ox)) (set-default var val)
808 ;; Any back-end not required anymore (not present in VAL and not
809 ;; a parent of any back-end in the new value) is removed from the
810 ;; list of registered back-ends.
811 (setq org-export-registered-backends
812 (cl-remove-if-not
813 (lambda (backend)
814 (let ((name (org-export-backend-name backend)))
815 (or (memq name val)
816 (catch 'parentp
817 (dolist (b val)
818 (and (org-export-derived-backend-p b name)
819 (throw 'parentp t)))))))
820 org-export-registered-backends))
821 ;; Now build NEW-LIST of both new back-ends and required
822 ;; parents.
823 (let ((new-list (mapcar #'org-export-backend-name
824 org-export-registered-backends)))
825 (dolist (backend val)
826 (cond
827 ((not (load (format "ox-%s" backend) t t))
828 (message "Problems while trying to load export back-end `%s'"
829 backend))
830 ((not (memq backend new-list)) (push backend new-list))))
831 ;; Set VAR to that list with fixed dependencies.
832 (set-default var new-list))))
833 :type '(set :greedy t
834 (const :tag " ascii Export buffer to ASCII format" ascii)
835 (const :tag " beamer Export buffer to Beamer presentation" beamer)
836 (const :tag " html Export buffer to HTML format" html)
837 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
838 (const :tag " latex Export buffer to LaTeX format" latex)
839 (const :tag " man Export buffer to MAN format" man)
840 (const :tag " md Export buffer to Markdown format" md)
841 (const :tag " odt Export buffer to ODT format" odt)
842 (const :tag " org Export buffer to Org format" org)
843 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
844 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
845 (const :tag "C deck Export buffer to deck.js presentations" deck)
846 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
847 (const :tag "C groff Export buffer to Groff format" groff)
848 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
849 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
850 (const :tag "C s5 Export buffer to s5 presentations" s5)
851 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
853 (eval-after-load 'ox
854 '(dolist (backend org-export-backends)
855 (condition-case nil (require (intern (format "ox-%s" backend)))
856 (error (message "Problems while trying to load export back-end `%s'"
857 backend)))))
859 (defcustom org-support-shift-select nil
860 "Non-nil means make shift-cursor commands select text when possible.
861 \\<org-mode-map>\
863 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
864 start selecting a region, or enlarge regions started in this way.
865 In Org mode, in special contexts, these same keys are used for
866 other purposes, important enough to compete with shift selection.
867 Org tries to balance these needs by supporting `shift-select-mode'
868 outside these special contexts, under control of this variable.
870 The default of this variable is nil, to avoid confusing behavior. Shifted
871 cursor keys will then execute Org commands in the following contexts:
872 - on a headline, changing TODO state (left/right) and priority (up/down)
873 - on a time stamp, changing the time
874 - in a plain list item, changing the bullet type
875 - in a property definition line, switching between allowed values
876 - in the BEGIN line of a clock table (changing the time block).
877 Outside these contexts, the commands will throw an error.
879 When this variable is t and the cursor is not in a special
880 context, Org mode will support shift-selection for making and
881 enlarging regions. To make this more effective, the bullet
882 cycling will no longer happen anywhere in an item line, but only
883 if the cursor is exactly on the bullet.
885 If you set this variable to the symbol `always', then the keys
886 will not be special in headlines, property lines, and item lines,
887 to make shift selection work there as well. If this is what you
888 want, you can use the following alternative commands:
889 `\\[org-todo]' and `\\[org-priority]' \
890 to change TODO state and priority,
891 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
892 can be used to switch TODO sets,
893 `\\[org-ctrl-c-minus]' to cycle item bullet types,
894 and properties can be edited by hand or in column view.
896 However, when the cursor is on a timestamp, shift-cursor commands
897 will still edit the time stamp - this is just too good to give up."
898 :group 'org
899 :type '(choice
900 (const :tag "Never" nil)
901 (const :tag "When outside special context" t)
902 (const :tag "Everywhere except timestamps" always)))
904 (defcustom org-loop-over-headlines-in-active-region nil
905 "Shall some commands act upon headlines in the active region?
907 When set to t, some commands will be performed in all headlines
908 within the active region.
910 When set to `start-level', some commands will be performed in all
911 headlines within the active region, provided that these headlines
912 are of the same level than the first one.
914 When set to a string, those commands will be performed on the
915 matching headlines within the active region. Such string must be
916 a tags/property/todo match as it is used in the agenda tags view.
918 The list of commands is: `org-schedule', `org-deadline',
919 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
920 `org-archive-to-archive-sibling'. The archiving commands skip
921 already archived entries."
922 :type '(choice (const :tag "Don't loop" nil)
923 (const :tag "All headlines in active region" t)
924 (const :tag "In active region, headlines at the same level than the first one" start-level)
925 (string :tag "Tags/Property/Todo matcher"))
926 :version "24.1"
927 :group 'org-todo
928 :group 'org-archive)
930 (defgroup org-startup nil
931 "Options concerning startup of Org mode."
932 :tag "Org Startup"
933 :group 'org)
935 (defcustom org-startup-folded t
936 "Non-nil means entering Org mode will switch to OVERVIEW.
938 This can also be configured on a per-file basis by adding one of
939 the following lines anywhere in the buffer:
941 #+STARTUP: fold (or `overview', this is equivalent)
942 #+STARTUP: nofold (or `showall', this is equivalent)
943 #+STARTUP: content
944 #+STARTUP: showeverything
946 Set `org-agenda-inhibit-startup' to a non-nil value if you want
947 to ignore this option when Org opens agenda files for the first
948 time."
949 :group 'org-startup
950 :type '(choice
951 (const :tag "nofold: show all" nil)
952 (const :tag "fold: overview" t)
953 (const :tag "content: all headlines" content)
954 (const :tag "show everything, even drawers" showeverything)))
956 (defcustom org-startup-truncated t
957 "Non-nil means entering Org mode will set `truncate-lines'.
958 This is useful since some lines containing links can be very long and
959 uninteresting. Also tables look terrible when wrapped.
961 The variable `org-startup-truncated' allows to configure
962 truncation for Org mode different to the other modes that use the
963 variable `truncate-lines' and as a shortcut instead of putting
964 the variable `truncate-lines' into the `org-mode-hook'. If one
965 wants to configure truncation for Org mode not statically but
966 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
967 the variable `truncate-lines' has to be used because in such a
968 case it is too late to set the variable `org-startup-truncated'."
969 :group 'org-startup
970 :type 'boolean)
972 (defcustom org-startup-indented nil
973 "Non-nil means turn on `org-indent-mode' on startup.
974 This can also be configured on a per-file basis by adding one of
975 the following lines anywhere in the buffer:
977 #+STARTUP: indent
978 #+STARTUP: noindent"
979 :group 'org-structure
980 :type '(choice
981 (const :tag "Not" nil)
982 (const :tag "Globally (slow on startup in large files)" t)))
984 (defcustom org-use-sub-superscripts t
985 "Non-nil means interpret \"_\" and \"^\" for display.
987 If you want to control how Org exports those characters, see
988 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
989 used to be an alias for `org-export-with-sub-superscripts' in
990 Org <8.0, it is not anymore.
992 When this option is turned on, you can use TeX-like syntax for
993 sub- and superscripts within the buffer. Several characters after
994 \"_\" or \"^\" will be considered as a single item - so grouping
995 with {} is normally not needed. For example, the following things
996 will be parsed as single sub- or superscripts:
998 10^24 or 10^tau several digits will be considered 1 item.
999 10^-12 or 10^-tau a leading sign with digits or a word
1000 x^2-y^3 will be read as x^2 - y^3, because items are
1001 terminated by almost any nonword/nondigit char.
1002 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1004 Still, ambiguity is possible. So when in doubt, use {} to enclose
1005 the sub/superscript. If you set this variable to the symbol `{}',
1006 the braces are *required* in order to trigger interpretations as
1007 sub/superscript. This can be helpful in documents that need \"_\"
1008 frequently in plain text."
1009 :group 'org-startup
1010 :version "24.4"
1011 :package-version '(Org . "8.0")
1012 :type '(choice
1013 (const :tag "Always interpret" t)
1014 (const :tag "Only with braces" {})
1015 (const :tag "Never interpret" nil)))
1017 (defcustom org-startup-with-beamer-mode nil
1018 "Non-nil means turn on `org-beamer-mode' on startup.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1022 #+STARTUP: beamer"
1023 :group 'org-startup
1024 :version "24.1"
1025 :type 'boolean)
1027 (defcustom org-startup-align-all-tables nil
1028 "Non-nil means align all tables when visiting a file.
1029 This is useful when the column width in tables is forced with <N> cookies
1030 in table fields. Such tables will look correct only after the first re-align.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: align
1034 #+STARTUP: noalign"
1035 :group 'org-startup
1036 :type 'boolean)
1038 (defcustom org-startup-with-inline-images nil
1039 "Non-nil means show inline images when loading a new Org file.
1040 This can also be configured on a per-file basis by adding one of
1041 the following lines anywhere in the buffer:
1042 #+STARTUP: inlineimages
1043 #+STARTUP: noinlineimages"
1044 :group 'org-startup
1045 :version "24.1"
1046 :type 'boolean)
1048 (defcustom org-startup-with-latex-preview nil
1049 "Non-nil means preview LaTeX fragments when loading a new Org file.
1051 This can also be configured on a per-file basis by adding one of
1052 the following lines anywhere in the buffer:
1053 #+STARTUP: latexpreview
1054 #+STARTUP: nolatexpreview"
1055 :group 'org-startup
1056 :version "24.4"
1057 :package-version '(Org . "8.0")
1058 :type 'boolean)
1060 (defcustom org-insert-mode-line-in-empty-file nil
1061 "Non-nil means insert the first line setting Org mode in empty files.
1062 When the function `org-mode' is called interactively in an empty file, this
1063 normally means that the file name does not automatically trigger Org mode.
1064 To ensure that the file will always be in Org mode in the future, a
1065 line enforcing Org mode will be inserted into the buffer, if this option
1066 has been set."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-replace-disputed-keys nil
1071 "Non-nil means use alternative key bindings for some keys.
1072 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1073 These keys are also used by other packages like shift-selection-mode'
1074 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1075 If you want to use Org mode together with one of these other modes,
1076 or more generally if you would like to move some Org mode commands to
1077 other keys, set this variable and configure the keys with the variable
1078 `org-disputed-keys'.
1080 This option is only relevant at load-time of Org mode, and must be set
1081 *before* org.el is loaded. Changing it requires a restart of Emacs to
1082 become effective."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defcustom org-use-extra-keys nil
1087 "Non-nil means use extra key sequence definitions for certain commands.
1088 This happens automatically if `window-system' is nil. This
1089 variable lets you do the same manually. You must set it before
1090 loading Org."
1091 :group 'org-startup
1092 :type 'boolean)
1094 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1096 (defcustom org-disputed-keys
1097 '(([(shift up)] . [(meta p)])
1098 ([(shift down)] . [(meta n)])
1099 ([(shift left)] . [(meta -)])
1100 ([(shift right)] . [(meta +)])
1101 ([(control shift right)] . [(meta shift +)])
1102 ([(control shift left)] . [(meta shift -)]))
1103 "Keys for which Org mode and other modes compete.
1104 This is an alist, cars are the default keys, second element specifies
1105 the alternative to use when `org-replace-disputed-keys' is t.
1107 Keys can be specified in any syntax supported by `define-key'.
1108 The value of this option takes effect only at Org mode startup,
1109 therefore you'll have to restart Emacs to apply it after changing."
1110 :group 'org-startup
1111 :type 'alist)
1113 (defun org-key (key)
1114 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1115 Or return the original if not disputed."
1116 (when org-replace-disputed-keys
1117 (let* ((nkey (key-description key))
1118 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1119 org-disputed-keys)))
1120 (setq key (if x (cdr x) key))))
1121 key)
1123 (defun org-defkey (keymap key def)
1124 "Define a key, possibly translated, as returned by `org-key'."
1125 (define-key keymap (org-key key) def))
1127 (defcustom org-ellipsis nil
1128 "The ellipsis to use in the Org mode outline.
1130 When nil, just use the standard three dots. When a non-empty string,
1131 use that string instead.
1133 The change affects only Org mode (which will then use its own display table).
1134 Changing this requires executing `\\[org-mode]' in a buffer to become
1135 effective."
1136 :group 'org-startup
1137 :type '(choice (const :tag "Default" nil)
1138 (string :tag "String" :value "...#"))
1139 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1141 (defvar org-display-table nil
1142 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1144 (defgroup org-keywords nil
1145 "Keywords in Org mode."
1146 :tag "Org Keywords"
1147 :group 'org)
1149 (defcustom org-closed-keep-when-no-todo nil
1150 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1151 :group 'org-todo
1152 :group 'org-keywords
1153 :version "24.4"
1154 :package-version '(Org . "8.0")
1155 :type 'boolean)
1157 (defgroup org-structure nil
1158 "Options concerning the general structure of Org files."
1159 :tag "Org Structure"
1160 :group 'org)
1162 (defgroup org-reveal-location nil
1163 "Options about how to make context of a location visible."
1164 :tag "Org Reveal Location"
1165 :group 'org-structure)
1167 (defcustom org-show-context-detail '((agenda . local)
1168 (bookmark-jump . lineage)
1169 (isearch . lineage)
1170 (default . ancestors))
1171 "Alist between context and visibility span when revealing a location.
1173 \\<org-mode-map>Some actions may move point into invisible
1174 locations. As a consequence, Org always expose a neighborhood
1175 around point. How much is shown depends on the initial action,
1176 or context. Valid contexts are
1178 agenda when exposing an entry from the agenda
1179 org-goto when using the command `org-goto' (`\\[org-goto]')
1180 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1181 tags-tree when constructing a sparse tree based on tags matches
1182 link-search when exposing search matches associated with a link
1183 mark-goto when exposing the jump goal of a mark
1184 bookmark-jump when exposing a bookmark location
1185 isearch when exiting from an incremental search
1186 default default for all contexts not set explicitly
1188 Allowed visibility spans are
1190 minimal show current headline; if point is not on headline,
1191 also show entry
1193 local show current headline, entry and next headline
1195 ancestors show current headline and its direct ancestors; if
1196 point is not on headline, also show entry
1198 lineage show current headline, its direct ancestors and all
1199 their children; if point is not on headline, also show
1200 entry and first child
1202 tree show current headline, its direct ancestors and all
1203 their children; if point is not on headline, also show
1204 entry and all children
1206 canonical show current headline, its direct ancestors along with
1207 their entries and children; if point is not located on
1208 the headline, also show current entry and all children
1210 As special cases, a nil or t value means show all contexts in
1211 `minimal' or `canonical' view, respectively.
1213 Some views can make displayed information very compact, but also
1214 make it harder to edit the location of the match. In such
1215 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1216 more context."
1217 :group 'org-reveal-location
1218 :version "26.1"
1219 :package-version '(Org . "9.0")
1220 :type '(choice
1221 (const :tag "Canonical" t)
1222 (const :tag "Minimal" nil)
1223 (repeat :greedy t :tag "Individual contexts"
1224 (cons
1225 (choice :tag "Context"
1226 (const agenda)
1227 (const org-goto)
1228 (const occur-tree)
1229 (const tags-tree)
1230 (const link-search)
1231 (const mark-goto)
1232 (const bookmark-jump)
1233 (const isearch)
1234 (const default))
1235 (choice :tag "Detail level"
1236 (const minimal)
1237 (const local)
1238 (const ancestors)
1239 (const lineage)
1240 (const tree)
1241 (const canonical))))))
1243 (defcustom org-indirect-buffer-display 'other-window
1244 "How should indirect tree buffers be displayed?
1246 This applies to indirect buffers created with the commands
1247 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1249 Valid values are:
1250 current-window Display in the current window
1251 other-window Just display in another window.
1252 dedicated-frame Create one new frame, and re-use it each time.
1253 new-frame Make a new frame each time. Note that in this case
1254 previously-made indirect buffers are kept, and you need to
1255 kill these buffers yourself."
1256 :group 'org-structure
1257 :group 'org-agenda-windows
1258 :type '(choice
1259 (const :tag "In current window" current-window)
1260 (const :tag "In current frame, other window" other-window)
1261 (const :tag "Each time a new frame" new-frame)
1262 (const :tag "One dedicated frame" dedicated-frame)))
1264 (defcustom org-use-speed-commands nil
1265 "Non-nil means activate single letter commands at beginning of a headline.
1266 This may also be a function to test for appropriate locations where speed
1267 commands should be active.
1269 For example, to activate speed commands when the point is on any
1270 star at the beginning of the headline, you can do this:
1272 (setq org-use-speed-commands
1273 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1274 :group 'org-structure
1275 :type '(choice
1276 (const :tag "Never" nil)
1277 (const :tag "At beginning of headline stars" t)
1278 (function)))
1280 (defcustom org-speed-commands-user nil
1281 "Alist of additional speed commands.
1282 This list will be checked before `org-speed-commands-default'
1283 when the variable `org-use-speed-commands' is non-nil
1284 and when the cursor is at the beginning of a headline.
1285 The car if each entry is a string with a single letter, which must
1286 be assigned to `self-insert-command' in the global map.
1287 The cdr is either a command to be called interactively, a function
1288 to be called, or a form to be evaluated.
1289 An entry that is just a list with a single string will be interpreted
1290 as a descriptive headline that will be added when listing the speed
1291 commands in the Help buffer using the `?' speed command."
1292 :group 'org-structure
1293 :type '(repeat :value ("k" . ignore)
1294 (choice :value ("k" . ignore)
1295 (list :tag "Descriptive Headline" (string :tag "Headline"))
1296 (cons :tag "Letter and Command"
1297 (string :tag "Command letter")
1298 (choice
1299 (function)
1300 (sexp))))))
1302 (defcustom org-bookmark-names-plist
1303 '(:last-capture "org-capture-last-stored"
1304 :last-refile "org-refile-last-stored"
1305 :last-capture-marker "org-capture-last-stored-marker")
1306 "Names for bookmarks automatically set by some Org commands.
1307 This can provide strings as names for a number of bookmarks Org sets
1308 automatically. The following keys are currently implemented:
1309 :last-capture
1310 :last-capture-marker
1311 :last-refile
1312 When a key does not show up in the property list, the corresponding bookmark
1313 is not set."
1314 :group 'org-structure
1315 :type 'plist)
1317 (defgroup org-cycle nil
1318 "Options concerning visibility cycling in Org mode."
1319 :tag "Org Cycle"
1320 :group 'org-structure)
1322 (defcustom org-cycle-skip-children-state-if-no-children t
1323 "Non-nil means skip CHILDREN state in entries that don't have any."
1324 :group 'org-cycle
1325 :type 'boolean)
1327 (defcustom org-cycle-max-level nil
1328 "Maximum level which should still be subject to visibility cycling.
1329 Levels higher than this will, for cycling, be treated as text, not a headline.
1330 When `org-odd-levels-only' is set, a value of N in this variable actually
1331 means 2N-1 stars as the limiting headline.
1332 When nil, cycle all levels.
1333 Note that the limiting level of cycling is also influenced by
1334 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1335 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1336 than its value."
1337 :group 'org-cycle
1338 :type '(choice
1339 (const :tag "No limit" nil)
1340 (integer :tag "Maximum level")))
1342 (defcustom org-hide-block-startup nil
1343 "Non-nil means entering Org mode will fold all blocks.
1344 This can also be set in on a per-file basis with
1346 #+STARTUP: hideblocks
1347 #+STARTUP: showblocks"
1348 :group 'org-startup
1349 :group 'org-cycle
1350 :type 'boolean)
1352 (defcustom org-cycle-global-at-bob nil
1353 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1355 This makes it possible to do global cycling without having to use `S-TAB'
1356 or `\\[universal-argument] TAB'. For this special case to work, the first \
1357 line of the buffer
1358 must not be a headline -- it may be empty or some other text.
1360 When used in this way, `org-cycle-hook' is disabled temporarily to make
1361 sure the cursor stays at the beginning of the buffer.
1363 When this option is nil, don't do anything special at the beginning of
1364 the buffer."
1365 :group 'org-cycle
1366 :type 'boolean)
1368 (defcustom org-cycle-level-after-item/entry-creation t
1369 "Non-nil means cycle entry level or item indentation in new empty entries.
1371 When the cursor is at the end of an empty headline, i.e., with only stars
1372 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1373 and then all possible ancestor states, before returning to the original state.
1374 This makes data entry extremely fast: M-RET to create a new headline,
1375 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1377 When the cursor is at the end of an empty plain list item, one TAB will
1378 make it a subitem, two or more tabs will back up to make this an item
1379 higher up in the item hierarchy."
1380 :group 'org-cycle
1381 :type 'boolean)
1383 (defcustom org-cycle-emulate-tab t
1384 "Where should `org-cycle' emulate TAB.
1385 nil Never
1386 white Only in completely white lines
1387 whitestart Only at the beginning of lines, before the first non-white char
1388 t Everywhere except in headlines
1389 exc-hl-bol Everywhere except at the start of a headline
1390 If TAB is used in a place where it does not emulate TAB, the current subtree
1391 visibility is cycled."
1392 :group 'org-cycle
1393 :type '(choice (const :tag "Never" nil)
1394 (const :tag "Only in completely white lines" white)
1395 (const :tag "Before first char in a line" whitestart)
1396 (const :tag "Everywhere except in headlines" t)
1397 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1399 (defcustom org-cycle-separator-lines 2
1400 "Number of empty lines needed to keep an empty line between collapsed trees.
1401 If you leave an empty line between the end of a subtree and the following
1402 headline, this empty line is hidden when the subtree is folded.
1403 Org mode will leave (exactly) one empty line visible if the number of
1404 empty lines is equal or larger to the number given in this variable.
1405 So the default 2 means at least 2 empty lines after the end of a subtree
1406 are needed to produce free space between a collapsed subtree and the
1407 following headline.
1409 If the number is negative, and the number of empty lines is at least -N,
1410 all empty lines are shown.
1412 Special case: when 0, never leave empty lines in collapsed view."
1413 :group 'org-cycle
1414 :type 'integer)
1415 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1417 (defcustom org-pre-cycle-hook nil
1418 "Hook that is run before visibility cycling is happening.
1419 The function(s) in this hook must accept a single argument which indicates
1420 the new state that will be set right after running this hook. The
1421 argument is a symbol. Before a global state change, it can have the values
1422 `overview', `content', or `all'. Before a local state change, it can have
1423 the values `folded', `children', or `subtree'."
1424 :group 'org-cycle
1425 :type 'hook)
1427 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1428 org-cycle-hide-drawers
1429 org-cycle-show-empty-lines
1430 org-optimize-window-after-visibility-change)
1431 "Hook that is run after `org-cycle' has changed the buffer visibility.
1432 The function(s) in this hook must accept a single argument which indicates
1433 the new state that was set by the most recent `org-cycle' command. The
1434 argument is a symbol. After a global state change, it can have the values
1435 `overview', `contents', or `all'. After a local state change, it can have
1436 the values `folded', `children', or `subtree'."
1437 :group 'org-cycle
1438 :type 'hook
1439 :version "26.1"
1440 :package-version '(Org . "8.3"))
1442 (defgroup org-edit-structure nil
1443 "Options concerning structure editing in Org mode."
1444 :tag "Org Edit Structure"
1445 :group 'org-structure)
1447 (defcustom org-odd-levels-only nil
1448 "Non-nil means skip even levels and only use odd levels for the outline.
1449 This has the effect that two stars are being added/taken away in
1450 promotion/demotion commands. It also influences how levels are
1451 handled by the exporters.
1452 Changing it requires restart of `font-lock-mode' to become effective
1453 for fontification also in regions already fontified.
1454 You may also set this on a per-file basis by adding one of the following
1455 lines to the buffer:
1457 #+STARTUP: odd
1458 #+STARTUP: oddeven"
1459 :group 'org-edit-structure
1460 :group 'org-appearance
1461 :type 'boolean)
1463 (defcustom org-adapt-indentation t
1464 "Non-nil means adapt indentation to outline node level.
1466 When this variable is set, Org assumes that you write outlines by
1467 indenting text in each node to align with the headline (after the
1468 stars). The following issues are influenced by this variable:
1470 - The indentation is increased by one space in a demotion
1471 command, and decreased by one in a promotion command. However,
1472 in the latter case, if shifting some line in the entry body
1473 would alter document structure (e.g., insert a new headline),
1474 indentation is not changed at all.
1476 - Property drawers and planning information is inserted indented
1477 when this variable is set. When nil, they will not be indented.
1479 - TAB indents a line relative to current level. The lines below
1480 a headline will be indented when this variable is set.
1482 Note that this is all about true indentation, by adding and
1483 removing space characters. See also `org-indent.el' which does
1484 level-dependent indentation in a virtual way, i.e. at display
1485 time in Emacs."
1486 :group 'org-edit-structure
1487 :type 'boolean)
1489 (defcustom org-special-ctrl-a/e nil
1490 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1492 When t, `C-a' will bring back the cursor to the beginning of the
1493 headline text, i.e. after the stars and after a possible TODO
1494 keyword. In an item, this will be the position after bullet and
1495 check-box, if any. When the cursor is already at that position,
1496 another `C-a' will bring it to the beginning of the line.
1498 `C-e' will jump to the end of the headline, ignoring the presence
1499 of tags in the headline. A second `C-e' will then jump to the
1500 true end of the line, after any tags. This also means that, when
1501 this variable is non-nil, `C-e' also will never jump beyond the
1502 end of the heading of a folded section, i.e. not after the
1503 ellipses.
1505 When set to the symbol `reversed', the first `C-a' or `C-e' works
1506 normally, going to the true line boundary first. Only a directly
1507 following, identical keypress will bring the cursor to the
1508 special positions.
1510 This may also be a cons cell where the behavior for `C-a' and
1511 `C-e' is set separately."
1512 :group 'org-edit-structure
1513 :type '(choice
1514 (const :tag "off" nil)
1515 (const :tag "on: after stars/bullet and before tags first" t)
1516 (const :tag "reversed: true line boundary first" reversed)
1517 (cons :tag "Set C-a and C-e separately"
1518 (choice :tag "Special C-a"
1519 (const :tag "off" nil)
1520 (const :tag "on: after stars/bullet first" t)
1521 (const :tag "reversed: before stars/bullet first" reversed))
1522 (choice :tag "Special C-e"
1523 (const :tag "off" nil)
1524 (const :tag "on: before tags first" t)
1525 (const :tag "reversed: after tags first" reversed)))))
1526 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1528 (defcustom org-special-ctrl-k nil
1529 "Non-nil means `C-k' will behave specially in headlines.
1530 When nil, `C-k' will call the default `kill-line' command.
1531 When t, the following will happen while the cursor is in the headline:
1533 - When the cursor is at the beginning of a headline, kill the entire
1534 line and possible the folded subtree below the line.
1535 - When in the middle of the headline text, kill the headline up to the tags.
1536 - When after the headline text, kill the tags."
1537 :group 'org-edit-structure
1538 :type 'boolean)
1540 (defcustom org-ctrl-k-protect-subtree nil
1541 "Non-nil means, do not delete a hidden subtree with C-k.
1542 When set to the symbol `error', simply throw an error when C-k is
1543 used to kill (part-of) a headline that has hidden text behind it.
1544 Any other non-nil value will result in a query to the user, if it is
1545 OK to kill that hidden subtree. When nil, kill without remorse."
1546 :group 'org-edit-structure
1547 :version "24.1"
1548 :type '(choice
1549 (const :tag "Do not protect hidden subtrees" nil)
1550 (const :tag "Protect hidden subtrees with a security query" t)
1551 (const :tag "Never kill a hidden subtree with C-k" error)))
1553 (defcustom org-special-ctrl-o t
1554 "Non-nil means, make `C-o' insert a row in tables."
1555 :group 'org-edit-structure
1556 :type 'boolean)
1558 (defcustom org-catch-invisible-edits nil
1559 "Check if in invisible region before inserting or deleting a character.
1560 Valid values are:
1562 nil Do not check, so just do invisible edits.
1563 error Throw an error and do nothing.
1564 show Make point visible, and do the requested edit.
1565 show-and-error Make point visible, then throw an error and abort the edit.
1566 smart Make point visible, and do insertion/deletion if it is
1567 adjacent to visible text and the change feels predictable.
1568 Never delete a previously invisible character or add in the
1569 middle or right after an invisible region. Basically, this
1570 allows insertion and backward-delete right before ellipses.
1571 FIXME: maybe in this case we should not even show?"
1572 :group 'org-edit-structure
1573 :version "24.1"
1574 :type '(choice
1575 (const :tag "Do not check" nil)
1576 (const :tag "Throw error when trying to edit" error)
1577 (const :tag "Unhide, but do not do the edit" show-and-error)
1578 (const :tag "Show invisible part and do the edit" show)
1579 (const :tag "Be smart and do the right thing" smart)))
1581 (defcustom org-yank-folded-subtrees t
1582 "Non-nil means when yanking subtrees, fold them.
1583 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1584 it starts with a heading and all other headings in it are either children
1585 or siblings, then fold all the subtrees. However, do this only if no
1586 text after the yank would be swallowed into a folded tree by this action."
1587 :group 'org-edit-structure
1588 :type 'boolean)
1590 (defcustom org-yank-adjusted-subtrees nil
1591 "Non-nil means when yanking subtrees, adjust the level.
1592 With this setting, `org-paste-subtree' is used to insert the subtree, see
1593 this function for details."
1594 :group 'org-edit-structure
1595 :type 'boolean)
1597 (defcustom org-M-RET-may-split-line '((default . t))
1598 "Non-nil means M-RET will split the line at the cursor position.
1599 When nil, it will go to the end of the line before making a
1600 new line.
1601 You may also set this option in a different way for different
1602 contexts. Valid contexts are:
1604 headline when creating a new headline
1605 item when creating a new item
1606 table in a table field
1607 default the value to be used for all contexts not explicitly
1608 customized"
1609 :group 'org-structure
1610 :group 'org-table
1611 :type '(choice
1612 (const :tag "Always" t)
1613 (const :tag "Never" nil)
1614 (repeat :greedy t :tag "Individual contexts"
1615 (cons
1616 (choice :tag "Context"
1617 (const headline)
1618 (const item)
1619 (const table)
1620 (const default))
1621 (boolean)))))
1624 (defcustom org-insert-heading-respect-content nil
1625 "Non-nil means insert new headings after the current subtree.
1626 \\<org-mode-map>
1627 When nil, the new heading is created directly after the current line.
1628 The commands `\\[org-insert-heading-respect-content]' and \
1629 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1630 for the duration of the command."
1631 :group 'org-structure
1632 :type 'boolean)
1634 (defcustom org-blank-before-new-entry '((heading . auto)
1635 (plain-list-item . auto))
1636 "Should `org-insert-heading' leave a blank line before new heading/item?
1637 The value is an alist, with `heading' and `plain-list-item' as CAR,
1638 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1639 which case Org will look at the surrounding headings/items and try to
1640 make an intelligent decision whether to insert a blank line or not."
1641 :group 'org-edit-structure
1642 :type '(list
1643 (cons (const heading)
1644 (choice (const :tag "Never" nil)
1645 (const :tag "Always" t)
1646 (const :tag "Auto" auto)))
1647 (cons (const plain-list-item)
1648 (choice (const :tag "Never" nil)
1649 (const :tag "Always" t)
1650 (const :tag "Auto" auto)))))
1652 (defcustom org-insert-heading-hook nil
1653 "Hook being run after inserting a new heading."
1654 :group 'org-edit-structure
1655 :type 'hook)
1657 (defcustom org-enable-fixed-width-editor t
1658 "Non-nil means lines starting with \":\" are treated as fixed-width.
1659 This currently only means they are never auto-wrapped.
1660 When nil, such lines will be treated like ordinary lines."
1661 :group 'org-edit-structure
1662 :type 'boolean)
1664 (defcustom org-goto-auto-isearch t
1665 "Non-nil means typing characters in `org-goto' starts incremental search.
1666 When nil, you can use these keybindings to navigate the buffer:
1668 q Quit the org-goto interface
1669 n Go to the next visible heading
1670 p Go to the previous visible heading
1671 f Go one heading forward on same level
1672 b Go one heading backward on same level
1673 u Go one heading up"
1674 :group 'org-edit-structure
1675 :type 'boolean)
1677 (defgroup org-sparse-trees nil
1678 "Options concerning sparse trees in Org mode."
1679 :tag "Org Sparse Trees"
1680 :group 'org-structure)
1682 (defcustom org-highlight-sparse-tree-matches t
1683 "Non-nil means highlight all matches that define a sparse tree.
1684 The highlights will automatically disappear the next time the buffer is
1685 changed by an edit command."
1686 :group 'org-sparse-trees
1687 :type 'boolean)
1689 (defcustom org-remove-highlights-with-change t
1690 "Non-nil means any change to the buffer will remove temporary highlights.
1691 \\<org-mode-map>\
1692 Such highlights are created by `org-occur' and `org-clock-display'.
1693 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1694 to get rid of the highlights.
1695 The highlights created by `org-toggle-latex-fragment' always need
1696 `\\[org-toggle-latex-fragment]' to be removed."
1697 :group 'org-sparse-trees
1698 :group 'org-time
1699 :type 'boolean)
1701 (defcustom org-occur-case-fold-search t
1702 "Non-nil means `org-occur' should be case-insensitive.
1703 If set to `smart' the search will be case-insensitive only if it
1704 doesn't specify any upper case character."
1705 :group 'org-sparse-trees
1706 :version "26.1"
1707 :type '(choice
1708 (const :tag "Case-sensitive" nil)
1709 (const :tag "Case-insensitive" t)
1710 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1712 (defcustom org-occur-hook '(org-first-headline-recenter)
1713 "Hook that is run after `org-occur' has constructed a sparse tree.
1714 This can be used to recenter the window to show as much of the structure
1715 as possible."
1716 :group 'org-sparse-trees
1717 :type 'hook)
1719 (defgroup org-imenu-and-speedbar nil
1720 "Options concerning imenu and speedbar in Org mode."
1721 :tag "Org Imenu and Speedbar"
1722 :group 'org-structure)
1724 (defcustom org-imenu-depth 2
1725 "The maximum level for Imenu access to Org headlines.
1726 This also applied for speedbar access."
1727 :group 'org-imenu-and-speedbar
1728 :type 'integer)
1730 (defgroup org-table nil
1731 "Options concerning tables in Org mode."
1732 :tag "Org Table"
1733 :group 'org)
1735 (defcustom org-enable-table-editor 'optimized
1736 "Non-nil means lines starting with \"|\" are handled by the table editor.
1737 When nil, such lines will be treated like ordinary lines.
1739 When equal to the symbol `optimized', the table editor will be optimized to
1740 do the following:
1741 - Automatic overwrite mode in front of whitespace in table fields.
1742 This makes the structure of the table stay in tact as long as the edited
1743 field does not exceed the column width.
1744 - Minimize the number of realigns. Normally, the table is aligned each time
1745 TAB or RET are pressed to move to another field. With optimization this
1746 happens only if changes to a field might have changed the column width.
1747 Optimization requires replacing the functions `self-insert-command',
1748 `delete-char', and `backward-delete-char' in Org buffers, with a
1749 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1750 good at guessing when a re-align will be necessary, but you can always
1751 force one with `\\[org-ctrl-c-ctrl-c]'.
1753 If you would like to use the optimized version in Org mode, but the
1754 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1756 This variable can be used to turn on and off the table editor during a session,
1757 but in order to toggle optimization, a restart is required.
1759 See also the variable `org-table-auto-blank-field'."
1760 :group 'org-table
1761 :type '(choice
1762 (const :tag "off" nil)
1763 (const :tag "on" t)
1764 (const :tag "on, optimized" optimized)))
1766 (defcustom org-self-insert-cluster-for-undo nil
1767 "Non-nil means cluster self-insert commands for undo when possible.
1768 If this is set, then, like in the Emacs command loop, 20 consecutive
1769 characters will be undone together.
1770 This is configurable, because there is some impact on typing performance."
1771 :group 'org-table
1772 :type 'boolean)
1774 (defcustom org-table-tab-recognizes-table.el t
1775 "Non-nil means TAB will automatically notice a table.el table.
1776 When it sees such a table, it moves point into it and - if necessary -
1777 calls `table-recognize-table'."
1778 :group 'org-table-editing
1779 :type 'boolean)
1781 (defgroup org-link nil
1782 "Options concerning links in Org mode."
1783 :tag "Org Link"
1784 :group 'org)
1786 (defvar-local org-link-abbrev-alist-local nil
1787 "Buffer-local version of `org-link-abbrev-alist', which see.
1788 The value of this is taken from the #+LINK lines.")
1790 (defcustom org-link-parameters
1791 '(("doi" :follow org--open-doi-link)
1792 ("elisp" :follow org--open-elisp-link)
1793 ("file" :complete org-file-complete-link)
1794 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1795 ("help" :follow org--open-help-link)
1796 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1797 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1798 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1799 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1800 ("shell" :follow org--open-shell-link))
1801 "An alist of properties that defines all the links in Org mode.
1802 The key in each association is a string of the link type.
1803 Subsequent optional elements make up a p-list of link properties.
1805 :follow - A function that takes the link path as an argument.
1807 :export - A function that takes the link path, description and
1808 export-backend as arguments.
1810 :store - A function responsible for storing the link. See the
1811 function `org-store-link-functions'.
1813 :complete - A function that inserts a link with completion. The
1814 function takes one optional prefix arg.
1816 :face - A face for the link, or a function that returns a face.
1817 The function takes one argument which is the link path. The
1818 default face is `org-link'.
1820 :mouse-face - The mouse-face. The default is `highlight'.
1822 :display - `full' will not fold the link in descriptive
1823 display. Default is `org-link'.
1825 :help-echo - A string or function that takes (window object position)
1826 as arguments and returns a string.
1828 :keymap - A keymap that is active on the link. The default is
1829 `org-mouse-map'.
1831 :htmlize-link - A function for the htmlize-link. Defaults
1832 to (list :uri \"type:path\")
1834 :activate-func - A function to run at the end of font-lock
1835 activation. The function must accept (link-start link-end path bracketp)
1836 as arguments."
1837 :group 'org-link
1838 :type '(alist :tag "Link display parameters"
1839 :value-type plist)
1840 :version "26.1"
1841 :package-version '(Org . "9.1"))
1843 (defun org-link-get-parameter (type key)
1844 "Get TYPE link property for KEY.
1845 TYPE is a string and KEY is a plist keyword."
1846 (plist-get
1847 (cdr (assoc type org-link-parameters))
1848 key))
1850 (defun org-link-set-parameters (type &rest parameters)
1851 "Set link TYPE properties to PARAMETERS.
1852 PARAMETERS should be :key val pairs."
1853 (let ((data (assoc type org-link-parameters)))
1854 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1855 (push (cons type parameters) org-link-parameters)
1856 (org-make-link-regexps)
1857 (org-element-update-syntax))))
1859 (defun org-link-types ()
1860 "Return a list of known link types."
1861 (mapcar #'car org-link-parameters))
1863 (defcustom org-link-abbrev-alist nil
1864 "Alist of link abbreviations.
1865 The car of each element is a string, to be replaced at the start of a link.
1866 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1867 links in Org buffers can have an optional tag after a double colon, e.g.,
1869 [[linkkey:tag][description]]
1871 The `linkkey' must be a single word, starting with a letter, followed
1872 by letters, numbers, `-' or `_'.
1874 If REPLACE is a string, the tag will simply be appended to create the link.
1875 If the string contains \"%s\", the tag will be inserted there. If the string
1876 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1877 at that point (see the function `url-hexify-string'). If the string contains
1878 the specifier \"%(my-function)\", then the custom function `my-function' will
1879 be invoked: this function takes the tag as its only argument and must return
1880 a string.
1882 REPLACE may also be a function that will be called with the tag as the
1883 only argument to create the link, which should be returned as a string.
1885 See the manual for examples."
1886 :group 'org-link
1887 :type '(repeat
1888 (cons
1889 (string :tag "Protocol")
1890 (choice
1891 (string :tag "Format")
1892 (function)))))
1894 (defcustom org-descriptive-links t
1895 "Non-nil means Org will display descriptive links.
1896 E.g. [[http://orgmode.org][Org website]] will be displayed as
1897 \"Org Website\", hiding the link itself and just displaying its
1898 description. When set to nil, Org will display the full links
1899 literally.
1901 You can interactively set the value of this variable by calling
1902 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1903 :group 'org-link
1904 :type 'boolean)
1906 (defcustom org-link-file-path-type 'adaptive
1907 "How the path name in file links should be stored.
1908 Valid values are:
1910 relative Relative to the current directory, i.e. the directory of the file
1911 into which the link is being inserted.
1912 absolute Absolute path, if possible with ~ for home directory.
1913 noabbrev Absolute path, no abbreviation of home directory.
1914 adaptive Use relative path for files in the current directory and sub-
1915 directories of it. For other files, use an absolute path."
1916 :group 'org-link
1917 :type '(choice
1918 (const relative)
1919 (const absolute)
1920 (const noabbrev)
1921 (const adaptive)))
1923 (defvaralias 'org-activate-links 'org-highlight-links)
1924 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1925 "Types of links that should be highlighted in Org files.
1927 This is a list of symbols, each one of them leading to the
1928 highlighting of a certain link type.
1930 You can still open links that are not highlighted.
1932 In principle, it does not hurt to turn on highlighting for all
1933 link types. There may be a small gain when turning off unused
1934 link types. The types are:
1936 bracket The recommended [[link][description]] or [[link]] links with hiding.
1937 angle Links in angular brackets that may contain whitespace like
1938 <bbdb:Carsten Dominik>.
1939 plain Plain links in normal text, no whitespace, like http://google.com.
1940 radio Text that is matched by a radio target, see manual for details.
1941 tag Tag settings in a headline (link to tag search).
1942 date Time stamps (link to calendar).
1943 footnote Footnote labels.
1945 If you set this variable during an Emacs session, use `org-mode-restart'
1946 in the Org buffer so that the change takes effect."
1947 :group 'org-link
1948 :group 'org-appearance
1949 :type '(set :greedy t
1950 (const :tag "Double bracket links" bracket)
1951 (const :tag "Angular bracket links" angle)
1952 (const :tag "Plain text links" plain)
1953 (const :tag "Radio target matches" radio)
1954 (const :tag "Tags" tag)
1955 (const :tag "Timestamps" date)
1956 (const :tag "Footnotes" footnote)))
1958 (defcustom org-make-link-description-function nil
1959 "Function to use for generating link descriptions from links.
1960 When nil, the link location will be used. This function must take
1961 two parameters: the first one is the link, the second one is the
1962 description generated by `org-insert-link'. The function should
1963 return the description to use."
1964 :group 'org-link
1965 :type '(choice (const nil) (function)))
1967 (defgroup org-link-store nil
1968 "Options concerning storing links in Org mode."
1969 :tag "Org Store Link"
1970 :group 'org-link)
1972 (defcustom org-url-hexify-p t
1973 "When non-nil, hexify URL when creating a link."
1974 :type 'boolean
1975 :version "24.3"
1976 :group 'org-link-store)
1978 (defcustom org-email-link-description-format "Email %c: %.30s"
1979 "Format of the description part of a link to an email or usenet message.
1980 The following %-escapes will be replaced by corresponding information:
1982 %F full \"From\" field
1983 %f name, taken from \"From\" field, address if no name
1984 %T full \"To\" field
1985 %t first name in \"To\" field, address if no name
1986 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1987 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1988 %s subject
1989 %d date
1990 %m message-id.
1992 You may use normal field width specification between the % and the letter.
1993 This is for example useful to limit the length of the subject.
1995 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1996 :group 'org-link-store
1997 :type 'string)
1999 (defcustom org-from-is-user-regexp
2000 (let (r1 r2)
2001 (when (and user-mail-address (not (string= user-mail-address "")))
2002 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
2003 (when (and user-full-name (not (string= user-full-name "")))
2004 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
2005 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2006 "Regexp matched against the \"From:\" header of an email or usenet message.
2007 It should match if the message is from the user him/herself."
2008 :group 'org-link-store
2009 :type 'regexp)
2011 (defcustom org-context-in-file-links t
2012 "Non-nil means file links from `org-store-link' contain context.
2013 \\<org-mode-map>
2014 A search string will be added to the file name with :: as separator
2015 and used to find the context when the link is activated by the command
2016 `org-open-at-point'. When this option is t, the entire active region
2017 will be placed in the search string of the file link. If set to a
2018 positive integer, only the first n lines of context will be stored.
2020 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2021 \\[org-store-link]')
2022 negates this setting for the duration of the command."
2023 :group 'org-link-store
2024 :type '(choice boolean integer))
2026 (defcustom org-keep-stored-link-after-insertion nil
2027 "Non-nil means keep link in list for entire session.
2028 \\<org-mode-map>
2029 The command `org-store-link' adds a link pointing to the current
2030 location to an internal list. These links accumulate during a session.
2031 The command `org-insert-link' can be used to insert links into any
2032 Org file (offering completion for all stored links).
2034 When this option is nil, every link which has been inserted once using
2035 `\\[org-insert-link]' will be removed from the list, to make completing the \
2036 unused
2037 links more efficient."
2038 :group 'org-link-store
2039 :type 'boolean)
2041 (defgroup org-link-follow nil
2042 "Options concerning following links in Org mode."
2043 :tag "Org Follow Link"
2044 :group 'org-link)
2046 (defcustom org-link-translation-function nil
2047 "Function to translate links with different syntax to Org syntax.
2048 This can be used to translate links created for example by the Planner
2049 or emacs-wiki packages to Org syntax.
2050 The function must accept two parameters, a TYPE containing the link
2051 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2052 which is everything after the link protocol. It should return a cons
2053 with possibly modified values of type and path.
2054 Org contains a function for this, so if you set this variable to
2055 `org-translate-link-from-planner', you should be able follow many
2056 links created by planner."
2057 :group 'org-link-follow
2058 :type '(choice (const nil) (function)))
2060 (defcustom org-follow-link-hook nil
2061 "Hook that is run after a link has been followed."
2062 :group 'org-link-follow
2063 :type 'hook)
2065 (defcustom org-tab-follows-link nil
2066 "Non-nil means on links TAB will follow the link.
2067 Needs to be set before org.el is loaded.
2068 This really should not be used, it does not make sense, and the
2069 implementation is bad."
2070 :group 'org-link-follow
2071 :type 'boolean)
2073 (defcustom org-return-follows-link nil
2074 "Non-nil means on links RET will follow the link.
2075 In tables, the special behavior of RET has precedence."
2076 :group 'org-link-follow
2077 :type 'boolean)
2079 (defcustom org-mouse-1-follows-link
2080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2081 "Non-nil means mouse-1 on a link will follow the link.
2082 A longer mouse click will still set point. Needs to be set
2083 before org.el is loaded."
2084 :group 'org-link-follow
2085 :version "24.4"
2086 :package-version '(Org . "8.3")
2087 :type '(choice
2088 (const :tag "A double click follows the link" double)
2089 (const :tag "Unconditionally follow the link with mouse-1" t)
2090 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2092 (defcustom org-mark-ring-length 4
2093 "Number of different positions to be recorded in the ring.
2094 Changing this requires a restart of Emacs to work correctly."
2095 :group 'org-link-follow
2096 :type 'integer)
2098 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2099 "Non-nil means internal fuzzy links can only match headlines.
2101 When nil, the a fuzzy link may point to a target or a named
2102 construct in the document. When set to the special value
2103 `query-to-create', offer to create a new headline when none
2104 matched.
2106 Spaces and statistics cookies are ignored during heading searches."
2107 :group 'org-link-follow
2108 :version "24.1"
2109 :type '(choice
2110 (const :tag "Use fuzzy text search" nil)
2111 (const :tag "Match only exact headline" t)
2112 (const :tag "Match exact headline or query to create it"
2113 query-to-create))
2114 :safe #'symbolp)
2116 (defcustom org-link-frame-setup
2117 '((vm . vm-visit-folder-other-frame)
2118 (vm-imap . vm-visit-imap-folder-other-frame)
2119 (gnus . org-gnus-no-new-news)
2120 (file . find-file-other-window)
2121 (wl . wl-other-frame))
2122 "Setup the frame configuration for following links.
2123 When following a link with Emacs, it may often be useful to display
2124 this link in another window or frame. This variable can be used to
2125 set this up for the different types of links.
2126 For VM, use any of
2127 `vm-visit-folder'
2128 `vm-visit-folder-other-window'
2129 `vm-visit-folder-other-frame'
2130 For Gnus, use any of
2131 `gnus'
2132 `gnus-other-frame'
2133 `org-gnus-no-new-news'
2134 For FILE, use any of
2135 `find-file'
2136 `find-file-other-window'
2137 `find-file-other-frame'
2138 For Wanderlust use any of
2139 `wl'
2140 `wl-other-frame'
2141 For the calendar, use the variable `calendar-setup'.
2142 For BBDB, it is currently only possible to display the matches in
2143 another window."
2144 :group 'org-link-follow
2145 :type '(list
2146 (cons (const vm)
2147 (choice
2148 (const vm-visit-folder)
2149 (const vm-visit-folder-other-window)
2150 (const vm-visit-folder-other-frame)))
2151 (cons (const vm-imap)
2152 (choice
2153 (const vm-visit-imap-folder)
2154 (const vm-visit-imap-folder-other-window)
2155 (const vm-visit-imap-folder-other-frame)))
2156 (cons (const gnus)
2157 (choice
2158 (const gnus)
2159 (const gnus-other-frame)
2160 (const org-gnus-no-new-news)))
2161 (cons (const file)
2162 (choice
2163 (const find-file)
2164 (const find-file-other-window)
2165 (const find-file-other-frame)))
2166 (cons (const wl)
2167 (choice
2168 (const wl)
2169 (const wl-other-frame)))))
2171 (defcustom org-display-internal-link-with-indirect-buffer nil
2172 "Non-nil means use indirect buffer to display infile links.
2173 Activating internal links (from one location in a file to another location
2174 in the same file) normally just jumps to the location. When the link is
2175 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2176 is displayed in
2177 another window. When this option is set, the other window actually displays
2178 an indirect buffer clone of the current buffer, to avoid any visibility
2179 changes to the current buffer."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-non-existing-files nil
2184 "Non-nil means `org-open-file' will open non-existing files.
2185 When nil, an error will be generated.
2186 This variable applies only to external applications because they
2187 might choke on non-existing files. If the link is to a file that
2188 will be opened in Emacs, the variable is ignored."
2189 :group 'org-link-follow
2190 :type 'boolean)
2192 (defcustom org-open-directory-means-index-dot-org nil
2193 "Non-nil means a link to a directory really means to index.org.
2194 When nil, following a directory link will run dired or open a finder/explorer
2195 window on that directory."
2196 :group 'org-link-follow
2197 :type 'boolean)
2199 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2200 "Non-nil means ask for confirmation before executing shell links.
2201 Shell links can be dangerous: just think about a link
2203 [[shell:rm -rf ~/*][Google Search]]
2205 This link would show up in your Org document as \"Google Search\",
2206 but really it would remove your entire home directory.
2207 Therefore we advise against setting this variable to nil.
2208 Just change it to `y-or-n-p' if you want to confirm with a
2209 single keystroke rather than having to type \"yes\"."
2210 :group 'org-link-follow
2211 :type '(choice
2212 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2213 (const :tag "with y-or-n (faster)" y-or-n-p)
2214 (const :tag "no confirmation (dangerous)" nil)))
2215 (put 'org-confirm-shell-link-function
2216 'safe-local-variable
2217 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2219 (defcustom org-confirm-shell-link-not-regexp ""
2220 "A regexp to skip confirmation for shell links."
2221 :group 'org-link-follow
2222 :version "24.1"
2223 :type 'regexp)
2225 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2226 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2227 Elisp links can be dangerous: just think about a link
2229 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2231 This link would show up in your Org document as \"Google Search\",
2232 but really it would remove your entire home directory.
2233 Therefore we advise against setting this variable to nil.
2234 Just change it to `y-or-n-p' if you want to confirm with a
2235 single keystroke rather than having to type \"yes\"."
2236 :group 'org-link-follow
2237 :type '(choice
2238 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2239 (const :tag "with y-or-n (faster)" y-or-n-p)
2240 (const :tag "no confirmation (dangerous)" nil)))
2241 (put 'org-confirm-shell-link-function
2242 'safe-local-variable
2243 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2245 (defcustom org-confirm-elisp-link-not-regexp ""
2246 "A regexp to skip confirmation for Elisp links."
2247 :group 'org-link-follow
2248 :version "24.1"
2249 :type 'regexp)
2251 (defconst org-file-apps-defaults-gnu
2252 '((remote . emacs)
2253 (system . mailcap)
2254 (t . mailcap))
2255 "Default file applications on a UNIX or GNU/Linux system.
2256 See `org-file-apps'.")
2258 (defconst org-file-apps-defaults-macosx
2259 '((remote . emacs)
2260 (system . "open %s")
2261 ("ps.gz" . "gv %s")
2262 ("eps.gz" . "gv %s")
2263 ("dvi" . "xdvi %s")
2264 ("fig" . "xfig %s")
2265 (t . "open %s"))
2266 "Default file applications on a macOS system.
2267 The system \"open\" is known as a default, but we use X11 applications
2268 for some files for which the OS does not have a good default.
2269 See `org-file-apps'.")
2271 (defconst org-file-apps-defaults-windowsnt
2272 (list '(remote . emacs)
2273 (cons 'system (lambda (file _path)
2274 (with-no-warnings (w32-shell-execute "open" file))))
2275 (cons t (lambda (file _path)
2276 (with-no-warnings (w32-shell-execute "open" file)))))
2277 "Default file applications on a Windows NT system.
2278 The system \"open\" is used for most files.
2279 See `org-file-apps'.")
2281 (defcustom org-file-apps
2282 '((auto-mode . emacs)
2283 ("\\.mm\\'" . default)
2284 ("\\.x?html?\\'" . default)
2285 ("\\.pdf\\'" . default))
2286 "External applications for opening `file:path' items in a document.
2287 \\<org-mode-map>\
2289 Org mode uses system defaults for different file types, but
2290 you can use this variable to set the application for a given file
2291 extension. The entries in this list are cons cells where the car identifies
2292 files and the cdr the corresponding command.
2294 Possible values for the file identifier are:
2296 \"string\" A string as a file identifier can be interpreted in different
2297 ways, depending on its contents:
2299 - Alphanumeric characters only:
2300 Match links with this file extension.
2301 Example: (\"pdf\" . \"evince %s\")
2302 to open PDFs with evince.
2304 - Regular expression: Match links where the
2305 filename matches the regexp. If you want to
2306 use groups here, use shy groups.
2308 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2309 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2310 to open *.html and *.xhtml with firefox.
2312 - Regular expression which contains (non-shy) groups:
2313 Match links where the whole link, including \"::\", and
2314 anything after that, matches the regexp.
2315 In a custom command string, %1, %2, etc. are replaced with
2316 the parts of the link that were matched by the groups.
2317 For backwards compatibility, if a command string is given
2318 that does not use any of the group matches, this case is
2319 handled identically to the second one (i.e. match against
2320 file name only).
2321 In a custom function, you can access the group matches with
2322 (match-string n link).
2324 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2325 \"evince -p %1 %s\")
2326 to open [[file:document.pdf::5]] with evince at page 5.
2328 `directory' Matches a directory
2329 `remote' Matches a remote file, accessible through tramp or efs.
2330 Remote files most likely should be visited through Emacs
2331 because external applications cannot handle such paths.
2332 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2333 so all files Emacs knows how to handle. Using this with
2334 command `emacs' will open most files in Emacs. Beware that this
2335 will also open html files inside Emacs, unless you add
2336 (\"html\" . default) to the list as well.
2337 `system' The system command to open files, like `open' on Windows
2338 and macOS, and mailcap under GNU/Linux. This is the command
2339 that will be selected if you call `org-open-at-point' with a
2340 double prefix argument (`\\[universal-argument] \
2341 \\[universal-argument] \\[org-open-at-point]').
2342 t Default for files not matched by any of the other options.
2344 Possible values for the command are:
2346 `emacs' The file will be visited by the current Emacs process.
2347 `default' Use the default application for this file type, which is the
2348 association for t in the list, most likely in the system-specific
2349 part. This can be used to overrule an unwanted setting in the
2350 system-specific variable.
2351 `system' Use the system command for opening files, like \"open\".
2352 This command is specified by the entry whose car is `system'.
2353 Most likely, the system-specific version of this variable
2354 does define this command, but you can overrule/replace it
2355 here.
2356 `mailcap' Use command specified in the mailcaps.
2357 string A command to be executed by a shell; %s will be replaced
2358 by the path to the file.
2359 function A Lisp function, which will be called with two arguments:
2360 the file path and the original link string, without the
2361 \"file:\" prefix.
2363 For more examples, see the system specific constants
2364 `org-file-apps-defaults-macosx'
2365 `org-file-apps-defaults-windowsnt'
2366 `org-file-apps-defaults-gnu'."
2367 :group 'org-link-follow
2368 :type '(repeat
2369 (cons (choice :value ""
2370 (string :tag "Extension")
2371 (const :tag "System command to open files" system)
2372 (const :tag "Default for unrecognized files" t)
2373 (const :tag "Remote file" remote)
2374 (const :tag "Links to a directory" directory)
2375 (const :tag "Any files that have Emacs modes"
2376 auto-mode))
2377 (choice :value ""
2378 (const :tag "Visit with Emacs" emacs)
2379 (const :tag "Use default" default)
2380 (const :tag "Use the system command" system)
2381 (string :tag "Command")
2382 (function :tag "Function")))))
2384 (defcustom org-doi-server-url "http://dx.doi.org/"
2385 "The URL of the DOI server."
2386 :type 'string
2387 :version "24.3"
2388 :group 'org-link-follow)
2390 (defgroup org-refile nil
2391 "Options concerning refiling entries in Org mode."
2392 :tag "Org Refile"
2393 :group 'org)
2395 (defcustom org-directory "~/org"
2396 "Directory with Org files.
2397 This is just a default location to look for Org files. There is no need
2398 at all to put your files into this directory. It is used in the
2399 following situations:
2401 1. When a capture template specifies a target file that is not an
2402 absolute path. The path will then be interpreted relative to
2403 `org-directory'
2404 2. When the value of variable `org-agenda-files' is a single file, any
2405 relative paths in this file will be taken as relative to
2406 `org-directory'."
2407 :group 'org-refile
2408 :group 'org-capture
2409 :type 'directory)
2411 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2412 "Default target for storing notes.
2413 Used as a fall back file for org-capture.el, for templates that
2414 do not specify a target file."
2415 :group 'org-refile
2416 :group 'org-capture
2417 :type 'file)
2419 (defcustom org-goto-interface 'outline
2420 "The default interface to be used for `org-goto'.
2421 Allowed values are:
2422 outline The interface shows an outline of the relevant file
2423 and the correct heading is found by moving through
2424 the outline or by searching with incremental search.
2425 outline-path-completion Headlines in the current buffer are offered via
2426 completion. This is the interface also used by
2427 the refile command."
2428 :group 'org-refile
2429 :type '(choice
2430 (const :tag "Outline" outline)
2431 (const :tag "Outline-path-completion" outline-path-completion)))
2433 (defcustom org-goto-max-level 5
2434 "Maximum target level when running `org-goto' with refile interface."
2435 :group 'org-refile
2436 :type 'integer)
2438 (defcustom org-reverse-note-order nil
2439 "Non-nil means store new notes at the beginning of a file or entry.
2440 When nil, new notes will be filed to the end of a file or entry.
2441 This can also be a list with cons cells of regular expressions that
2442 are matched against file names, and values."
2443 :group 'org-capture
2444 :group 'org-refile
2445 :type '(choice
2446 (const :tag "Reverse always" t)
2447 (const :tag "Reverse never" nil)
2448 (repeat :tag "By file name regexp"
2449 (cons regexp boolean))))
2451 (defcustom org-log-refile nil
2452 "Information to record when a task is refiled.
2454 Possible values are:
2456 nil Don't add anything
2457 time Add a time stamp to the task
2458 note Prompt for a note and add it with template `org-log-note-headings'
2460 This option can also be set with on a per-file-basis with
2462 #+STARTUP: nologrefile
2463 #+STARTUP: logrefile
2464 #+STARTUP: lognoterefile
2466 You can have local logging settings for a subtree by setting the LOGGING
2467 property to one or more of these keywords.
2469 When bulk-refiling from the agenda, the value `note' is forbidden and
2470 will temporarily be changed to `time'."
2471 :group 'org-refile
2472 :group 'org-progress
2473 :version "24.1"
2474 :type '(choice
2475 (const :tag "No logging" nil)
2476 (const :tag "Record timestamp" time)
2477 (const :tag "Record timestamp with note." note)))
2479 (defcustom org-refile-targets nil
2480 "Targets for refiling entries with `\\[org-refile]'.
2481 This is a list of cons cells. Each cell contains:
2482 - a specification of the files to be considered, either a list of files,
2483 or a symbol whose function or variable value will be used to retrieve
2484 a file name or a list of file names. If you use `org-agenda-files' for
2485 that, all agenda files will be scanned for targets. Nil means consider
2486 headings in the current buffer.
2487 - A specification of how to find candidate refile targets. This may be
2488 any of:
2489 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2490 This tag has to be present in all target headlines, inheritance will
2491 not be considered.
2492 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2493 todo keyword.
2494 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2495 headlines that are refiling targets.
2496 - a cons cell (:level . N). Any headline of level N is considered a target.
2497 Note that, when `org-odd-levels-only' is set, level corresponds to
2498 order in hierarchy, not to the number of stars.
2499 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2500 Note that, when `org-odd-levels-only' is set, level corresponds to
2501 order in hierarchy, not to the number of stars.
2503 Each element of this list generates a set of possible targets.
2504 The union of these sets is presented (with completion) to
2505 the user by `org-refile'.
2507 You can set the variable `org-refile-target-verify-function' to a function
2508 to verify each headline found by the simple criteria above.
2510 When this variable is nil, all top-level headlines in the current buffer
2511 are used, equivalent to the value `((nil . (:level . 1))'."
2512 :group 'org-refile
2513 :type '(repeat
2514 (cons
2515 (choice :value org-agenda-files
2516 (const :tag "All agenda files" org-agenda-files)
2517 (const :tag "Current buffer" nil)
2518 (function) (variable) (file))
2519 (choice :tag "Identify target headline by"
2520 (cons :tag "Specific tag" (const :value :tag) (string))
2521 (cons :tag "TODO keyword" (const :value :todo) (string))
2522 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2523 (cons :tag "Level number" (const :value :level) (integer))
2524 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2526 (defcustom org-refile-target-verify-function nil
2527 "Function to verify if the headline at point should be a refile target.
2528 The function will be called without arguments, with point at the
2529 beginning of the headline. It should return t and leave point
2530 where it is if the headline is a valid target for refiling.
2532 If the target should not be selected, the function must return nil.
2533 In addition to this, it may move point to a place from where the search
2534 should be continued. For example, the function may decide that the entire
2535 subtree of the current entry should be excluded and move point to the end
2536 of the subtree."
2537 :group 'org-refile
2538 :type '(choice
2539 (const nil)
2540 (function)))
2542 (defcustom org-refile-use-cache nil
2543 "Non-nil means cache refile targets to speed up the process.
2544 \\<org-mode-map>\
2545 The cache for a particular file will be updated automatically when
2546 the buffer has been killed, or when any of the marker used for flagging
2547 refile targets no longer points at a live buffer.
2548 If you have added new entries to a buffer that might themselves be targets,
2549 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2550 if you find that easier, \
2551 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2552 \\[org-refile]'."
2553 :group 'org-refile
2554 :version "24.1"
2555 :type 'boolean)
2557 (defcustom org-refile-use-outline-path nil
2558 "Non-nil means provide refile targets as paths.
2559 So a level 3 headline will be available as level1/level2/level3.
2561 When the value is `file', also include the file name (without directory)
2562 into the path. In this case, you can also stop the completion after
2563 the file name, to get entries inserted as top level in the file.
2565 When `full-file-path', include the full file path.
2567 When `buffer-name', use the buffer name."
2568 :group 'org-refile
2569 :type '(choice
2570 (const :tag "Not" nil)
2571 (const :tag "Yes" t)
2572 (const :tag "Start with file name" file)
2573 (const :tag "Start with full file path" full-file-path)
2574 (const :tag "Start with buffer name" buffer-name)))
2576 (defcustom org-outline-path-complete-in-steps t
2577 "Non-nil means complete the outline path in hierarchical steps.
2578 When Org uses the refile interface to select an outline path (see
2579 `org-refile-use-outline-path'), the completion of the path can be
2580 done in a single go, or it can be done in steps down the headline
2581 hierarchy. Going in steps is probably the best if you do not use
2582 a special completion package like `ido' or `icicles'. However,
2583 when using these packages, going in one step can be very fast,
2584 while still showing the whole path to the entry."
2585 :group 'org-refile
2586 :type 'boolean)
2588 (defcustom org-refile-allow-creating-parent-nodes nil
2589 "Non-nil means allow the creation of new nodes as refile targets.
2590 New nodes are then created by adding \"/new node name\" to the completion
2591 of an existing node. When the value of this variable is `confirm',
2592 new node creation must be confirmed by the user (recommended).
2593 When nil, the completion must match an existing entry.
2595 Note that, if the new heading is not seen by the criteria
2596 listed in `org-refile-targets', multiple instances of the same
2597 heading would be created by trying again to file under the new
2598 heading."
2599 :group 'org-refile
2600 :type '(choice
2601 (const :tag "Never" nil)
2602 (const :tag "Always" t)
2603 (const :tag "Prompt for confirmation" confirm)))
2605 (defcustom org-refile-active-region-within-subtree nil
2606 "Non-nil means also refile active region within a subtree.
2608 By default `org-refile' doesn't allow refiling regions if they
2609 don't contain a set of subtrees, but it might be convenient to
2610 do so sometimes: in that case, the first line of the region is
2611 converted to a headline before refiling."
2612 :group 'org-refile
2613 :version "24.1"
2614 :type 'boolean)
2616 (defgroup org-todo nil
2617 "Options concerning TODO items in Org mode."
2618 :tag "Org TODO"
2619 :group 'org)
2621 (defgroup org-progress nil
2622 "Options concerning Progress logging in Org mode."
2623 :tag "Org Progress"
2624 :group 'org-time)
2626 (defvar org-todo-interpretation-widgets
2627 '((:tag "Sequence (cycling hits every state)" sequence)
2628 (:tag "Type (cycling directly to DONE)" type))
2629 "The available interpretation symbols for customizing `org-todo-keywords'.
2630 Interested libraries should add to this list.")
2632 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2633 "List of TODO entry keyword sequences and their interpretation.
2634 \\<org-mode-map>This is a list of sequences.
2636 Each sequence starts with a symbol, either `sequence' or `type',
2637 indicating if the keywords should be interpreted as a sequence of
2638 action steps, or as different types of TODO items. The first
2639 keywords are states requiring action - these states will select a headline
2640 for inclusion into the global TODO list Org produces. If one of the
2641 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2642 signify that no further action is necessary. If \"|\" is not found,
2643 the last keyword is treated as the only DONE state of the sequence.
2645 The command `\\[org-todo]' cycles an entry through these states, and one
2646 additional state where no keyword is present. For details about this
2647 cycling, see the manual.
2649 TODO keywords and interpretation can also be set on a per-file basis with
2650 the special #+SEQ_TODO and #+TYP_TODO lines.
2652 Each keyword can optionally specify a character for fast state selection
2653 \(in combination with the variable `org-use-fast-todo-selection')
2654 and specifiers for state change logging, using the same syntax that
2655 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2656 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2657 indicates to record a time stamp each time this state is selected.
2659 Each keyword may also specify if a timestamp or a note should be
2660 recorded when entering or leaving the state, by adding additional
2661 characters in the parenthesis after the keyword. This looks like this:
2662 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2663 record only the time of the state change. With X and Y being either
2664 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2665 Y when leaving the state if and only if the *target* state does not
2666 define X. You may omit any of the fast-selection key or X or /Y,
2667 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2669 For backward compatibility, this variable may also be just a list
2670 of keywords. In this case the interpretation (sequence or type) will be
2671 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2672 :group 'org-todo
2673 :group 'org-keywords
2674 :type '(choice
2675 (repeat :tag "Old syntax, just keywords"
2676 (string :tag "Keyword"))
2677 (repeat :tag "New syntax"
2678 (cons
2679 (choice
2680 :tag "Interpretation"
2681 ;;Quick and dirty way to see
2682 ;;`org-todo-interpretations'. This takes the
2683 ;;place of item arguments
2684 :convert-widget
2685 (lambda (widget)
2686 (widget-put widget
2687 :args (mapcar
2688 (lambda (x)
2689 (widget-convert
2690 (cons 'const x)))
2691 org-todo-interpretation-widgets))
2692 widget))
2693 (repeat
2694 (string :tag "Keyword"))))))
2696 (defvar-local org-todo-keywords-1 nil
2697 "All TODO and DONE keywords active in a buffer.")
2698 (defvar org-todo-keywords-for-agenda nil)
2699 (defvar org-done-keywords-for-agenda nil)
2700 (defvar org-todo-keyword-alist-for-agenda nil)
2701 (defvar org-tag-alist-for-agenda nil
2702 "Alist of all tags from all agenda files.")
2703 (defvar org-tag-groups-alist-for-agenda nil
2704 "Alist of all groups tags from all current agenda files.")
2705 (defvar-local org-tag-groups-alist nil)
2706 (defvar org-agenda-contributing-files nil)
2707 (defvar-local org-current-tag-alist nil
2708 "Alist of all tag groups in current buffer.
2709 This variable takes into consideration `org-tag-alist',
2710 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2711 (defvar-local org-not-done-keywords nil)
2712 (defvar-local org-done-keywords nil)
2713 (defvar-local org-todo-heads nil)
2714 (defvar-local org-todo-sets nil)
2715 (defvar-local org-todo-log-states nil)
2716 (defvar-local org-todo-kwd-alist nil)
2717 (defvar-local org-todo-key-alist nil)
2718 (defvar-local org-todo-key-trigger nil)
2720 (defcustom org-todo-interpretation 'sequence
2721 "Controls how TODO keywords are interpreted.
2722 This variable is in principle obsolete and is only used for
2723 backward compatibility, if the interpretation of todo keywords is
2724 not given already in `org-todo-keywords'. See that variable for
2725 more information."
2726 :group 'org-todo
2727 :group 'org-keywords
2728 :type '(choice (const sequence)
2729 (const type)))
2731 (defcustom org-use-fast-todo-selection t
2732 "\\<org-mode-map>\
2733 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2734 This variable describes if and under what circumstances the cycling
2735 mechanism for TODO keywords will be replaced by a single-key, direct
2736 selection scheme.
2738 When nil, fast selection is never used.
2740 When the symbol `prefix', it will be used when `org-todo' is called
2741 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2742 in an Org buffer, and
2743 `\\[universal-argument] t' in an agenda buffer.
2745 When t, fast selection is used by default. In this case, the prefix
2746 argument forces cycling instead.
2748 In all cases, the special interface is only used if access keys have
2749 actually been assigned by the user, i.e. if keywords in the configuration
2750 are followed by a letter in parenthesis, like TODO(t)."
2751 :group 'org-todo
2752 :type '(choice
2753 (const :tag "Never" nil)
2754 (const :tag "By default" t)
2755 (const :tag "Only with C-u C-c C-t" prefix)))
2757 (defcustom org-provide-todo-statistics t
2758 "Non-nil means update todo statistics after insert and toggle.
2759 ALL-HEADLINES means update todo statistics by including headlines
2760 with no TODO keyword as well, counting them as not done.
2761 A list of TODO keywords means the same, but skip keywords that are
2762 not in this list.
2763 When set to a list of two lists, the first list contains keywords
2764 to consider as TODO keywords, the second list contains keywords
2765 to consider as DONE keywords.
2767 When this is set, todo statistics is updated in the parent of the
2768 current entry each time a todo state is changed."
2769 :group 'org-todo
2770 :type '(choice
2771 (const :tag "Yes, only for TODO entries" t)
2772 (const :tag "Yes, including all entries" all-headlines)
2773 (repeat :tag "Yes, for TODOs in this list"
2774 (string :tag "TODO keyword"))
2775 (list :tag "Yes, for TODOs and DONEs in these lists"
2776 (repeat (string :tag "TODO keyword"))
2777 (repeat (string :tag "DONE keyword")))
2778 (other :tag "No TODO statistics" nil)))
2780 (defcustom org-hierarchical-todo-statistics t
2781 "Non-nil means TODO statistics covers just direct children.
2782 When nil, all entries in the subtree are considered.
2783 This has only an effect if `org-provide-todo-statistics' is set.
2784 To set this to nil for only a single subtree, use a COOKIE_DATA
2785 property and include the word \"recursive\" into the value."
2786 :group 'org-todo
2787 :type 'boolean)
2789 (defcustom org-after-todo-state-change-hook nil
2790 "Hook which is run after the state of a TODO item was changed.
2791 The new state (a string with a TODO keyword, or nil) is available in the
2792 Lisp variable `org-state'."
2793 :group 'org-todo
2794 :type 'hook)
2796 (defvar org-blocker-hook nil
2797 "Hook for functions that are allowed to block a state change.
2799 Functions in this hook should not modify the buffer.
2800 Each function gets as its single argument a property list,
2801 see `org-trigger-hook' for more information about this list.
2803 If any of the functions in this hook returns nil, the state change
2804 is blocked.")
2806 (defvar org-trigger-hook nil
2807 "Hook for functions that are triggered by a state change.
2809 Each function gets as its single argument a property list with at
2810 least the following elements:
2812 (:type type-of-change :position pos-at-entry-start
2813 :from old-state :to new-state)
2815 Depending on the type, more properties may be present.
2817 This mechanism is currently implemented for:
2819 TODO state changes
2820 ------------------
2821 :type todo-state-change
2822 :from previous state (keyword as a string), or nil, or a symbol
2823 `todo' or `done', to indicate the general type of state.
2824 :to new state, like in :from")
2826 (defcustom org-enforce-todo-dependencies nil
2827 "Non-nil means undone TODO entries will block switching the parent to DONE.
2828 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2829 be blocked if any prior sibling is not yet done.
2830 Finally, if the parent is blocked because of ordered siblings of its own,
2831 the child will also be blocked."
2832 :set (lambda (var val)
2833 (set var val)
2834 (if val
2835 (add-hook 'org-blocker-hook
2836 'org-block-todo-from-children-or-siblings-or-parent)
2837 (remove-hook 'org-blocker-hook
2838 'org-block-todo-from-children-or-siblings-or-parent)))
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-enforce-todo-checkbox-dependencies nil
2843 "Non-nil means unchecked boxes will block switching the parent to DONE.
2844 When this is nil, checkboxes have no influence on switching TODO states.
2845 When non-nil, you first need to check off all check boxes before the TODO
2846 entry can be switched to DONE.
2847 This variable needs to be set before org.el is loaded, and you need to
2848 restart Emacs after a change to make the change effective. The only way
2849 to change is while Emacs is running is through the customize interface."
2850 :set (lambda (var val)
2851 (set var val)
2852 (if val
2853 (add-hook 'org-blocker-hook
2854 'org-block-todo-from-checkboxes)
2855 (remove-hook 'org-blocker-hook
2856 'org-block-todo-from-checkboxes)))
2857 :group 'org-todo
2858 :type 'boolean)
2860 (defcustom org-treat-insert-todo-heading-as-state-change nil
2861 "Non-nil means inserting a TODO heading is treated as state change.
2862 So when the command `\\[org-insert-todo-heading]' is used, state change
2863 logging will apply if appropriate. When nil, the new TODO item will
2864 be inserted directly, and no logging will take place."
2865 :group 'org-todo
2866 :type 'boolean)
2868 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2869 "Non-nil means switching TODO states with S-cursor counts as state change.
2870 This is the default behavior. However, setting this to nil allows a
2871 convenient way to select a TODO state and bypass any logging associated
2872 with that."
2873 :group 'org-todo
2874 :type 'boolean)
2876 (defcustom org-todo-state-tags-triggers nil
2877 "Tag changes that should be triggered by TODO state changes.
2878 This is a list. Each entry is
2880 (state-change (tag . flag) .......)
2882 State-change can be a string with a state, and empty string to indicate the
2883 state that has no TODO keyword, or it can be one of the symbols `todo'
2884 or `done', meaning any not-done or done state, respectively."
2885 :group 'org-todo
2886 :group 'org-tags
2887 :type '(repeat
2888 (cons (choice :tag "When changing to"
2889 (const :tag "Not-done state" todo)
2890 (const :tag "Done state" done)
2891 (string :tag "State"))
2892 (repeat
2893 (cons :tag "Tag action"
2894 (string :tag "Tag")
2895 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2897 (defcustom org-log-done nil
2898 "Information to record when a task moves to the DONE state.
2900 Possible values are:
2902 nil Don't add anything, just change the keyword
2903 time Add a time stamp to the task
2904 note Prompt for a note and add it with template `org-log-note-headings'
2906 This option can also be set with on a per-file-basis with
2908 #+STARTUP: nologdone
2909 #+STARTUP: logdone
2910 #+STARTUP: lognotedone
2912 You can have local logging settings for a subtree by setting the LOGGING
2913 property to one or more of these keywords."
2914 :group 'org-todo
2915 :group 'org-progress
2916 :type '(choice
2917 (const :tag "No logging" nil)
2918 (const :tag "Record CLOSED timestamp" time)
2919 (const :tag "Record CLOSED timestamp with note." note)))
2921 ;; Normalize old uses of org-log-done.
2922 (cond
2923 ((eq org-log-done t) (setq org-log-done 'time))
2924 ((and (listp org-log-done) (memq 'done org-log-done))
2925 (setq org-log-done 'note)))
2927 (defcustom org-log-reschedule nil
2928 "Information to record when the scheduling date of a tasks is modified.
2930 Possible values are:
2932 nil Don't add anything, just change the date
2933 time Add a time stamp to the task
2934 note Prompt for a note and add it with template `org-log-note-headings'
2936 This option can also be set with on a per-file-basis with
2938 #+STARTUP: nologreschedule
2939 #+STARTUP: logreschedule
2940 #+STARTUP: lognotereschedule"
2941 :group 'org-todo
2942 :group 'org-progress
2943 :type '(choice
2944 (const :tag "No logging" nil)
2945 (const :tag "Record timestamp" time)
2946 (const :tag "Record timestamp with note." note)))
2948 (defcustom org-log-redeadline nil
2949 "Information to record when the deadline date of a tasks is modified.
2951 Possible values are:
2953 nil Don't add anything, just change the date
2954 time Add a time stamp to the task
2955 note Prompt for a note and add it with template `org-log-note-headings'
2957 This option can also be set with on a per-file-basis with
2959 #+STARTUP: nologredeadline
2960 #+STARTUP: logredeadline
2961 #+STARTUP: lognoteredeadline
2963 You can have local logging settings for a subtree by setting the LOGGING
2964 property to one or more of these keywords."
2965 :group 'org-todo
2966 :group 'org-progress
2967 :type '(choice
2968 (const :tag "No logging" nil)
2969 (const :tag "Record timestamp" time)
2970 (const :tag "Record timestamp with note." note)))
2972 (defcustom org-log-note-clock-out nil
2973 "Non-nil means record a note when clocking out of an item.
2974 This can also be configured on a per-file basis by adding one of
2975 the following lines anywhere in the buffer:
2977 #+STARTUP: lognoteclock-out
2978 #+STARTUP: nolognoteclock-out"
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type 'boolean)
2983 (defcustom org-log-done-with-time t
2984 "Non-nil means the CLOSED time stamp will contain date and time.
2985 When nil, only the date will be recorded."
2986 :group 'org-progress
2987 :type 'boolean)
2989 (defcustom org-log-note-headings
2990 '((done . "CLOSING NOTE %t")
2991 (state . "State %-12s from %-12S %t")
2992 (note . "Note taken on %t")
2993 (reschedule . "Rescheduled from %S on %t")
2994 (delschedule . "Not scheduled, was %S on %t")
2995 (redeadline . "New deadline from %S on %t")
2996 (deldeadline . "Removed deadline, was %S on %t")
2997 (refile . "Refiled on %t")
2998 (clock-out . ""))
2999 "Headings for notes added to entries.
3001 The value is an alist, with the car being a symbol indicating the
3002 note context, and the cdr is the heading to be used. The heading
3003 may also be the empty string. The following placeholders can be
3004 used:
3006 %t a time stamp.
3007 %T an active time stamp instead the default inactive one
3008 %d a short-format time stamp.
3009 %D an active short-format time stamp.
3010 %s the new TODO state or time stamp (inactive), in double quotes.
3011 %S the old TODO state or time stamp (inactive), in double quotes.
3012 %u the user name.
3013 %U full user name.
3015 In fact, it is not a good idea to change the `state' entry,
3016 because Agenda Log mode depends on the format of these entries."
3017 :group 'org-todo
3018 :group 'org-progress
3019 :type '(list :greedy t
3020 (cons (const :tag "Heading when closing an item" done) string)
3021 (cons (const :tag
3022 "Heading when changing todo state (todo sequence only)"
3023 state) string)
3024 (cons (const :tag "Heading when just taking a note" note) string)
3025 (cons (const :tag "Heading when rescheduling" reschedule) string)
3026 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3027 (cons (const :tag "Heading when changing deadline" redeadline) string)
3028 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3029 (cons (const :tag "Heading when refiling" refile) string)
3030 (cons (const :tag "Heading when clocking out" clock-out) string)))
3032 (unless (assq 'note org-log-note-headings)
3033 (push '(note . "%t") org-log-note-headings))
3035 (defcustom org-log-into-drawer nil
3036 "Non-nil means insert state change notes and time stamps into a drawer.
3037 When nil, state changes notes will be inserted after the headline and
3038 any scheduling and clock lines, but not inside a drawer.
3040 The value of this variable should be the name of the drawer to use.
3041 LOGBOOK is proposed as the default drawer for this purpose, you can
3042 also set this to a string to define the drawer of your choice.
3044 A value of t is also allowed, representing \"LOGBOOK\".
3046 A value of t or nil can also be set with on a per-file-basis with
3048 #+STARTUP: logdrawer
3049 #+STARTUP: nologdrawer
3051 If this variable is set, `org-log-state-notes-insert-after-drawers'
3052 will be ignored.
3054 You can set the property LOG_INTO_DRAWER to overrule this setting for
3055 a subtree.
3057 Do not check directly this variable in a Lisp program. Call
3058 function `org-log-into-drawer' instead."
3059 :group 'org-todo
3060 :group 'org-progress
3061 :type '(choice
3062 (const :tag "Not into a drawer" nil)
3063 (const :tag "LOGBOOK" t)
3064 (string :tag "Other")))
3066 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3068 (defun org-log-into-drawer ()
3069 "Name of the log drawer, as a string, or nil.
3070 This is the value of `org-log-into-drawer'. However, if the
3071 current entry has or inherits a LOG_INTO_DRAWER property, it will
3072 be used instead of the default value."
3073 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3074 (cond ((equal p "nil") nil)
3075 ((equal p "t") "LOGBOOK")
3076 ((stringp p) p)
3077 (p "LOGBOOK")
3078 ((stringp org-log-into-drawer) org-log-into-drawer)
3079 (org-log-into-drawer "LOGBOOK"))))
3081 (defcustom org-log-state-notes-insert-after-drawers nil
3082 "Non-nil means insert state change notes after any drawers in entry.
3083 Only the drawers that *immediately* follow the headline and the
3084 deadline/scheduled line are skipped.
3085 When nil, insert notes right after the heading and perhaps the line
3086 with deadline/scheduling if present.
3088 This variable will have no effect if `org-log-into-drawer' is
3089 set."
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-log-states-order-reversed t
3095 "Non-nil means the latest state note will be directly after heading.
3096 When nil, the state change notes will be ordered according to time.
3098 This option can also be set with on a per-file-basis with
3100 #+STARTUP: logstatesreversed
3101 #+STARTUP: nologstatesreversed"
3102 :group 'org-todo
3103 :group 'org-progress
3104 :type 'boolean)
3106 (defcustom org-todo-repeat-to-state nil
3107 "The TODO state to which a repeater should return the repeating task.
3108 By default this is the first task in a TODO sequence, or the previous state
3109 in a TODO_TYP set. But you can specify another task here.
3110 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3111 :group 'org-todo
3112 :version "24.1"
3113 :type '(choice (const :tag "Head of sequence" nil)
3114 (string :tag "Specific state")))
3116 (defcustom org-log-repeat 'time
3117 "Non-nil means record moving through the DONE state when triggering repeat.
3118 An auto-repeating task is immediately switched back to TODO when
3119 marked DONE. If you are not logging state changes (by adding \"@\"
3120 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3121 record a closing note, there will be no record of the task moving
3122 through DONE. This variable forces taking a note anyway.
3124 nil Don't force a record
3125 time Record a time stamp
3126 note Prompt for a note and add it with template `org-log-note-headings'
3128 This option can also be set with on a per-file-basis with
3130 #+STARTUP: nologrepeat
3131 #+STARTUP: logrepeat
3132 #+STARTUP: lognoterepeat
3134 You can have local logging settings for a subtree by setting the LOGGING
3135 property to one or more of these keywords."
3136 :group 'org-todo
3137 :group 'org-progress
3138 :type '(choice
3139 (const :tag "Don't force a record" nil)
3140 (const :tag "Force recording the DONE state" time)
3141 (const :tag "Force recording a note with the DONE state" note)))
3144 (defgroup org-priorities nil
3145 "Priorities in Org mode."
3146 :tag "Org Priorities"
3147 :group 'org-todo)
3149 (defcustom org-enable-priority-commands t
3150 "Non-nil means priority commands are active.
3151 When nil, these commands will be disabled, so that you never accidentally
3152 set a priority."
3153 :group 'org-priorities
3154 :type 'boolean)
3156 (defcustom org-highest-priority ?A
3157 "The highest priority of TODO items. A character like ?A, ?B etc.
3158 Must have a smaller ASCII number than `org-lowest-priority'."
3159 :group 'org-priorities
3160 :type 'character)
3162 (defcustom org-lowest-priority ?C
3163 "The lowest priority of TODO items. A character like ?A, ?B etc.
3164 Must have a larger ASCII number than `org-highest-priority'."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-default-priority ?B
3169 "The default priority of TODO items.
3170 This is the priority an item gets if no explicit priority is given.
3171 When starting to cycle on an empty priority the first step in the cycle
3172 depends on `org-priority-start-cycle-with-default'. The resulting first
3173 step priority must not exceed the range from `org-highest-priority' to
3174 `org-lowest-priority' which means that `org-default-priority' has to be
3175 in this range exclusive or inclusive the range boundaries. Else the
3176 first step refuses to set the default and the second will fall back
3177 to (depending on the command used) the highest or lowest priority."
3178 :group 'org-priorities
3179 :type 'character)
3181 (defcustom org-priority-start-cycle-with-default t
3182 "Non-nil means start with default priority when starting to cycle.
3183 When this is nil, the first step in the cycle will be (depending on the
3184 command used) one higher or lower than the default priority.
3185 See also `org-default-priority'."
3186 :group 'org-priorities
3187 :type 'boolean)
3189 (defcustom org-get-priority-function nil
3190 "Function to extract the priority from a string.
3191 The string is normally the headline. If this is nil Org computes the
3192 priority from the priority cookie like [#A] in the headline. It returns
3193 an integer, increasing by 1000 for each priority level.
3194 The user can set a different function here, which should take a string
3195 as an argument and return the numeric priority."
3196 :group 'org-priorities
3197 :version "24.1"
3198 :type '(choice
3199 (const nil)
3200 (function)))
3202 (defgroup org-time nil
3203 "Options concerning time stamps and deadlines in Org mode."
3204 :tag "Org Time"
3205 :group 'org)
3207 (defcustom org-time-stamp-rounding-minutes '(0 5)
3208 "Number of minutes to round time stamps to.
3209 \\<org-mode-map>\
3210 These are two values, the first applies when first creating a time stamp.
3211 The second applies when changing it with the commands `S-up' and `S-down'.
3212 When changing the time stamp, this means that it will change in steps
3213 of N minutes, as given by the second value.
3215 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3216 numbers should be factors of 60, so for example 5, 10, 15.
3218 When this is larger than 1, you can still force an exact time stamp by using
3219 a double prefix argument to a time stamp command like \
3220 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3221 and by using a prefix arg to `S-up/down' to specify the exact number
3222 of minutes to shift."
3223 :group 'org-time
3224 :get (lambda (var) ; Make sure both elements are there
3225 (if (integerp (default-value var))
3226 (list (default-value var) 5)
3227 (default-value var)))
3228 :type '(list
3229 (integer :tag "when inserting times")
3230 (integer :tag "when modifying times")))
3232 ;; Normalize old customizations of this variable.
3233 (when (integerp org-time-stamp-rounding-minutes)
3234 (setq org-time-stamp-rounding-minutes
3235 (list org-time-stamp-rounding-minutes
3236 org-time-stamp-rounding-minutes)))
3238 (defcustom org-display-custom-times nil
3239 "Non-nil means overlay custom formats over all time stamps.
3240 The formats are defined through the variable `org-time-stamp-custom-formats'.
3241 To turn this on on a per-file basis, insert anywhere in the file:
3242 #+STARTUP: customtime"
3243 :group 'org-time
3244 :set 'set-default
3245 :type 'sexp)
3246 (make-variable-buffer-local 'org-display-custom-times)
3248 (defcustom org-time-stamp-custom-formats
3249 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3250 "Custom formats for time stamps. See `format-time-string' for the syntax.
3251 These are overlaid over the default ISO format if the variable
3252 `org-display-custom-times' is set. Time like %H:%M should be at the
3253 end of the second format. The custom formats are also honored by export
3254 commands, if custom time display is turned on at the time of export."
3255 :group 'org-time
3256 :type 'sexp)
3258 (defun org-time-stamp-format (&optional long inactive)
3259 "Get the right format for a time string."
3260 (let ((f (if long (cdr org-time-stamp-formats)
3261 (car org-time-stamp-formats))))
3262 (if inactive
3263 (concat "[" (substring f 1 -1) "]")
3264 f)))
3266 (defcustom org-deadline-warning-days 14
3267 "Number of days before expiration during which a deadline becomes active.
3268 This variable governs the display in sparse trees and in the agenda.
3269 When 0 or negative, it means use this number (the absolute value of it)
3270 even if a deadline has a different individual lead time specified.
3272 Custom commands can set this variable in the options section."
3273 :group 'org-time
3274 :group 'org-agenda-daily/weekly
3275 :type 'integer)
3277 (defcustom org-scheduled-delay-days 0
3278 "Number of days before a scheduled item becomes active.
3279 This variable governs the display in sparse trees and in the agenda.
3280 The default value (i.e. 0) means: don't delay scheduled item.
3281 When negative, it means use this number (the absolute value of it)
3282 even if a scheduled item has a different individual delay time
3283 specified.
3285 Custom commands can set this variable in the options section."
3286 :group 'org-time
3287 :group 'org-agenda-daily/weekly
3288 :version "24.4"
3289 :package-version '(Org . "8.0")
3290 :type 'integer)
3292 (defcustom org-read-date-prefer-future t
3293 "Non-nil means assume future for incomplete date input from user.
3294 This affects the following situations:
3295 1. The user gives a month but not a year.
3296 For example, if it is April and you enter \"feb 2\", this will be read
3297 as Feb 2, *next* year. \"May 5\", however, will be this year.
3298 2. The user gives a day, but no month.
3299 For example, if today is the 15th, and you enter \"3\", Org will read
3300 this as the third of *next* month. However, if you enter \"17\",
3301 it will be considered as *this* month.
3303 If you set this variable to the symbol `time', then also the following
3304 will work:
3306 3. If the user gives a time.
3307 If the time is before now, it will be interpreted as tomorrow.
3309 Currently none of this works for ISO week specifications.
3311 When this option is nil, the current day, month and year will always be
3312 used as defaults.
3314 See also `org-agenda-jump-prefer-future'."
3315 :group 'org-time
3316 :type '(choice
3317 (const :tag "Never" nil)
3318 (const :tag "Check month and day" t)
3319 (const :tag "Check month, day, and time" time)))
3321 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3322 "Should the agenda jump command prefer the future for incomplete dates?
3323 The default is to do the same as configured in `org-read-date-prefer-future'.
3324 But you can also set a deviating value here.
3325 This may t or nil, or the symbol `org-read-date-prefer-future'."
3326 :group 'org-agenda
3327 :group 'org-time
3328 :version "24.1"
3329 :type '(choice
3330 (const :tag "Use org-read-date-prefer-future"
3331 org-read-date-prefer-future)
3332 (const :tag "Never" nil)
3333 (const :tag "Always" t)))
3335 (defcustom org-read-date-force-compatible-dates t
3336 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3338 Depending on the system Emacs is running on, certain dates cannot
3339 be represented with the type used internally to represent time.
3340 Dates between 1970-1-1 and 2038-1-1 can always be represented
3341 correctly. Some systems allow for earlier dates, some for later,
3342 some for both. One way to find out it to insert any date into an
3343 Org buffer, putting the cursor on the year and hitting S-up and
3344 S-down to test the range.
3346 When this variable is set to t, the date/time prompt will not let
3347 you specify dates outside the 1970-2037 range, so it is certain that
3348 these dates will work in whatever version of Emacs you are
3349 running, and also that you can move a file from one Emacs implementation
3350 to another. WHenever Org is forcing the year for you, it will display
3351 a message and beep.
3353 When this variable is nil, Org will check if the date is
3354 representable in the specific Emacs implementation you are using.
3355 If not, it will force a year, usually the current year, and beep
3356 to remind you. Currently this setting is not recommended because
3357 the likelihood that you will open your Org files in an Emacs that
3358 has limited date range is not negligible.
3360 A workaround for this problem is to use diary sexp dates for time
3361 stamps outside of this range."
3362 :group 'org-time
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-read-date-display-live t
3367 "Non-nil means display current interpretation of date prompt live.
3368 This display will be in an overlay, in the minibuffer."
3369 :group 'org-time
3370 :type 'boolean)
3372 (defcustom org-read-date-popup-calendar t
3373 "Non-nil means pop up a calendar when prompting for a date.
3374 In the calendar, the date can be selected with mouse-1. However, the
3375 minibuffer will also be active, and you can simply enter the date as well.
3376 When nil, only the minibuffer will be available."
3377 :group 'org-time
3378 :type 'boolean)
3379 (defvaralias 'org-popup-calendar-for-date-prompt
3380 'org-read-date-popup-calendar)
3382 (defcustom org-extend-today-until 0
3383 "The hour when your day really ends. Must be an integer.
3384 This has influence for the following applications:
3385 - When switching the agenda to \"today\". It it is still earlier than
3386 the time given here, the day recognized as TODAY is actually yesterday.
3387 - When a date is read from the user and it is still before the time given
3388 here, the current date and time will be assumed to be yesterday, 23:59.
3389 Also, timestamps inserted in capture templates follow this rule.
3391 IMPORTANT: This is a feature whose implementation is and likely will
3392 remain incomplete. Really, it is only here because past midnight seems to
3393 be the favorite working time of John Wiegley :-)"
3394 :group 'org-time
3395 :type 'integer)
3397 (defcustom org-use-effective-time nil
3398 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3399 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3400 \"effective time\" of any timestamps between midnight and 8am will be
3401 23:59 of the previous day."
3402 :group 'org-time
3403 :version "24.1"
3404 :type 'boolean)
3406 (defcustom org-use-last-clock-out-time-as-effective-time nil
3407 "When non-nil, use the last clock out time for `org-todo'.
3408 Note that this option has precedence over the combined use of
3409 `org-use-effective-time' and `org-extend-today-until'."
3410 :group 'org-time
3411 :version "24.4"
3412 :package-version '(Org . "8.0")
3413 :type 'boolean)
3415 (defcustom org-edit-timestamp-down-means-later nil
3416 "Non-nil means S-down will increase the time in a time stamp.
3417 When nil, S-up will increase."
3418 :group 'org-time
3419 :type 'boolean)
3421 (defcustom org-calendar-follow-timestamp-change t
3422 "Non-nil means make the calendar window follow timestamp changes.
3423 When a timestamp is modified and the calendar window is visible, it will be
3424 moved to the new date."
3425 :group 'org-time
3426 :type 'boolean)
3428 (defgroup org-tags nil
3429 "Options concerning tags in Org mode."
3430 :tag "Org Tags"
3431 :group 'org)
3433 (defcustom org-tag-alist nil
3434 "Default tags available in Org files.
3436 The value of this variable is an alist. Associations either:
3438 (TAG)
3439 (TAG . SELECT)
3440 (SPECIAL)
3442 where TAG is a tag as a string, SELECT is character, used to
3443 select that tag through the fast tag selection interface, and
3444 SPECIAL is one of the following keywords: `:startgroup',
3445 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3446 `:newline'. These keywords are used to define a hierarchy of
3447 tags. See manual for details.
3449 When this variable is nil, Org mode bases tag input on what is
3450 already in the buffer. The value can be overridden locally by
3451 using a TAGS keyword, e.g.,
3453 #+TAGS: tag1 tag2
3455 See also `org-tag-persistent-alist' to sidestep this behavior."
3456 :group 'org-tags
3457 :type '(repeat
3458 (choice
3459 (cons (string :tag "Tag name")
3460 (character :tag "Access char"))
3461 (const :tag "Start radio group" (:startgroup))
3462 (const :tag "Start tag group, non distinct" (:startgrouptag))
3463 (const :tag "Group tags delimiter" (:grouptags))
3464 (const :tag "End radio group" (:endgroup))
3465 (const :tag "End tag group, non distinct" (:endgrouptag))
3466 (const :tag "New line" (:newline)))))
3468 (defcustom org-tag-persistent-alist nil
3469 "Tags always available in Org files.
3471 The value of this variable is an alist. Associations either:
3473 (TAG)
3474 (TAG . SELECT)
3475 (SPECIAL)
3477 where TAG is a tag as a string, SELECT is a character, used to
3478 select that tag through the fast tag selection interface, and
3479 SPECIAL is one of the following keywords: `:startgroup',
3480 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3481 `:newline'. These keywords are used to define a hierarchy of
3482 tags. See manual for details.
3484 Unlike to `org-tag-alist', tags defined in this variable do not
3485 depend on a local TAGS keyword. Instead, to disable these tags
3486 on a per-file basis, insert anywhere in the file:
3488 #+STARTUP: noptag"
3489 :group 'org-tags
3490 :type '(repeat
3491 (choice
3492 (cons (string :tag "Tag name")
3493 (character :tag "Access char"))
3494 (const :tag "Start radio group" (:startgroup))
3495 (const :tag "Start tag group, non distinct" (:startgrouptag))
3496 (const :tag "Group tags delimiter" (:grouptags))
3497 (const :tag "End radio group" (:endgroup))
3498 (const :tag "End tag group, non distinct" (:endgrouptag))
3499 (const :tag "New line" (:newline)))))
3501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3502 "If non-nil, always offer completion for all tags of all agenda files.
3503 Instead of customizing this variable directly, you might want to
3504 set it locally for capture buffers, because there no list of
3505 tags in that file can be created dynamically (there are none).
3507 (add-hook \\='org-capture-mode-hook
3508 (lambda ()
3509 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3510 :group 'org-tags
3511 :version "24.1"
3512 :type 'boolean)
3514 (defvar org-file-tags nil
3515 "List of tags that can be inherited by all entries in the file.
3516 The tags will be inherited if the variable `org-use-tag-inheritance'
3517 says they should be.
3518 This variable is populated from #+FILETAGS lines.")
3520 (defcustom org-use-fast-tag-selection 'auto
3521 "Non-nil means use fast tag selection scheme.
3522 This is a special interface to select and deselect tags with single keys.
3523 When nil, fast selection is never used.
3524 When the symbol `auto', fast selection is used if and only if selection
3525 characters for tags have been configured, either through the variable
3526 `org-tag-alist' or through a #+TAGS line in the buffer.
3527 When t, fast selection is always used and selection keys are assigned
3528 automatically if necessary."
3529 :group 'org-tags
3530 :type '(choice
3531 (const :tag "Always" t)
3532 (const :tag "Never" nil)
3533 (const :tag "When selection characters are configured" auto)))
3535 (defcustom org-fast-tag-selection-single-key nil
3536 "Non-nil means fast tag selection exits after first change.
3537 When nil, you have to press RET to exit it.
3538 During fast tag selection, you can toggle this flag with `C-c'.
3539 This variable can also have the value `expert'. In this case, the window
3540 displaying the tags menu is not even shown, until you press C-c again."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No" nil)
3544 (const :tag "Yes" t)
3545 (const :tag "Expert" expert)))
3547 (defvar org-fast-tag-selection-include-todo nil
3548 "Non-nil means fast tags selection interface will also offer TODO states.
3549 This is an undocumented feature, you should not rely on it.")
3551 (defcustom org-tags-column -77
3552 "The column to which tags should be indented in a headline.
3553 If this number is positive, it specifies the column. If it is negative,
3554 it means that the tags should be flushright to that column. For example,
3555 -80 works well for a normal 80 character screen.
3556 When 0, place tags directly after headline text, with only one space in
3557 between."
3558 :group 'org-tags
3559 :type 'integer)
3561 (defcustom org-auto-align-tags t
3562 "Non-nil keeps tags aligned when modifying headlines.
3563 Some operations (i.e. demoting) change the length of a headline and
3564 therefore shift the tags around. With this option turned on, after
3565 each such operation the tags are again aligned to `org-tags-column'."
3566 :group 'org-tags
3567 :type 'boolean)
3569 (defcustom org-use-tag-inheritance t
3570 "Non-nil means tags in levels apply also for sublevels.
3571 When nil, only the tags directly given in a specific line apply there.
3572 This may also be a list of tags that should be inherited, or a regexp that
3573 matches tags that should be inherited. Additional control is possible
3574 with the variable `org-tags-exclude-from-inheritance' which gives an
3575 explicit list of tags to be excluded from inheritance, even if the value of
3576 `org-use-tag-inheritance' would select it for inheritance.
3578 If this option is t, a match early-on in a tree can lead to a large
3579 number of matches in the subtree when constructing the agenda or creating
3580 a sparse tree. If you only want to see the first match in a tree during
3581 a search, check out the variable `org-tags-match-list-sublevels'."
3582 :group 'org-tags
3583 :type '(choice
3584 (const :tag "Not" nil)
3585 (const :tag "Always" t)
3586 (repeat :tag "Specific tags" (string :tag "Tag"))
3587 (regexp :tag "Tags matched by regexp")))
3589 (defcustom org-tags-exclude-from-inheritance nil
3590 "List of tags that should never be inherited.
3591 This is a way to exclude a few tags from inheritance. For way to do
3592 the opposite, to actively allow inheritance for selected tags,
3593 see the variable `org-use-tag-inheritance'."
3594 :group 'org-tags
3595 :type '(repeat (string :tag "Tag")))
3597 (defun org-tag-inherit-p (tag)
3598 "Check if TAG is one that should be inherited."
3599 (cond
3600 ((member tag org-tags-exclude-from-inheritance) nil)
3601 ((eq org-use-tag-inheritance t) t)
3602 ((not org-use-tag-inheritance) nil)
3603 ((stringp org-use-tag-inheritance)
3604 (string-match org-use-tag-inheritance tag))
3605 ((listp org-use-tag-inheritance)
3606 (member tag org-use-tag-inheritance))
3607 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3609 (defcustom org-tags-match-list-sublevels t
3610 "Non-nil means list also sublevels of headlines matching a search.
3611 This variable applies to tags/property searches, and also to stuck
3612 projects because this search is based on a tags match as well.
3614 When set to the symbol `indented', sublevels are indented with
3615 leading dots.
3617 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3618 the sublevels of a headline matching a tag search often also match
3619 the same search. Listing all of them can create very long lists.
3620 Setting this variable to nil causes subtrees of a match to be skipped.
3622 This variable is semi-obsolete and probably should always be true. It
3623 is better to limit inheritance to certain tags using the variables
3624 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3625 :group 'org-tags
3626 :type '(choice
3627 (const :tag "No, don't list them" nil)
3628 (const :tag "Yes, do list them" t)
3629 (const :tag "List them, indented with leading dots" indented)))
3631 (defcustom org-tags-sort-function nil
3632 "When set, tags are sorted using this function as a comparator."
3633 :group 'org-tags
3634 :type '(choice
3635 (const :tag "No sorting" nil)
3636 (const :tag "Alphabetical" string<)
3637 (const :tag "Reverse alphabetical" string>)
3638 (function :tag "Custom function" nil)))
3640 (defvar org-tags-history nil
3641 "History of minibuffer reads for tags.")
3642 (defvar org-last-tags-completion-table nil
3643 "The last used completion table for tags.")
3644 (defvar org-after-tags-change-hook nil
3645 "Hook that is run after the tags in a line have changed.")
3647 (defgroup org-properties nil
3648 "Options concerning properties in Org mode."
3649 :tag "Org Properties"
3650 :group 'org)
3652 (defcustom org-property-format "%-10s %s"
3653 "How property key/value pairs should be formatted by `indent-line'.
3654 When `indent-line' hits a property definition, it will format the line
3655 according to this format, mainly to make sure that the values are
3656 lined-up with respect to each other."
3657 :group 'org-properties
3658 :type 'string)
3660 (defcustom org-properties-postprocess-alist nil
3661 "Alist of properties and functions to adjust inserted values.
3662 Elements of this alist must be of the form
3664 ([string] [function])
3666 where [string] must be a property name and [function] must be a
3667 lambda expression: this lambda expression must take one argument,
3668 the value to adjust, and return the new value as a string.
3670 For example, this element will allow the property \"Remaining\"
3671 to be updated wrt the relation between the \"Effort\" property
3672 and the clock summary:
3674 ((\"Remaining\" (lambda(value)
3675 (let ((clocksum (org-clock-sum-current-item))
3676 (effort (org-duration-to-minutes
3677 (org-entry-get (point) \"Effort\"))))
3678 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3679 :group 'org-properties
3680 :version "24.1"
3681 :type '(alist :key-type (string :tag "Property")
3682 :value-type (function :tag "Function")))
3684 (defcustom org-use-property-inheritance nil
3685 "Non-nil means properties apply also for sublevels.
3687 This setting is chiefly used during property searches. Turning it on can
3688 cause significant overhead when doing a search, which is why it is not
3689 on by default.
3691 When nil, only the properties directly given in the current entry count.
3692 When t, every property is inherited. The value may also be a list of
3693 properties that should have inheritance, or a regular expression matching
3694 properties that should be inherited.
3696 However, note that some special properties use inheritance under special
3697 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3698 and the properties ending in \"_ALL\" when they are used as descriptor
3699 for valid values of a property.
3701 Note for programmers:
3702 When querying an entry with `org-entry-get', you can control if inheritance
3703 should be used. By default, `org-entry-get' looks only at the local
3704 properties. You can request inheritance by setting the inherit argument
3705 to t (to force inheritance) or to `selective' (to respect the setting
3706 in this variable)."
3707 :group 'org-properties
3708 :type '(choice
3709 (const :tag "Not" nil)
3710 (const :tag "Always" t)
3711 (repeat :tag "Specific properties" (string :tag "Property"))
3712 (regexp :tag "Properties matched by regexp")))
3714 (defun org-property-inherit-p (property)
3715 "Return a non-nil value if PROPERTY should be inherited."
3716 (cond
3717 ((eq org-use-property-inheritance t) t)
3718 ((not org-use-property-inheritance) nil)
3719 ((stringp org-use-property-inheritance)
3720 (string-match org-use-property-inheritance property))
3721 ((listp org-use-property-inheritance)
3722 (member-ignore-case property org-use-property-inheritance))
3723 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3725 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3726 "The default column format, if no other format has been defined.
3727 This variable can be set on the per-file basis by inserting a line
3729 #+COLUMNS: %25ITEM ....."
3730 :group 'org-properties
3731 :type 'string)
3733 (defcustom org-columns-ellipses ".."
3734 "The ellipses to be used when a field in column view is truncated.
3735 When this is the empty string, as many characters as possible are shown,
3736 but then there will be no visual indication that the field has been truncated.
3737 When this is a string of length N, the last N characters of a truncated
3738 field are replaced by this string. If the column is narrower than the
3739 ellipses string, only part of the ellipses string will be shown."
3740 :group 'org-properties
3741 :type 'string)
3743 (defconst org-global-properties-fixed
3744 '(("VISIBILITY_ALL" . "folded children content all")
3745 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3746 "List of property/value pairs that can be inherited by any entry.
3748 These are fixed values, for the preset properties. The user variable
3749 that can be used to add to this list is `org-global-properties'.
3751 The entries in this list are cons cells where the car is a property
3752 name and cdr is a string with the value. If the value represents
3753 multiple items like an \"_ALL\" property, separate the items by
3754 spaces.")
3756 (defcustom org-global-properties nil
3757 "List of property/value pairs that can be inherited by any entry.
3759 This list will be combined with the constant `org-global-properties-fixed'.
3761 The entries in this list are cons cells where the car is a property
3762 name and cdr is a string with the value.
3764 You can set buffer-local values for the same purpose in the variable
3765 `org-file-properties' this by adding lines like
3767 #+PROPERTY: NAME VALUE"
3768 :group 'org-properties
3769 :type '(repeat
3770 (cons (string :tag "Property")
3771 (string :tag "Value"))))
3773 (defvar-local org-file-properties nil
3774 "List of property/value pairs that can be inherited by any entry.
3775 Valid for the current buffer.
3776 This variable is populated from #+PROPERTY lines.")
3778 (defgroup org-agenda nil
3779 "Options concerning agenda views in Org mode."
3780 :tag "Org Agenda"
3781 :group 'org)
3783 (defvar-local org-category nil
3784 "Variable used by org files to set a category for agenda display.
3785 Such files should use a file variable to set it, for example
3787 # -*- mode: org; org-category: \"ELisp\"
3789 or contain a special line
3791 #+CATEGORY: ELisp
3793 If the file does not specify a category, then file's base name
3794 is used instead.")
3795 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3797 (defcustom org-agenda-files nil
3798 "The files to be used for agenda display.
3800 If an entry is a directory, all files in that directory that are matched
3801 by `org-agenda-file-regexp' will be part of the file list.
3803 If the value of the variable is not a list but a single file name, then
3804 the list of agenda files is actually stored and maintained in that file,
3805 one agenda file per line. In this file paths can be given relative to
3806 `org-directory'. Tilde expansion and environment variable substitution
3807 are also made.
3809 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3810 and removed with `\\[org-remove-file]'."
3811 :group 'org-agenda
3812 :type '(choice
3813 (repeat :tag "List of files and directories" file)
3814 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3816 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3817 "Regular expression to match files for `org-agenda-files'.
3818 If any element in the list in that variable contains a directory instead
3819 of a normal file, all files in that directory that are matched by this
3820 regular expression will be included."
3821 :group 'org-agenda
3822 :type 'regexp)
3824 (defcustom org-agenda-text-search-extra-files nil
3825 "List of extra files to be searched by text search commands.
3826 These files will be searched in addition to the agenda files by the
3827 commands `org-search-view' (`\\[org-agenda] s') \
3828 and `org-occur-in-agenda-files'.
3829 Note that these files will only be searched for text search commands,
3830 not for the other agenda views like todo lists, tag searches or the weekly
3831 agenda. This variable is intended to list notes and possibly archive files
3832 that should also be searched by these two commands.
3833 In fact, if the first element in the list is the symbol `agenda-archives',
3834 then all archive files of all agenda files will be added to the search
3835 scope."
3836 :group 'org-agenda
3837 :type '(set :greedy t
3838 (const :tag "Agenda Archives" agenda-archives)
3839 (repeat :inline t (file))))
3841 (defvaralias 'org-agenda-multi-occur-extra-files
3842 'org-agenda-text-search-extra-files)
3844 (defcustom org-agenda-skip-unavailable-files nil
3845 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3846 A nil value means to remove them, after a query, from the list."
3847 :group 'org-agenda
3848 :type 'boolean)
3850 (defcustom org-calendar-to-agenda-key [?c]
3851 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3852 The command `org-calendar-goto-agenda' will be bound to this key. The
3853 default is the character `c' because then `c' can be used to switch back and
3854 forth between agenda and calendar."
3855 :group 'org-agenda
3856 :type 'sexp)
3858 (defcustom org-calendar-insert-diary-entry-key [?i]
3859 "The key to be installed in `calendar-mode-map' for adding diary entries.
3860 This option is irrelevant until `org-agenda-diary-file' has been configured
3861 to point to an Org file. When that is the case, the command
3862 `org-agenda-diary-entry' will be bound to the key given here, by default
3863 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3864 if you want to continue doing this, you need to change this to a different
3865 key."
3866 :group 'org-agenda
3867 :type 'sexp)
3869 (defcustom org-agenda-diary-file 'diary-file
3870 "File to which to add new entries with the `i' key in agenda and calendar.
3871 When this is the symbol `diary-file', the functionality in the Emacs
3872 calendar will be used to add entries to the `diary-file'. But when this
3873 points to a file, `org-agenda-diary-entry' will be used instead."
3874 :group 'org-agenda
3875 :type '(choice
3876 (const :tag "The standard Emacs diary file" diary-file)
3877 (file :tag "Special Org file diary entries")))
3879 (eval-after-load "calendar"
3880 '(progn
3881 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3882 'org-calendar-goto-agenda)
3883 (add-hook 'calendar-mode-hook
3884 (lambda ()
3885 (unless (eq org-agenda-diary-file 'diary-file)
3886 (define-key calendar-mode-map
3887 org-calendar-insert-diary-entry-key
3888 'org-agenda-diary-entry))))))
3890 (defgroup org-latex nil
3891 "Options for embedding LaTeX code into Org mode."
3892 :tag "Org LaTeX"
3893 :group 'org)
3895 (defcustom org-format-latex-options
3896 '(:foreground default :background default :scale 1.0
3897 :html-foreground "Black" :html-background "Transparent"
3898 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3899 "Options for creating images from LaTeX fragments.
3900 This is a property list with the following properties:
3901 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3902 `default' means use the foreground of the default face.
3903 `auto' means use the foreground from the text face.
3904 :background the background color, or \"Transparent\".
3905 `default' means use the background of the default face.
3906 `auto' means use the background from the text face.
3907 :scale a scaling factor for the size of the images, to get more pixels
3908 :html-foreground, :html-background, :html-scale
3909 the same numbers for HTML export.
3910 :matchers a list indicating which matchers should be used to
3911 find LaTeX fragments. Valid members of this list are:
3912 \"begin\" find environments
3913 \"$1\" find single characters surrounded by $.$
3914 \"$\" find math expressions surrounded by $...$
3915 \"$$\" find math expressions surrounded by $$....$$
3916 \"\\(\" find math expressions surrounded by \\(...\\)
3917 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3918 :group 'org-latex
3919 :type 'plist)
3921 (defcustom org-format-latex-signal-error t
3922 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3923 When nil, just push out a message."
3924 :group 'org-latex
3925 :version "24.1"
3926 :type 'boolean)
3928 (defcustom org-latex-to-mathml-jar-file nil
3929 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3930 Use this to specify additional executable file say a jar file.
3932 When using MathToWeb as the converter, specify the full-path to
3933 your mathtoweb.jar file."
3934 :group 'org-latex
3935 :version "24.1"
3936 :type '(choice
3937 (const :tag "None" nil)
3938 (file :tag "JAR file" :must-match t)))
3940 (defcustom org-latex-to-mathml-convert-command nil
3941 "Command to convert LaTeX fragments to MathML.
3942 Replace format-specifiers in the command as noted below and use
3943 `shell-command' to convert LaTeX to MathML.
3944 %j: Executable file in fully expanded form as specified by
3945 `org-latex-to-mathml-jar-file'.
3946 %I: Input LaTeX file in fully expanded form.
3947 %i: The latex fragment to be converted.
3948 %o: Output MathML file.
3950 This command is used by `org-create-math-formula'.
3952 When using MathToWeb as the converter, set this option to
3953 \"java -jar %j -unicode -force -df %o %I\".
3955 When using LaTeXML set this option to
3956 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3957 :group 'org-latex
3958 :version "24.1"
3959 :type '(choice
3960 (const :tag "None" nil)
3961 (string :tag "\nShell command")))
3963 (defcustom org-preview-latex-default-process 'dvipng
3964 "The default process to convert LaTeX fragments to image files.
3965 All available processes and theirs documents can be found in
3966 `org-preview-latex-process-alist', which see."
3967 :group 'org-latex
3968 :version "26.1"
3969 :package-version '(Org . "9.0")
3970 :type 'symbol)
3972 (defcustom org-preview-latex-process-alist
3973 '((dvipng
3974 :programs ("latex" "dvipng")
3975 :description "dvi > png"
3976 :message "you need to install the programs: latex and dvipng."
3977 :image-input-type "dvi"
3978 :image-output-type "png"
3979 :image-size-adjust (1.0 . 1.0)
3980 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3981 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3982 (dvisvgm
3983 :programs ("latex" "dvisvgm")
3984 :description "dvi > svg"
3985 :message "you need to install the programs: latex and dvisvgm."
3986 :use-xcolor t
3987 :image-input-type "dvi"
3988 :image-output-type "svg"
3989 :image-size-adjust (1.7 . 1.5)
3990 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3991 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3992 (imagemagick
3993 :programs ("latex" "convert")
3994 :description "pdf > png"
3995 :message "you need to install the programs: latex and imagemagick."
3996 :use-xcolor t
3997 :image-input-type "pdf"
3998 :image-output-type "png"
3999 :image-size-adjust (1.0 . 1.0)
4000 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4001 :image-converter
4002 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4003 "Definitions of external processes for LaTeX previewing.
4004 Org mode can use some external commands to generate TeX snippet's images for
4005 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4006 `org-create-formula-image' how to call them.
4008 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4009 PROPERTIES accepts the following attributes:
4011 :programs list of strings, required programs.
4012 :description string, describe the process.
4013 :message string, message it when required programs cannot be found.
4014 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4015 :image-output-type string, output file type of image converter (e.g., \"png\").
4016 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4017 deal with background and foreground color of image.
4018 Otherwise, dvipng style background and foregroud color
4019 format are generated. You may then refer to them in
4020 command options with \"%F\" and \"%B\".
4021 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4022 image size showed in buffer and the cdr element is for
4023 HTML file. This option is only useful for process
4024 developers, users should use variable
4025 `org-format-latex-options' instead.
4026 :post-clean list of strings, files matched are to be cleaned up once
4027 the image is generated. When nil, the files with \".dvi\",
4028 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4029 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4030 be cleaned up.
4031 :latex-header list of strings, the LaTeX header of the snippet file.
4032 When nil, the fallback value is used instead, which is
4033 controlled by `org-format-latex-header',
4034 `org-latex-default-packages-alist' and
4035 `org-latex-packages-alist', which see.
4036 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4037 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4038 replaced with values defined below.
4039 :image-converter list of image converter commands strings. Each of them is
4040 given to the shell and supports any of the following
4041 place-holders defined below.
4043 Place-holders used by `:image-converter' and `:latex-compiler':
4045 %f input file name
4046 %b base name of input file
4047 %o base directory of input file
4048 %O absolute output file name
4050 Place-holders only used by `:image-converter':
4052 %F foreground of image
4053 %B background of image
4054 %D dpi, which is used to adjust image size by some processing commands.
4055 %S the image size scale ratio, which is used to adjust image size by some
4056 processing commands."
4057 :group 'org-latex
4058 :version "26.1"
4059 :package-version '(Org . "9.0")
4060 :type '(alist :tag "LaTeX to image backends"
4061 :value-type (plist)))
4063 (defcustom org-preview-latex-image-directory "ltximg/"
4064 "Path to store latex preview images.
4065 A relative path here creates many directories relative to the
4066 processed org files paths. An absolute path puts all preview
4067 images at the same place."
4068 :group 'org-latex
4069 :version "26.1"
4070 :package-version '(Org . "9.0")
4071 :type 'string)
4073 (defun org-format-latex-mathml-available-p ()
4074 "Return t if `org-latex-to-mathml-convert-command' is usable."
4075 (save-match-data
4076 (when (and (boundp 'org-latex-to-mathml-convert-command)
4077 org-latex-to-mathml-convert-command)
4078 (let ((executable (car (split-string
4079 org-latex-to-mathml-convert-command))))
4080 (when (executable-find executable)
4081 (if (string-match
4082 "%j" org-latex-to-mathml-convert-command)
4083 (file-readable-p org-latex-to-mathml-jar-file)
4084 t))))))
4086 (defcustom org-format-latex-header "\\documentclass{article}
4087 \\usepackage[usenames]{color}
4088 \[PACKAGES]
4089 \[DEFAULT-PACKAGES]
4090 \\pagestyle{empty} % do not remove
4091 % The settings below are copied from fullpage.sty
4092 \\setlength{\\textwidth}{\\paperwidth}
4093 \\addtolength{\\textwidth}{-3cm}
4094 \\setlength{\\oddsidemargin}{1.5cm}
4095 \\addtolength{\\oddsidemargin}{-2.54cm}
4096 \\setlength{\\evensidemargin}{\\oddsidemargin}
4097 \\setlength{\\textheight}{\\paperheight}
4098 \\addtolength{\\textheight}{-\\headheight}
4099 \\addtolength{\\textheight}{-\\headsep}
4100 \\addtolength{\\textheight}{-\\footskip}
4101 \\addtolength{\\textheight}{-3cm}
4102 \\setlength{\\topmargin}{1.5cm}
4103 \\addtolength{\\topmargin}{-2.54cm}"
4104 "The document header used for processing LaTeX fragments.
4105 It is imperative that this header make sure that no page number
4106 appears on the page. The package defined in the variables
4107 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4108 will either replace the placeholder \"[PACKAGES]\" in this
4109 header, or they will be appended."
4110 :group 'org-latex
4111 :type 'string)
4113 (defun org-set-packages-alist (var val)
4114 "Set the packages alist and make sure it has 3 elements per entry."
4115 (set var (mapcar (lambda (x)
4116 (if (and (consp x) (= (length x) 2))
4117 (list (car x) (nth 1 x) t)
4119 val)))
4121 (defun org-get-packages-alist (var)
4122 "Get the packages alist and make sure it has 3 elements per entry."
4123 (mapcar (lambda (x)
4124 (if (and (consp x) (= (length x) 2))
4125 (list (car x) (nth 1 x) t)
4127 (default-value var)))
4129 (defcustom org-latex-default-packages-alist
4130 '(("AUTO" "inputenc" t ("pdflatex"))
4131 ("T1" "fontenc" t ("pdflatex"))
4132 ("" "graphicx" t)
4133 ("" "grffile" t)
4134 ("" "longtable" nil)
4135 ("" "wrapfig" nil)
4136 ("" "rotating" nil)
4137 ("normalem" "ulem" t)
4138 ("" "amsmath" t)
4139 ("" "textcomp" t)
4140 ("" "amssymb" t)
4141 ("" "capt-of" nil)
4142 ("" "hyperref" nil))
4143 "Alist of default packages to be inserted in the header.
4145 Change this only if one of the packages here causes an
4146 incompatibility with another package you are using.
4148 The packages in this list are needed by one part or another of
4149 Org mode to function properly:
4151 - inputenc, fontenc: for basic font and character selection
4152 - graphicx: for including images
4153 - grffile: allow periods and spaces in graphics file names
4154 - longtable: For multipage tables
4155 - wrapfig: for figure placement
4156 - rotating: for sideways figures and tables
4157 - ulem: for underline and strike-through
4158 - amsmath: for subscript and superscript and math environments
4159 - textcomp, amssymb: for various symbols used
4160 for interpreting the entities in `org-entities'. You can skip
4161 some of these packages if you don't use any of their symbols.
4162 - capt-of: for captions outside of floats
4163 - hyperref: for cross references
4165 Therefore you should not modify this variable unless you know
4166 what you are doing. The one reason to change it anyway is that
4167 you might be loading some other package that conflicts with one
4168 of the default packages. Each element is either a cell or
4169 a string.
4171 A cell is of the format
4173 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4175 If SNIPPET-FLAG is non-nil, the package also needs to be included
4176 when compiling LaTeX snippets into images for inclusion into
4177 non-LaTeX output. COMPILERS is a list of compilers that should
4178 include the package, see `org-latex-compiler'. If the document
4179 compiler is not in the list, and the list is non-nil, the package
4180 will not be inserted in the final document.
4182 A string will be inserted as-is in the header of the document."
4183 :group 'org-latex
4184 :group 'org-export-latex
4185 :set 'org-set-packages-alist
4186 :get 'org-get-packages-alist
4187 :version "26.1"
4188 :package-version '(Org . "8.3")
4189 :type '(repeat
4190 (choice
4191 (list :tag "options/package pair"
4192 (string :tag "options")
4193 (string :tag "package")
4194 (boolean :tag "Snippet"))
4195 (string :tag "A line of LaTeX"))))
4197 (defcustom org-latex-packages-alist nil
4198 "Alist of packages to be inserted in every LaTeX header.
4200 These will be inserted after `org-latex-default-packages-alist'.
4201 Each element is either a cell or a string.
4203 A cell is of the format:
4205 (\"options\" \"package\" SNIPPET-FLAG)
4207 SNIPPET-FLAG, when non-nil, indicates that this package is also
4208 needed when turning LaTeX snippets into images for inclusion into
4209 non-LaTeX output.
4211 A string will be inserted as-is in the header of the document.
4213 Make sure that you only list packages here which:
4215 - you want in every file;
4216 - do not conflict with the setup in `org-format-latex-header';
4217 - do not conflict with the default packages in
4218 `org-latex-default-packages-alist'."
4219 :group 'org-latex
4220 :group 'org-export-latex
4221 :set 'org-set-packages-alist
4222 :get 'org-get-packages-alist
4223 :type '(repeat
4224 (choice
4225 (list :tag "options/package pair"
4226 (string :tag "options")
4227 (string :tag "package")
4228 (boolean :tag "Snippet"))
4229 (string :tag "A line of LaTeX"))))
4231 (defgroup org-appearance nil
4232 "Settings for Org mode appearance."
4233 :tag "Org Appearance"
4234 :group 'org)
4236 (defcustom org-level-color-stars-only nil
4237 "Non-nil means fontify only the stars in each headline.
4238 When nil, the entire headline is fontified.
4239 Changing it requires restart of `font-lock-mode' to become effective
4240 also in regions already fontified."
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-hide-leading-stars nil
4245 "Non-nil means hide the first N-1 stars in a headline.
4246 This works by using the face `org-hide' for these stars. This
4247 face is white for a light background, and black for a dark
4248 background. You may have to customize the face `org-hide' to
4249 make this work.
4250 Changing it requires restart of `font-lock-mode' to become effective
4251 also in regions already fontified.
4252 You may also set this on a per-file basis by adding one of the following
4253 lines to the buffer:
4255 #+STARTUP: hidestars
4256 #+STARTUP: showstars"
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-hidden-keywords nil
4261 "List of symbols corresponding to keywords to be hidden the org buffer.
4262 For example, a value \\='(title) for this list will make the document's title
4263 appear in the buffer without the initial #+TITLE: keyword."
4264 :group 'org-appearance
4265 :version "24.1"
4266 :type '(set (const :tag "#+AUTHOR" author)
4267 (const :tag "#+DATE" date)
4268 (const :tag "#+EMAIL" email)
4269 (const :tag "#+TITLE" title)))
4271 (defcustom org-custom-properties nil
4272 "List of properties (as strings) with a special meaning.
4273 The default use of these custom properties is to let the user
4274 hide them with `org-toggle-custom-properties-visibility'."
4275 :group 'org-properties
4276 :group 'org-appearance
4277 :version "24.3"
4278 :type '(repeat (string :tag "Property Name")))
4280 (defcustom org-fontify-done-headline nil
4281 "Non-nil means change the face of a headline if it is marked DONE.
4282 Normally, only the TODO/DONE keyword indicates the state of a headline.
4283 When this is non-nil, the headline after the keyword is set to the
4284 `org-headline-done' as an additional indication."
4285 :group 'org-appearance
4286 :type 'boolean)
4288 (defcustom org-fontify-emphasized-text t
4289 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4290 Changing this variable requires a restart of Emacs to take effect."
4291 :group 'org-appearance
4292 :type 'boolean)
4294 (defcustom org-fontify-whole-heading-line nil
4295 "Non-nil means fontify the whole line for headings.
4296 This is useful when setting a background color for the
4297 org-level-* faces."
4298 :group 'org-appearance
4299 :type 'boolean)
4301 (defcustom org-highlight-latex-and-related nil
4302 "Non-nil means highlight LaTeX related syntax in the buffer.
4303 When non nil, the value should be a list containing any of the
4304 following symbols:
4305 `latex' Highlight LaTeX snippets and environments.
4306 `script' Highlight subscript and superscript.
4307 `entities' Highlight entities."
4308 :group 'org-appearance
4309 :version "24.4"
4310 :package-version '(Org . "8.0")
4311 :type '(choice
4312 (const :tag "No highlighting" nil)
4313 (set :greedy t :tag "Highlight"
4314 (const :tag "LaTeX snippets and environments" latex)
4315 (const :tag "Subscript and superscript" script)
4316 (const :tag "Entities" entities))))
4318 (defcustom org-hide-emphasis-markers nil
4319 "Non-nil mean font-lock should hide the emphasis marker characters."
4320 :group 'org-appearance
4321 :type 'boolean)
4323 (defcustom org-hide-macro-markers nil
4324 "Non-nil mean font-lock should hide the brackets marking macro calls."
4325 :group 'org-appearance
4326 :type 'boolean)
4328 (defcustom org-pretty-entities nil
4329 "Non-nil means show entities as UTF8 characters.
4330 When nil, the \\name form remains in the buffer."
4331 :group 'org-appearance
4332 :version "24.1"
4333 :type 'boolean)
4335 (defcustom org-pretty-entities-include-sub-superscripts t
4336 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4337 :group 'org-appearance
4338 :version "24.1"
4339 :type 'boolean)
4341 (defvar org-emph-re nil
4342 "Regular expression for matching emphasis.
4343 After a match, the match groups contain these elements:
4344 0 The match of the full regular expression, including the characters
4345 before and after the proper match
4346 1 The character before the proper match, or empty at beginning of line
4347 2 The proper match, including the leading and trailing markers
4348 3 The leading marker like * or /, indicating the type of highlighting
4349 4 The text between the emphasis markers, not including the markers
4350 5 The character after the match, empty at the end of a line")
4352 (defvar org-verbatim-re nil
4353 "Regular expression for matching verbatim text.")
4355 (defvar org-emphasis-regexp-components) ; defined just below
4356 (defvar org-emphasis-alist) ; defined just below
4357 (defun org-set-emph-re (var val)
4358 "Set variable and compute the emphasis regular expression."
4359 (set var val)
4360 (when (and (boundp 'org-emphasis-alist)
4361 (boundp 'org-emphasis-regexp-components)
4362 org-emphasis-alist org-emphasis-regexp-components)
4363 (pcase-let*
4364 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4365 (body (if (<= nl 0) body
4366 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4367 (template
4368 (format (concat "\\([%s]\\|^\\)" ;before markers
4369 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4370 "\\([%s]\\|$\\)") ;after markers
4371 pre border border body border post)))
4372 (setq org-emph-re (format template "*/_+"))
4373 (setq org-verbatim-re (format template "=~")))))
4375 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4376 ;; set this option proved cumbersome. See this message/thread:
4377 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4378 (defvar org-emphasis-regexp-components
4379 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4380 "Components used to build the regular expression for emphasis.
4381 This is a list with five entries. Terminology: In an emphasis string
4382 like \" *strong word* \", we call the initial space PREMATCH, the final
4383 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4384 and \"trong wor\" is the body. The different components in this variable
4385 specify what is allowed/forbidden in each part:
4387 pre Chars allowed as prematch. Beginning of line will be allowed too.
4388 post Chars allowed as postmatch. End of line will be allowed too.
4389 border The chars *forbidden* as border characters.
4390 body-regexp A regexp like \".\" to match a body character. Don't use
4391 non-shy groups here, and don't allow newline here.
4392 newline The maximum number of newlines allowed in an emphasis exp.
4394 You need to reload Org or to restart Emacs after customizing this.")
4396 (defcustom org-emphasis-alist
4397 '(("*" bold)
4398 ("/" italic)
4399 ("_" underline)
4400 ("=" org-verbatim verbatim)
4401 ("~" org-code verbatim)
4402 ("+" (:strike-through t)))
4403 "Alist of characters and faces to emphasize text.
4404 Text starting and ending with a special character will be emphasized,
4405 for example *bold*, _underlined_ and /italic/. This variable sets the
4406 marker characters and the face to be used by font-lock for highlighting
4407 in Org buffers.
4409 You need to reload Org or to restart Emacs after customizing this."
4410 :group 'org-appearance
4411 :set 'org-set-emph-re
4412 :version "24.4"
4413 :package-version '(Org . "8.0")
4414 :type '(repeat
4415 (list
4416 (string :tag "Marker character")
4417 (choice
4418 (face :tag "Font-lock-face")
4419 (plist :tag "Face property list"))
4420 (option (const verbatim)))))
4422 (defvar org-protecting-blocks '("src" "example" "export")
4423 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4424 This is needed for font-lock setup.")
4426 ;;; Functions and variables from their packages
4427 ;; Declared here to avoid compiler warnings
4428 (defvar mark-active)
4430 ;; Various packages
4431 (declare-function calc-eval "calc" (str &optional separator &rest args))
4432 (declare-function calendar-forward-day "cal-move" (arg))
4433 (declare-function calendar-goto-date "cal-move" (date))
4434 (declare-function calendar-goto-today "cal-move" ())
4435 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4436 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4437 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4438 (declare-function cdlatex-tab "ext:cdlatex" ())
4439 (declare-function dired-get-filename
4440 "dired"
4441 (&optional localp no-error-if-not-filep))
4442 (declare-function iswitchb-read-buffer
4443 "iswitchb"
4444 (prompt &optional
4445 default require-match _predicate start matches-set))
4446 (declare-function org-agenda-change-all-lines
4447 "org-agenda"
4448 (newhead hdmarker &optional fixface just-this))
4449 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4450 "org-agenda"
4451 (&optional end))
4452 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4453 (declare-function org-agenda-format-item
4454 "org-agenda"
4455 (extra txt &optional level category tags dotime
4456 remove-re habitp))
4457 (declare-function org-agenda-maybe-redo "org-agenda" ())
4458 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4459 (declare-function org-agenda-save-markers-for-cut-and-paste
4460 "org-agenda"
4461 (beg end))
4462 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4463 (declare-function org-agenda-skip "org-agenda" ())
4464 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4465 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4466 (declare-function org-indent-mode "org-indent" (&optional arg))
4467 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4468 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4469 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4470 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4471 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4472 (declare-function parse-time-string "parse-time" (string))
4473 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4475 (defvar align-mode-rules-list)
4476 (defvar calc-embedded-close-formula)
4477 (defvar calc-embedded-open-formula)
4478 (defvar calc-embedded-open-mode)
4479 (defvar font-lock-unfontify-region-function)
4480 (defvar iswitchb-temp-buflist)
4481 (defvar org-agenda-tags-todo-honor-ignore-options)
4482 (defvar remember-data-file)
4483 (defvar texmathp-why)
4485 ;;;###autoload
4486 (defun turn-on-orgtbl ()
4487 "Unconditionally turn on `orgtbl-mode'."
4488 (require 'org-table)
4489 (orgtbl-mode 1))
4491 (defun org-at-table-p (&optional table-type)
4492 "Non-nil if the cursor is inside an Org table.
4493 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4494 If `org-enable-table-editor' is nil, return nil unconditionally."
4495 (and
4496 org-enable-table-editor
4497 (save-excursion
4498 (beginning-of-line)
4499 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4500 (or (not (derived-mode-p 'org-mode))
4501 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4502 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4504 (defun org-at-table.el-p ()
4505 "Non-nil when point is at a table.el table."
4506 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4507 (let ((element (org-element-at-point)))
4508 (and (eq (org-element-type element) 'table)
4509 (eq (org-element-property :type element) 'table.el)))))
4511 (defun org-at-table-hline-p ()
4512 "Non-nil when point is inside a hline in a table.
4513 Assume point is already in a table. If `org-enable-table-editor'
4514 is nil, return nil unconditionally."
4515 (and org-enable-table-editor
4516 (save-excursion
4517 (beginning-of-line)
4518 (looking-at org-table-hline-regexp))))
4520 (defun org-table-map-tables (function &optional quietly)
4521 "Apply FUNCTION to the start of all tables in the buffer."
4522 (org-with-wide-buffer
4523 (goto-char (point-min))
4524 (while (re-search-forward org-table-any-line-regexp nil t)
4525 (unless quietly
4526 (message "Mapping tables: %d%%"
4527 (floor (* 100.0 (point)) (buffer-size))))
4528 (beginning-of-line 1)
4529 (when (and (looking-at org-table-line-regexp)
4530 ;; Exclude tables in src/example/verbatim/clocktable blocks
4531 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4532 (save-excursion (funcall function))
4533 (or (looking-at org-table-line-regexp)
4534 (forward-char 1)))
4535 (re-search-forward org-table-any-border-regexp nil 1)))
4536 (unless quietly (message "Mapping tables: done")))
4538 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4539 (declare-function org-clock-update-mode-line "org-clock" ())
4540 (declare-function org-resolve-clocks "org-clock"
4541 (&optional also-non-dangling-p prompt last-valid))
4543 (defun org-at-TBLFM-p (&optional pos)
4544 "Non-nil when point (or POS) is in #+TBLFM line."
4545 (save-excursion
4546 (goto-char (or pos (point)))
4547 (beginning-of-line)
4548 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4549 (eq (org-element-type (org-element-at-point)) 'table))))
4551 (defvar org-clock-start-time)
4552 (defvar org-clock-marker (make-marker)
4553 "Marker recording the last clock-in.")
4554 (defvar org-clock-hd-marker (make-marker)
4555 "Marker recording the last clock-in, but the headline position.")
4556 (defvar org-clock-heading ""
4557 "The heading of the current clock entry.")
4558 (defun org-clock-is-active ()
4559 "Return the buffer where the clock is currently running.
4560 Return nil if no clock is running."
4561 (marker-buffer org-clock-marker))
4563 (defun org-check-running-clock ()
4564 "Check if the current buffer contains the running clock.
4565 If yes, offer to stop it and to save the buffer with the changes."
4566 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4567 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4568 (buffer-name))))
4569 (org-clock-out)
4570 (when (y-or-n-p "Save changed buffer?")
4571 (save-buffer))))
4573 (defun org-clocktable-try-shift (dir n)
4574 "Check if this line starts a clock table, if yes, shift the time block."
4575 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4576 (org-clocktable-shift dir n)))
4578 ;;;###autoload
4579 (defun org-clock-persistence-insinuate ()
4580 "Set up hooks for clock persistence."
4581 (require 'org-clock)
4582 (add-hook 'org-mode-hook 'org-clock-load)
4583 (add-hook 'kill-emacs-hook 'org-clock-save))
4585 (defgroup org-archive nil
4586 "Options concerning archiving in Org mode."
4587 :tag "Org Archive"
4588 :group 'org-structure)
4590 (defcustom org-archive-location "%s_archive::"
4591 "The location where subtrees should be archived.
4593 The value of this variable is a string, consisting of two parts,
4594 separated by a double-colon. The first part is a filename and
4595 the second part is a headline.
4597 When the filename is omitted, archiving happens in the same file.
4598 %s in the filename will be replaced by the current file
4599 name (without the directory part). Archiving to a different file
4600 is useful to keep archived entries from contributing to the
4601 Org Agenda.
4603 The archived entries will be filed as subtrees of the specified
4604 headline. When the headline is omitted, the subtrees are simply
4605 filed away at the end of the file, as top-level entries. Also in
4606 the heading you can use %s to represent the file name, this can be
4607 useful when using the same archive for a number of different files.
4609 Here are a few examples:
4610 \"%s_archive::\"
4611 If the current file is Projects.org, archive in file
4612 Projects.org_archive, as top-level trees. This is the default.
4614 \"::* Archived Tasks\"
4615 Archive in the current file, under the top-level headline
4616 \"* Archived Tasks\".
4618 \"~/org/archive.org::\"
4619 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4621 \"~/org/archive.org::* From %s\"
4622 Archive in file ~/org/archive.org (absolute path), under headlines
4623 \"From FILENAME\" where file name is the current file name.
4625 \"~/org/datetree.org::datetree/* Finished Tasks\"
4626 The \"datetree/\" string is special, signifying to archive
4627 items to the datetree. Items are placed in either the CLOSED
4628 date of the item, or the current date if there is no CLOSED date.
4629 The heading will be a subentry to the current date. There doesn't
4630 need to be a heading, but there always needs to be a slash after
4631 datetree. For example, to store archived items directly in the
4632 datetree, use \"~/org/datetree.org::datetree/\".
4634 \"basement::** Finished Tasks\"
4635 Archive in file ./basement (relative path), as level 3 trees
4636 below the level 2 heading \"** Finished Tasks\".
4638 You may set this option on a per-file basis by adding to the buffer a
4639 line like
4641 #+ARCHIVE: basement::** Finished Tasks
4643 You may also define it locally for a subtree by setting an ARCHIVE property
4644 in the entry. If such a property is found in an entry, or anywhere up
4645 the hierarchy, it will be used."
4646 :group 'org-archive
4647 :type 'string)
4649 (defcustom org-agenda-skip-archived-trees t
4650 "Non-nil means the agenda will skip any items located in archived trees.
4651 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4652 variable is no longer recommended, you should leave it at the value t.
4653 Instead, use the key `v' to cycle the archives-mode in the agenda."
4654 :group 'org-archive
4655 :group 'org-agenda-skip
4656 :type 'boolean)
4658 (defcustom org-columns-skip-archived-trees t
4659 "Non-nil means ignore archived trees when creating column view."
4660 :group 'org-archive
4661 :group 'org-properties
4662 :type 'boolean)
4664 (defcustom org-cycle-open-archived-trees nil
4665 "Non-nil means `org-cycle' will open archived trees.
4666 An archived tree is a tree marked with the tag ARCHIVE.
4667 When nil, archived trees will stay folded. You can still open them with
4668 normal outline commands like `show-all', but not with the cycling commands."
4669 :group 'org-archive
4670 :group 'org-cycle
4671 :type 'boolean)
4673 (defcustom org-sparse-tree-open-archived-trees nil
4674 "Non-nil means sparse tree construction shows matches in archived trees.
4675 When nil, matches in these trees are highlighted, but the trees are kept in
4676 collapsed state."
4677 :group 'org-archive
4678 :group 'org-sparse-trees
4679 :type 'boolean)
4681 (defcustom org-sparse-tree-default-date-type nil
4682 "The default date type when building a sparse tree.
4683 When this is nil, a date is a scheduled or a deadline timestamp.
4684 Otherwise, these types are allowed:
4686 all: all timestamps
4687 active: only active timestamps (<...>)
4688 inactive: only inactive timestamps ([...])
4689 scheduled: only scheduled timestamps
4690 deadline: only deadline timestamps"
4691 :type '(choice (const :tag "Scheduled or deadline" nil)
4692 (const :tag "All timestamps" all)
4693 (const :tag "Only active timestamps" active)
4694 (const :tag "Only inactive timestamps" inactive)
4695 (const :tag "Only scheduled timestamps" scheduled)
4696 (const :tag "Only deadline timestamps" deadline)
4697 (const :tag "Only closed timestamps" closed))
4698 :version "26.1"
4699 :package-version '(Org . "8.3")
4700 :group 'org-sparse-trees)
4702 (defun org-cycle-hide-archived-subtrees (state)
4703 "Re-hide all archived subtrees after a visibility state change."
4704 (when (and (not org-cycle-open-archived-trees)
4705 (not (memq state '(overview folded))))
4706 (save-excursion
4707 (let* ((globalp (memq state '(contents all)))
4708 (beg (if globalp (point-min) (point)))
4709 (end (if globalp (point-max) (org-end-of-subtree t))))
4710 (org-hide-archived-subtrees beg end)
4711 (goto-char beg)
4712 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4713 (message "%s" (substitute-command-keys
4714 "Subtree is archived and stays closed. Use \
4715 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4717 (defun org-force-cycle-archived ()
4718 "Cycle subtree even if it is archived."
4719 (interactive)
4720 (setq this-command 'org-cycle)
4721 (let ((org-cycle-open-archived-trees t))
4722 (call-interactively 'org-cycle)))
4724 (defun org-hide-archived-subtrees (beg end)
4725 "Re-hide all archived subtrees after a visibility state change."
4726 (org-with-wide-buffer
4727 (let ((case-fold-search nil)
4728 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4729 (goto-char beg)
4730 ;; Include headline point is currently on.
4731 (beginning-of-line)
4732 (while (and (< (point) end) (re-search-forward re end t))
4733 (when (member org-archive-tag (org-get-tags))
4734 (org-flag-subtree t)
4735 (org-end-of-subtree t))))))
4737 (declare-function outline-end-of-heading "outline" ())
4738 (declare-function outline-flag-region "outline" (from to flag))
4739 (defun org-flag-subtree (flag)
4740 (save-excursion
4741 (org-back-to-heading t)
4742 (outline-end-of-heading)
4743 (outline-flag-region (point)
4744 (progn (org-end-of-subtree t) (point))
4745 flag)))
4747 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4749 ;; Declare Column View Code
4751 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4752 (declare-function org-columns-compute "org-colview" (property))
4754 ;; Declare ID code
4756 (declare-function org-id-store-link "org-id")
4757 (declare-function org-id-locations-load "org-id")
4758 (declare-function org-id-locations-save "org-id")
4759 (defvar org-id-track-globally)
4761 ;;; Variables for pre-computed regular expressions, all buffer local
4763 (defvar-local org-todo-regexp nil
4764 "Matches any of the TODO state keywords.
4765 Since TODO keywords are case-sensitive, `case-fold-search' is
4766 expected to be bound to nil when matching against this regexp.")
4768 (defvar-local org-not-done-regexp nil
4769 "Matches any of the TODO state keywords except the last one.
4770 Since TODO keywords are case-sensitive, `case-fold-search' is
4771 expected to be bound to nil when matching against this regexp.")
4773 (defvar-local org-not-done-heading-regexp nil
4774 "Matches a TODO headline that is not done.
4775 Since TODO keywords are case-sensitive, `case-fold-search' is
4776 expected to be bound to nil when matching against this regexp.")
4778 (defvar-local org-todo-line-regexp nil
4779 "Matches a headline and puts TODO state into group 2 if present.
4780 Since TODO keywords are case-sensitive, `case-fold-search' is
4781 expected to be bound to nil when matching against this regexp.")
4783 (defvar-local org-complex-heading-regexp nil
4784 "Matches a headline and puts everything into groups:
4786 group 1: Stars
4787 group 2: The TODO keyword, maybe
4788 group 3: Priority cookie
4789 group 4: True headline
4790 group 5: Tags
4792 Since TODO keywords are case-sensitive, `case-fold-search' is
4793 expected to be bound to nil when matching against this regexp.")
4795 (defvar-local org-complex-heading-regexp-format nil
4796 "Printf format to make regexp to match an exact headline.
4797 This regexp will match the headline of any node which has the
4798 exact headline text that is put into the format, but may have any
4799 TODO state, priority and tags.")
4801 (defvar-local org-todo-line-tags-regexp nil
4802 "Matches a headline and puts TODO state into group 2 if present.
4803 Also put tags into group 4 if tags are present.")
4805 (defconst org-plain-time-of-day-regexp
4806 (concat
4807 "\\(\\<[012]?[0-9]"
4808 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4809 "\\(--?"
4810 "\\(\\<[012]?[0-9]"
4811 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4812 "\\)?")
4813 "Regular expression to match a plain time or time range.
4814 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4815 groups carry important information:
4816 0 the full match
4817 1 the first time, range or not
4818 8 the second time, if it is a range.")
4820 (defconst org-plain-time-extension-regexp
4821 (concat
4822 "\\(\\<[012]?[0-9]"
4823 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4824 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4825 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4826 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4827 groups carry important information:
4828 0 the full match
4829 7 hours of duration
4830 9 minutes of duration")
4832 (defconst org-stamp-time-of-day-regexp
4833 (concat
4834 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4835 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4836 "\\(--?"
4837 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4838 "Regular expression to match a timestamp time or time range.
4839 After a match, the following groups carry important information:
4840 0 the full match
4841 1 date plus weekday, for back referencing to make sure both times are on the same day
4842 2 the first time, range or not
4843 4 the second time, if it is a range.")
4845 (defconst org-startup-options
4846 '(("fold" org-startup-folded t)
4847 ("overview" org-startup-folded t)
4848 ("nofold" org-startup-folded nil)
4849 ("showall" org-startup-folded nil)
4850 ("showeverything" org-startup-folded showeverything)
4851 ("content" org-startup-folded content)
4852 ("indent" org-startup-indented t)
4853 ("noindent" org-startup-indented nil)
4854 ("hidestars" org-hide-leading-stars t)
4855 ("showstars" org-hide-leading-stars nil)
4856 ("odd" org-odd-levels-only t)
4857 ("oddeven" org-odd-levels-only nil)
4858 ("align" org-startup-align-all-tables t)
4859 ("noalign" org-startup-align-all-tables nil)
4860 ("inlineimages" org-startup-with-inline-images t)
4861 ("noinlineimages" org-startup-with-inline-images nil)
4862 ("latexpreview" org-startup-with-latex-preview t)
4863 ("nolatexpreview" org-startup-with-latex-preview nil)
4864 ("customtime" org-display-custom-times t)
4865 ("logdone" org-log-done time)
4866 ("lognotedone" org-log-done note)
4867 ("nologdone" org-log-done nil)
4868 ("lognoteclock-out" org-log-note-clock-out t)
4869 ("nolognoteclock-out" org-log-note-clock-out nil)
4870 ("logrepeat" org-log-repeat state)
4871 ("lognoterepeat" org-log-repeat note)
4872 ("logdrawer" org-log-into-drawer t)
4873 ("nologdrawer" org-log-into-drawer nil)
4874 ("logstatesreversed" org-log-states-order-reversed t)
4875 ("nologstatesreversed" org-log-states-order-reversed nil)
4876 ("nologrepeat" org-log-repeat nil)
4877 ("logreschedule" org-log-reschedule time)
4878 ("lognotereschedule" org-log-reschedule note)
4879 ("nologreschedule" org-log-reschedule nil)
4880 ("logredeadline" org-log-redeadline time)
4881 ("lognoteredeadline" org-log-redeadline note)
4882 ("nologredeadline" org-log-redeadline nil)
4883 ("logrefile" org-log-refile time)
4884 ("lognoterefile" org-log-refile note)
4885 ("nologrefile" org-log-refile nil)
4886 ("fninline" org-footnote-define-inline t)
4887 ("nofninline" org-footnote-define-inline nil)
4888 ("fnlocal" org-footnote-section nil)
4889 ("fnauto" org-footnote-auto-label t)
4890 ("fnprompt" org-footnote-auto-label nil)
4891 ("fnconfirm" org-footnote-auto-label confirm)
4892 ("fnplain" org-footnote-auto-label plain)
4893 ("fnadjust" org-footnote-auto-adjust t)
4894 ("nofnadjust" org-footnote-auto-adjust nil)
4895 ("constcgs" constants-unit-system cgs)
4896 ("constSI" constants-unit-system SI)
4897 ("noptag" org-tag-persistent-alist nil)
4898 ("hideblocks" org-hide-block-startup t)
4899 ("nohideblocks" org-hide-block-startup nil)
4900 ("beamer" org-startup-with-beamer-mode t)
4901 ("entitiespretty" org-pretty-entities t)
4902 ("entitiesplain" org-pretty-entities nil))
4903 "Variable associated with STARTUP options for org-mode.
4904 Each element is a list of three items: the startup options (as written
4905 in the #+STARTUP line), the corresponding variable, and the value to set
4906 this variable to if the option is found. An optional forth element PUSH
4907 means to push this value onto the list in the variable.")
4909 (defcustom org-group-tags t
4910 "When non-nil (the default), use group tags.
4911 This can be turned on/off through `org-toggle-tags-groups'."
4912 :group 'org-tags
4913 :group 'org-startup
4914 :type 'boolean)
4916 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4918 (defun org-toggle-tags-groups ()
4919 "Toggle support for group tags.
4920 Support for group tags is controlled by the option
4921 `org-group-tags', which is non-nil by default."
4922 (interactive)
4923 (setq org-group-tags (not org-group-tags))
4924 (cond ((and (derived-mode-p 'org-agenda-mode)
4925 org-group-tags)
4926 (org-agenda-redo))
4927 ((derived-mode-p 'org-mode)
4928 (let ((org-inhibit-startup t)) (org-mode))))
4929 (message "Groups tags support has been turned %s"
4930 (if org-group-tags "on" "off")))
4932 (defun org-set-regexps-and-options (&optional tags-only)
4933 "Precompute regular expressions used in the current buffer.
4934 When optional argument TAGS-ONLY is non-nil, only compute tags
4935 related expressions."
4936 (when (derived-mode-p 'org-mode)
4937 (let ((alist (org--setup-collect-keywords
4938 (org-make-options-regexp
4939 (append '("FILETAGS" "TAGS" "SETUPFILE")
4940 (and (not tags-only)
4941 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4942 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4943 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4944 ;; Startup options. Get this early since it does change
4945 ;; behavior for other options (e.g., tags).
4946 (let ((startup (cdr (assq 'startup alist))))
4947 (dolist (option startup)
4948 (let ((entry (assoc-string option org-startup-options t)))
4949 (when entry
4950 (let ((var (nth 1 entry))
4951 (val (nth 2 entry)))
4952 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4953 (unless (listp (symbol-value var))
4954 (set (make-local-variable var) nil))
4955 (add-to-list var val)))))))
4956 (setq-local org-file-tags
4957 (mapcar #'org-add-prop-inherited
4958 (cdr (assq 'filetags alist))))
4959 (setq org-current-tag-alist
4960 (append org-tag-persistent-alist
4961 (let ((tags (cdr (assq 'tags alist))))
4962 (if tags (org-tag-string-to-alist tags)
4963 org-tag-alist))))
4964 (setq org-tag-groups-alist
4965 (org-tag-alist-to-groups org-current-tag-alist))
4966 (unless tags-only
4967 ;; File properties.
4968 (setq-local org-file-properties (cdr (assq 'property alist)))
4969 ;; Archive location.
4970 (let ((archive (cdr (assq 'archive alist))))
4971 (when archive (setq-local org-archive-location archive)))
4972 ;; Category.
4973 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4974 (when cat
4975 (setq-local org-category (intern cat))
4976 (setq-local org-file-properties
4977 (org--update-property-plist
4978 "CATEGORY" cat org-file-properties))))
4979 ;; Columns.
4980 (let ((column (cdr (assq 'columns alist))))
4981 (when column (setq-local org-columns-default-format column)))
4982 ;; Constants.
4983 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4984 ;; Link abbreviations.
4985 (let ((links (cdr (assq 'link alist))))
4986 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4987 ;; Priorities.
4988 (let ((priorities (cdr (assq 'priorities alist))))
4989 (when priorities
4990 (setq-local org-highest-priority (nth 0 priorities))
4991 (setq-local org-lowest-priority (nth 1 priorities))
4992 (setq-local org-default-priority (nth 2 priorities))))
4993 ;; Scripts.
4994 (let ((scripts (assq 'scripts alist)))
4995 (when scripts
4996 (setq-local org-use-sub-superscripts (cdr scripts))))
4997 ;; TODO keywords.
4998 (setq-local org-todo-kwd-alist nil)
4999 (setq-local org-todo-key-alist nil)
5000 (setq-local org-todo-key-trigger nil)
5001 (setq-local org-todo-keywords-1 nil)
5002 (setq-local org-done-keywords nil)
5003 (setq-local org-todo-heads nil)
5004 (setq-local org-todo-sets nil)
5005 (setq-local org-todo-log-states nil)
5006 (let ((todo-sequences
5007 (or (nreverse (cdr (assq 'todo alist)))
5008 (let ((d (default-value 'org-todo-keywords)))
5009 (if (not (stringp (car d))) d
5010 ;; XXX: Backward compatibility code.
5011 (list (cons org-todo-interpretation d)))))))
5012 (dolist (sequence todo-sequences)
5013 (let* ((sequence (or (run-hook-with-args-until-success
5014 'org-todo-setup-filter-hook sequence)
5015 sequence))
5016 (sequence-type (car sequence))
5017 (keywords (cdr sequence))
5018 (sep (member "|" keywords))
5019 names alist)
5020 (dolist (k (remove "|" keywords))
5021 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5023 (error "Invalid TODO keyword %s" k))
5024 (let ((name (match-string 1 k))
5025 (key (match-string 2 k))
5026 (log (org-extract-log-state-settings k)))
5027 (push name names)
5028 (push (cons name (and key (string-to-char key))) alist)
5029 (when log (push log org-todo-log-states))))
5030 (let* ((names (nreverse names))
5031 (done (if sep (org-remove-keyword-keys (cdr sep))
5032 (last names)))
5033 (head (car names))
5034 (tail (list sequence-type head (car done) (org-last done))))
5035 (add-to-list 'org-todo-heads head 'append)
5036 (push names org-todo-sets)
5037 (setq org-done-keywords (append org-done-keywords done nil))
5038 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5039 (setq org-todo-key-alist
5040 (append org-todo-key-alist
5041 (and alist
5042 (append '((:startgroup))
5043 (nreverse alist)
5044 '((:endgroup))))))
5045 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5046 (setq org-todo-sets (nreverse org-todo-sets)
5047 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5048 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5049 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5050 ;; Compute the regular expressions and other local variables.
5051 ;; Using `org-outline-regexp-bol' would complicate them much,
5052 ;; because of the fixed white space at the end of that string.
5053 (unless org-done-keywords
5054 (setq org-done-keywords
5055 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5056 (setq org-not-done-keywords
5057 (org-delete-all org-done-keywords
5058 (copy-sequence org-todo-keywords-1))
5059 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5060 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5061 org-not-done-heading-regexp
5062 (format org-heading-keyword-regexp-format org-not-done-regexp)
5063 org-todo-line-regexp
5064 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5065 org-complex-heading-regexp
5066 (concat "^\\(\\*+\\)"
5067 "\\(?: +" org-todo-regexp "\\)?"
5068 "\\(?: +\\(\\[#.\\]\\)\\)?"
5069 "\\(?: +\\(.*?\\)\\)??"
5070 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5071 "[ \t]*$")
5072 org-complex-heading-regexp-format
5073 (concat "^\\(\\*+\\)"
5074 "\\(?: +" org-todo-regexp "\\)?"
5075 "\\(?: +\\(\\[#.\\]\\)\\)?"
5076 "\\(?: +"
5077 ;; Stats cookies can be stuck to body.
5078 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5079 "\\(%s\\)"
5080 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5081 "\\)"
5082 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5083 "[ \t]*$")
5084 org-todo-line-tags-regexp
5085 (concat "^\\(\\*+\\)"
5086 "\\(?: +" org-todo-regexp "\\)?"
5087 "\\(?: +\\(.*?\\)\\)??"
5088 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5089 "[ \t]*$"))
5090 (org-compute-latex-and-related-regexp)))))
5092 (defun org--setup-collect-keywords (regexp &optional files alist)
5093 "Return setup keywords values as an alist.
5095 REGEXP matches a subset of setup keywords. FILES is a list of
5096 file names already visited. It is used to avoid circular setup
5097 files. ALIST, when non-nil, is the alist computed so far.
5099 Return value contains the following keys: `archive', `category',
5100 `columns', `constants', `filetags', `link', `priorities',
5101 `property', `scripts', `startup', `tags' and `todo'."
5102 (org-with-wide-buffer
5103 (goto-char (point-min))
5104 (let ((case-fold-search t))
5105 (while (re-search-forward regexp nil t)
5106 (let ((element (org-element-at-point)))
5107 (when (eq (org-element-type element) 'keyword)
5108 (let ((key (org-element-property :key element))
5109 (value (org-element-property :value element)))
5110 (cond
5111 ((equal key "ARCHIVE")
5112 (when (org-string-nw-p value)
5113 (push (cons 'archive value) alist)))
5114 ((equal key "CATEGORY") (push (cons 'category value) alist))
5115 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5116 ((equal key "CONSTANTS")
5117 (let* ((constants (assq 'constants alist))
5118 (store (cdr constants)))
5119 (dolist (pair (org-split-string value))
5120 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5121 pair)
5122 (let* ((name (match-string 1 pair))
5123 (value (match-string 2 pair))
5124 (old (assoc name store)))
5125 (if old (setcdr old value)
5126 (push (cons name value) store)))))
5127 (if constants (setcdr constants store)
5128 (push (cons 'constants store) alist))))
5129 ((equal key "FILETAGS")
5130 (when (org-string-nw-p value)
5131 (let ((old (assq 'filetags alist))
5132 (new (apply #'nconc
5133 (mapcar (lambda (x) (org-split-string x ":"))
5134 (org-split-string value)))))
5135 (if old (setcdr old (append new (cdr old)))
5136 (push (cons 'filetags new) alist)))))
5137 ((equal key "LINK")
5138 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5139 (let ((links (assq 'link alist))
5140 (pair (cons (match-string-no-properties 1 value)
5141 (match-string-no-properties 2 value))))
5142 (if links (push pair (cdr links))
5143 (push (list 'link pair) alist)))))
5144 ((equal key "OPTIONS")
5145 (when (and (org-string-nw-p value)
5146 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5147 (push (cons 'scripts (read (match-string 1 value))) alist)))
5148 ((equal key "PRIORITIES")
5149 (push (cons 'priorities
5150 (let ((prio (org-split-string value)))
5151 (if (< (length prio) 3) '(?A ?C ?B)
5152 (mapcar #'string-to-char prio))))
5153 alist))
5154 ((equal key "PROPERTY")
5155 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5156 (let* ((property (assq 'property alist))
5157 (value (org--update-property-plist
5158 (match-string-no-properties 1 value)
5159 (match-string-no-properties 2 value)
5160 (cdr property))))
5161 (if property (setcdr property value)
5162 (push (cons 'property value) alist)))))
5163 ((equal key "STARTUP")
5164 (let ((startup (assq 'startup alist)))
5165 (if startup
5166 (setcdr startup
5167 (append (cdr startup) (org-split-string value)))
5168 (push (cons 'startup (org-split-string value)) alist))))
5169 ((equal key "TAGS")
5170 (let ((tag-cell (assq 'tags alist)))
5171 (if tag-cell
5172 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5173 (push (cons 'tags value) alist))))
5174 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5175 (let ((todo (assq 'todo alist))
5176 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5177 (org-split-string value))))
5178 (if todo (push value (cdr todo))
5179 (push (list 'todo value) alist))))
5180 ((equal key "SETUPFILE")
5181 (unless buffer-read-only ; Do not check in Gnus messages.
5182 (let ((f (and (org-string-nw-p value)
5183 (expand-file-name
5184 (org-unbracket-string "\"" "\"" value)))))
5185 (when (and f (file-readable-p f) (not (member f files)))
5186 (with-temp-buffer
5187 (setq default-directory (file-name-directory f))
5188 (insert-file-contents f)
5189 (setq alist
5190 ;; Fake Org mode to benefit from cache
5191 ;; without recurring needlessly.
5192 (let ((major-mode 'org-mode))
5193 (org--setup-collect-keywords
5194 regexp (cons f files) alist)))))))))))))))
5195 alist)
5197 (defun org-tag-string-to-alist (s)
5198 "Return tag alist associated to string S.
5199 S is a value for TAGS keyword or produced with
5200 `org-tag-alist-to-string'. Return value is an alist suitable for
5201 `org-tag-alist' or `org-tag-persistent-alist'."
5202 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5203 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5204 "\\|{.+?}\\)" ; regular expression
5205 "\\(?:(\\(.\\))\\)?\\'"))
5206 alist group-flag)
5207 (dolist (tokens lines (cdr (nreverse alist)))
5208 (push '(:newline) alist)
5209 (while tokens
5210 (let ((token (pop tokens)))
5211 (pcase token
5212 ("{"
5213 (push '(:startgroup) alist)
5214 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5215 ("}"
5216 (push '(:endgroup) alist)
5217 (setq group-flag nil))
5218 ("["
5219 (push '(:startgrouptag) alist)
5220 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5221 ("]"
5222 (push '(:endgrouptag) alist)
5223 (setq group-flag nil))
5224 (":"
5225 (push '(:grouptags) alist))
5226 ((guard (string-match tag-re token))
5227 (let ((tag (match-string 1 token))
5228 (key (and (match-beginning 2)
5229 (string-to-char (match-string 2 token)))))
5230 ;; Push all tags in groups, no matter if they already
5231 ;; appear somewhere else in the list.
5232 (when (or group-flag (not (assoc tag alist)))
5233 (push (cons tag key) alist))))))))))
5235 (defun org-tag-alist-to-string (alist &optional skip-key)
5236 "Return tag string associated to ALIST.
5238 ALIST is an alist, as defined in `org-tag-alist' or
5239 `org-tag-persistent-alist', or produced with
5240 `org-tag-string-to-alist'.
5242 Return value is a string suitable as a value for \"TAGS\"
5243 keyword.
5245 When optional argument SKIP-KEY is non-nil, skip selection keys
5246 next to tags."
5247 (mapconcat (lambda (token)
5248 (pcase token
5249 (`(:startgroup) "{")
5250 (`(:endgroup) "}")
5251 (`(:startgrouptag) "[")
5252 (`(:endgrouptag) "]")
5253 (`(:grouptags) ":")
5254 (`(:newline) "\\n")
5255 ((and
5256 (guard (not skip-key))
5257 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5258 (format "%s(%c)" tag key))
5259 (`(,(and tag (pred stringp)) . ,_) tag)
5260 (_ (user-error "Invalid tag token: %S" token))))
5261 alist
5262 " "))
5264 (defun org-tag-alist-to-groups (alist)
5265 "Return group alist from tag ALIST.
5266 ALIST is an alist, as defined in `org-tag-alist' or
5267 `org-tag-persistent-alist', or produced with
5268 `org-tag-string-to-alist'. Return value is an alist following
5269 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5270 a string, summarizing TAGS, as a list of strings."
5271 (let (groups group-status current-group)
5272 (dolist (token alist (nreverse groups))
5273 (pcase token
5274 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5275 (`(,(or :endgroup :endgrouptag))
5276 (when (eq group-status 'append)
5277 (push (nreverse current-group) groups))
5278 (setq group-status nil))
5279 (`(:grouptags) (setq group-status 'append))
5280 ((and `(,tag . ,_) (guard group-status))
5281 (if (eq group-status 'append) (push tag current-group)
5282 (setq current-group (list tag))))
5283 (_ nil)))))
5285 (defvar org--file-cache (make-hash-table :test #'equal)
5286 "Hash table to store contents of files referenced via a URL.
5287 This is the cache of file URLs read using `org-file-contents'.")
5289 (defun org-reset-file-cache ()
5290 "Reset the cache of files downloaded by `org-file-contents'."
5291 (clrhash org--file-cache))
5293 (defun org-file-url-p (file)
5294 "Non-nil if FILE is a URL."
5295 (require 'ffap)
5296 (string-match-p ffap-url-regexp file))
5298 (defun org-file-contents (file &optional noerror nocache)
5299 "Return the contents of FILE, as a string.
5301 FILE can be a file name or URL.
5303 If FILE is a URL, download the contents. If the URL contents are
5304 already cached in the `org--file-cache' hash table, the download step
5305 is skipped.
5307 If NOERROR is non-nil, ignore the error when unable to read the FILE
5308 from file or URL.
5310 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5311 is available. This option applies only if FILE is a URL."
5312 (let* ((is-url (org-file-url-p file))
5313 (cache (and is-url
5314 (not nocache)
5315 (gethash file org--file-cache))))
5316 (cond
5317 (cache)
5318 (is-url
5319 (with-current-buffer (url-retrieve-synchronously file)
5320 (goto-char (point-min))
5321 ;; Move point to after the url-retrieve header.
5322 (search-forward "\n\n" nil :move)
5323 ;; Search for the success code only in the url-retrieve header.
5324 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5325 ;; Update the cache `org--file-cache' and return contents.
5326 (puthash file
5327 (buffer-substring-no-properties (point) (point-max))
5328 org--file-cache)
5329 (funcall (if noerror #'message #'user-error)
5330 "Unable to fetch file from %S"
5331 file))))
5333 (with-temp-buffer
5334 (condition-case err
5335 (progn
5336 (insert-file-contents file)
5337 (buffer-string))
5338 (file-error
5339 (funcall (if noerror #'message #'user-error)
5340 (error-message-string err)))))))))
5342 (defun org-extract-log-state-settings (x)
5343 "Extract the log state setting from a TODO keyword string.
5344 This will extract info from a string like \"WAIT(w@/!)\"."
5345 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5346 (let ((kw (match-string 1 x))
5347 (log1 (and (match-end 3) (match-string 3 x)))
5348 (log2 (and (match-end 4) (match-string 4 x))))
5349 (and (or log1 log2)
5350 (list kw
5351 (and log1 (if (equal log1 "!") 'time 'note))
5352 (and log2 (if (equal log2 "!") 'time 'note)))))))
5354 (defun org-remove-keyword-keys (list)
5355 "Remove a pair of parenthesis at the end of each string in LIST."
5356 (mapcar (lambda (x)
5357 (if (string-match "(.*)$" x)
5358 (substring x 0 (match-beginning 0))
5360 list))
5362 (defun org-assign-fast-keys (alist)
5363 "Assign fast keys to a keyword-key alist.
5364 Respect keys that are already there."
5365 (let (new e (alt ?0))
5366 (while (setq e (pop alist))
5367 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5368 (cdr e)) ;; Key already assigned.
5369 (push e new)
5370 (let ((clist (string-to-list (downcase (car e))))
5371 (used (append new alist)))
5372 (when (= (car clist) ?@)
5373 (pop clist))
5374 (while (and clist (rassoc (car clist) used))
5375 (pop clist))
5376 (unless clist
5377 (while (rassoc alt used)
5378 (cl-incf alt)))
5379 (push (cons (car e) (or (car clist) alt)) new))))
5380 (nreverse new)))
5382 ;;; Some variables used in various places
5384 (defvar org-window-configuration nil
5385 "Used in various places to store a window configuration.")
5386 (defvar org-selected-window nil
5387 "Used in various places to store a window configuration.")
5388 (defvar org-finish-function nil
5389 "Function to be called when `C-c C-c' is used.
5390 This is for getting out of special buffers like capture.")
5391 (defvar org-last-state)
5393 ;; Defined somewhere in this file, but used before definition.
5394 (defvar org-entities) ;; defined in org-entities.el
5395 (defvar org-struct-menu)
5396 (defvar org-org-menu)
5397 (defvar org-tbl-menu)
5399 ;;;; Define the Org mode
5401 ;; We use a before-change function to check if a table might need
5402 ;; an update.
5403 (defvar org-table-may-need-update t
5404 "Indicates that a table might need an update.
5405 This variable is set by `org-before-change-function'.
5406 `org-table-align' sets it back to nil.")
5407 (defun org-before-change-function (_beg _end)
5408 "Every change indicates that a table might need an update."
5409 (setq org-table-may-need-update t))
5410 (defvar org-mode-map)
5411 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5412 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5413 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5414 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5415 (defvar org-table-buffer-is-an nil)
5417 (defvar bidi-paragraph-direction)
5418 (defvar buffer-face-mode-face)
5420 (require 'outline)
5422 ;; Other stuff we need.
5423 (require 'time-date)
5424 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5425 (require 'easymenu)
5426 (autoload 'easy-menu-add "easymenu")
5427 (require 'overlay)
5429 ;; (require 'org-macs) moved higher up in the file before it is first used
5430 (require 'org-entities)
5431 ;; (require 'org-compat) moved higher up in the file before it is first used
5432 (require 'org-faces)
5433 (require 'org-list)
5434 (require 'org-pcomplete)
5435 (require 'org-src)
5436 (require 'org-footnote)
5437 (require 'org-macro)
5439 ;; babel
5440 (require 'ob)
5442 ;;;###autoload
5443 (define-derived-mode org-mode outline-mode "Org"
5444 "Outline-based notes management and organizer, alias
5445 \"Carsten's outline-mode for keeping track of everything.\"
5447 Org mode develops organizational tasks around a NOTES file which
5448 contains information about projects as plain text. Org mode is
5449 implemented on top of Outline mode, which is ideal to keep the content
5450 of large files well structured. It supports ToDo items, deadlines and
5451 time stamps, which magically appear in the diary listing of the Emacs
5452 calendar. Tables are easily created with a built-in table editor.
5453 Plain text URL-like links connect to websites, emails (VM), Usenet
5454 messages (Gnus), BBDB entries, and any files related to the project.
5455 For printing and sharing of notes, an Org file (or a part of it)
5456 can be exported as a structured ASCII or HTML file.
5458 The following commands are available:
5460 \\{org-mode-map}"
5462 ;; Get rid of Outline menus, they are not needed
5463 ;; Need to do this here because define-derived-mode sets up
5464 ;; the keymap so late. Still, it is a waste to call this each time
5465 ;; we switch another buffer into Org mode.
5466 (define-key org-mode-map [menu-bar headings] 'undefined)
5467 (define-key org-mode-map [menu-bar hide] 'undefined)
5468 (define-key org-mode-map [menu-bar show] 'undefined)
5470 (org-load-modules-maybe)
5471 (org-install-agenda-files-menu)
5472 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5473 (add-to-invisibility-spec '(org-cwidth))
5474 (add-to-invisibility-spec '(org-hide-block . t))
5475 (setq-local outline-regexp org-outline-regexp)
5476 (setq-local outline-level 'org-outline-level)
5477 (setq bidi-paragraph-direction 'left-to-right)
5478 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5479 (unless org-display-table
5480 (setq org-display-table (make-display-table)))
5481 (set-display-table-slot
5482 org-display-table 4
5483 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5484 org-ellipsis)))
5485 (setq buffer-display-table org-display-table))
5486 (org-set-regexps-and-options)
5487 (org-set-font-lock-defaults)
5488 (when (and org-tag-faces (not org-tags-special-faces-re))
5489 ;; tag faces set outside customize.... force initialization.
5490 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5491 ;; Calc embedded
5492 (setq-local calc-embedded-open-mode "# ")
5493 ;; Modify a few syntax entries
5494 (modify-syntax-entry ?@ "w")
5495 (modify-syntax-entry ?\" "\"")
5496 (modify-syntax-entry ?\\ "_")
5497 (modify-syntax-entry ?~ "_")
5498 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5499 ;; Activate before-change-function
5500 (setq-local org-table-may-need-update t)
5501 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5502 ;; Check for running clock before killing a buffer
5503 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5504 ;; Initialize macros templates.
5505 (org-macro-initialize-templates)
5506 ;; Initialize radio targets.
5507 (org-update-radio-target-regexp)
5508 ;; Indentation.
5509 (setq-local indent-line-function 'org-indent-line)
5510 (setq-local indent-region-function 'org-indent-region)
5511 ;; Filling and auto-filling.
5512 (org-setup-filling)
5513 ;; Comments.
5514 (org-setup-comments-handling)
5515 ;; Initialize cache.
5516 (org-element-cache-reset)
5517 ;; Beginning/end of defun
5518 (setq-local beginning-of-defun-function 'org-backward-element)
5519 (setq-local end-of-defun-function
5520 (lambda ()
5521 (if (not (org-at-heading-p))
5522 (org-forward-element)
5523 (org-forward-element)
5524 (forward-char -1))))
5525 ;; Next error for sparse trees
5526 (setq-local next-error-function 'org-occur-next-match)
5527 ;; Make sure dependence stuff works reliably, even for users who set it
5528 ;; too late :-(
5529 (if org-enforce-todo-dependencies
5530 (add-hook 'org-blocker-hook
5531 'org-block-todo-from-children-or-siblings-or-parent)
5532 (remove-hook 'org-blocker-hook
5533 'org-block-todo-from-children-or-siblings-or-parent))
5534 (if org-enforce-todo-checkbox-dependencies
5535 (add-hook 'org-blocker-hook
5536 'org-block-todo-from-checkboxes)
5537 (remove-hook 'org-blocker-hook
5538 'org-block-todo-from-checkboxes))
5540 ;; Align options lines
5541 (setq-local
5542 align-mode-rules-list
5543 '((org-in-buffer-settings
5544 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5545 (modes . '(org-mode)))))
5547 ;; Imenu
5548 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5550 ;; Make isearch reveal context
5551 (setq-local outline-isearch-open-invisible-function
5552 (lambda (&rest _) (org-show-context 'isearch)))
5554 ;; Setup the pcomplete hooks
5555 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5556 (setq-local pcomplete-command-name-function 'org-command-at-point)
5557 (setq-local pcomplete-default-completion-function 'ignore)
5558 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5559 (setq-local pcomplete-termination-string "")
5560 (setq-local buffer-face-mode-face 'org-default)
5562 ;; If empty file that did not turn on Org mode automatically, make
5563 ;; it to.
5564 (when (and org-insert-mode-line-in-empty-file
5565 (called-interactively-p 'any)
5566 (= (point-min) (point-max)))
5567 (insert "# -*- mode: org -*-\n\n"))
5568 (unless org-inhibit-startup
5569 (org-unmodified
5570 (when org-startup-with-beamer-mode (org-beamer-mode))
5571 (when org-startup-align-all-tables
5572 (org-table-map-tables #'org-table-align t))
5573 (when org-startup-with-inline-images (org-display-inline-images))
5574 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5575 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5576 (when org-startup-truncated (setq truncate-lines t))
5577 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5578 (org-refresh-effort-properties)))
5579 ;; Try to set `org-hide' face correctly.
5580 (let ((foreground (org-find-invisible-foreground)))
5581 (when foreground
5582 (set-face-foreground 'org-hide foreground))))
5584 ;; Update `customize-package-emacs-version-alist'
5585 (add-to-list 'customize-package-emacs-version-alist
5586 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5587 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5588 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5589 ("9.0" . "26.1")))
5591 (defvar org-mode-transpose-word-syntax-table
5592 (let ((st (make-syntax-table text-mode-syntax-table)))
5593 (dolist (c org-emphasis-alist st)
5594 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5596 (when (fboundp 'abbrev-table-put)
5597 (abbrev-table-put org-mode-abbrev-table
5598 :parents (list text-mode-abbrev-table)))
5600 (defun org-find-invisible-foreground ()
5601 (let ((candidates (remove
5602 "unspecified-bg"
5603 (nconc
5604 (list (face-background 'default)
5605 (face-background 'org-default))
5606 (mapcar
5607 (lambda (alist)
5608 (when (boundp alist)
5609 (cdr (assq 'background-color (symbol-value alist)))))
5610 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5611 (list (face-foreground 'org-hide))))))
5612 (car (remove nil candidates))))
5614 (defun org-current-time (&optional rounding-minutes past)
5615 "Current time, possibly rounded to ROUNDING-MINUTES.
5616 When ROUNDING-MINUTES is not an integer, fall back on the car of
5617 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5618 the rounding returns a past time."
5619 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5620 (car org-time-stamp-rounding-minutes)))
5621 (time (decode-time)) res)
5622 (if (< r 1)
5623 (current-time)
5624 (setq res
5625 (apply 'encode-time
5626 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5627 (nthcdr 2 time))))
5628 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5629 (seconds-to-time (- (float-time res) (* r 60)))
5630 res))))
5632 (defun org-today ()
5633 "Return today date, considering `org-extend-today-until'."
5634 (time-to-days
5635 (time-subtract (current-time)
5636 (list 0 (* 3600 org-extend-today-until) 0))))
5638 ;;;; Font-Lock stuff, including the activators
5640 (defvar org-mouse-map (make-sparse-keymap))
5641 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5642 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5643 (when org-mouse-1-follows-link
5644 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5645 (when org-tab-follows-link
5646 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5647 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5649 (require 'font-lock)
5651 (defconst org-non-link-chars "]\t\n\r<>")
5652 (defvar org-link-types-re nil
5653 "Matches a link that has a url-like prefix like \"http:\"")
5654 (defvar org-link-re-with-space nil
5655 "Matches a link with spaces, optional angular brackets around it.")
5656 (defvar org-link-re-with-space2 nil
5657 "Matches a link with spaces, optional angular brackets around it.")
5658 (defvar org-link-re-with-space3 nil
5659 "Matches a link with spaces, only for internal part in bracket links.")
5660 (defvar org-angle-link-re nil
5661 "Matches link with angular brackets, spaces are allowed.")
5662 (defvar org-plain-link-re nil
5663 "Matches plain link, without spaces.")
5664 (defvar org-bracket-link-regexp nil
5665 "Matches a link in double brackets.")
5666 (defvar org-bracket-link-analytic-regexp nil
5667 "Regular expression used to analyze links.
5668 Here is what the match groups contain after a match:
5669 1: http:
5670 2: http
5671 3: path
5672 4: [desc]
5673 5: desc")
5674 (defvar org-bracket-link-analytic-regexp++ nil
5675 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5676 (defvar org-any-link-re nil
5677 "Regular expression matching any link.")
5679 (defconst org-match-sexp-depth 3
5680 "Number of stacked braces for sub/superscript matching.")
5682 (defun org-create-multibrace-regexp (left right n)
5683 "Create a regular expression which will match a balanced sexp.
5684 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5685 as single character strings.
5686 The regexp returned will match the entire expression including the
5687 delimiters. It will also define a single group which contains the
5688 match except for the outermost delimiters. The maximum depth of
5689 stacked delimiters is N. Escaping delimiters is not possible."
5690 (let* ((nothing (concat "[^" left right "]*?"))
5691 (or "\\|")
5692 (re nothing)
5693 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5694 (while (> n 1)
5695 (setq n (1- n)
5696 re (concat re or next)
5697 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5698 (concat left "\\(" re "\\)" right)))
5700 (defconst org-match-substring-regexp
5701 (concat
5702 "\\(\\S-\\)\\([_^]\\)\\("
5703 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5704 "\\|"
5705 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5706 "\\|"
5707 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5708 "The regular expression matching a sub- or superscript.")
5710 (defconst org-match-substring-with-braces-regexp
5711 (concat
5712 "\\(\\S-\\)\\([_^]\\)"
5713 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5714 "The regular expression matching a sub- or superscript, forcing braces.")
5716 (defun org-make-link-regexps ()
5717 "Update the link regular expressions.
5718 This should be called after the variable `org-link-parameters' has changed."
5719 (let ((types-re (regexp-opt (org-link-types) t)))
5720 (setq org-link-types-re
5721 (concat "\\`" types-re ":")
5722 org-link-re-with-space
5723 (concat "<?" types-re ":"
5724 "\\([^" org-non-link-chars " ]"
5725 "[^" org-non-link-chars "]*"
5726 "[^" org-non-link-chars " ]\\)>?")
5727 org-link-re-with-space2
5728 (concat "<?" types-re ":"
5729 "\\([^" org-non-link-chars " ]"
5730 "[^\t\n\r]*"
5731 "[^" org-non-link-chars " ]\\)>?")
5732 org-link-re-with-space3
5733 (concat "<?" types-re ":"
5734 "\\([^" org-non-link-chars " ]"
5735 "[^\t\n\r]*\\)")
5736 org-angle-link-re
5737 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5738 types-re)
5739 org-plain-link-re
5740 (concat
5741 "\\<" types-re ":"
5742 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5743 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5744 org-bracket-link-regexp
5745 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5746 org-bracket-link-analytic-regexp
5747 (concat
5748 "\\[\\["
5749 "\\(" types-re ":\\)?"
5750 "\\([^]]+\\)"
5751 "\\]"
5752 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5753 "\\]")
5754 org-bracket-link-analytic-regexp++
5755 (concat
5756 "\\[\\["
5757 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5758 "\\([^]]+\\)"
5759 "\\]"
5760 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5761 "\\]")
5762 org-any-link-re
5763 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5764 org-angle-link-re "\\)\\|\\("
5765 org-plain-link-re "\\)"))))
5767 (org-make-link-regexps)
5769 (defvar org-emph-face nil)
5771 (defun org-do-emphasis-faces (limit)
5772 "Run through the buffer and emphasize strings."
5773 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5774 (car org-emphasis-regexp-components))))
5775 (catch :exit
5776 (while (re-search-forward quick-re limit t)
5777 (let* ((marker (match-string 2))
5778 (verbatim? (member marker '("~" "="))))
5779 (when (save-excursion
5780 (goto-char (match-beginning 0))
5781 ;; Do not match headline stars. Do not consider
5782 ;; stars of a headline as closing marker for bold
5783 ;; markup either.
5784 (and (not (looking-at-p org-outline-regexp-bol))
5785 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5786 (not (string-match-p
5787 (concat org-outline-regexp-bol "\\'")
5788 (match-string 0)))))
5789 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5790 (font-lock-prepend-text-property
5791 (match-beginning 2) (match-end 2) 'face face)
5792 (when verbatim?
5793 (org-remove-flyspell-overlays-in
5794 (match-beginning 0) (match-end 0)))
5795 (add-text-properties (match-beginning 2) (match-end 2)
5796 '(font-lock-multiline t org-emphasis t))
5797 (when org-hide-emphasis-markers
5798 (add-text-properties (match-end 4) (match-beginning 5)
5799 '(invisible org-link))
5800 (add-text-properties (match-beginning 3) (match-end 3)
5801 '(invisible org-link)))
5802 (throw :exit t))))))))
5804 (defun org-emphasize (&optional char)
5805 "Insert or change an emphasis, i.e. a font like bold or italic.
5806 If there is an active region, change that region to a new emphasis.
5807 If there is no region, just insert the marker characters and position
5808 the cursor between them.
5809 CHAR should be the marker character. If it is a space, it means to
5810 remove the emphasis of the selected region.
5811 If CHAR is not given (for example in an interactive call) it will be
5812 prompted for."
5813 (interactive)
5814 (let ((erc org-emphasis-regexp-components)
5815 (string "") beg end move s)
5816 (if (org-region-active-p)
5817 (setq beg (region-beginning)
5818 end (region-end)
5819 string (buffer-substring beg end))
5820 (setq move t))
5822 (unless char
5823 (message "Emphasis marker or tag: [%s]"
5824 (mapconcat #'car org-emphasis-alist ""))
5825 (setq char (read-char-exclusive)))
5826 (if (equal char ?\s)
5827 (setq s ""
5828 move nil)
5829 (unless (assoc (char-to-string char) org-emphasis-alist)
5830 (user-error "No such emphasis marker: \"%c\"" char))
5831 (setq s (char-to-string char)))
5832 (while (and (> (length string) 1)
5833 (equal (substring string 0 1) (substring string -1))
5834 (assoc (substring string 0 1) org-emphasis-alist))
5835 (setq string (substring string 1 -1)))
5836 (setq string (concat s string s))
5837 (when beg (delete-region beg end))
5838 (unless (or (bolp)
5839 (string-match (concat "[" (nth 0 erc) "\n]")
5840 (char-to-string (char-before (point)))))
5841 (insert " "))
5842 (unless (or (eobp)
5843 (string-match (concat "[" (nth 1 erc) "\n]")
5844 (char-to-string (char-after (point)))))
5845 (insert " ") (backward-char 1))
5846 (insert string)
5847 (and move (backward-char 1))))
5849 (defconst org-nonsticky-props
5850 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5852 (defsubst org-rear-nonsticky-at (pos)
5853 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5855 (defun org-activate-links (limit)
5856 "Add link properties to links.
5857 This includes angle, plain, and bracket links."
5858 (catch :exit
5859 (while (re-search-forward org-any-link-re limit t)
5860 (let* ((start (match-beginning 0))
5861 (end (match-end 0))
5862 (style (cond ((eq ?< (char-after start)) 'angle)
5863 ((eq ?\[ (char-after (1+ start))) 'bracket)
5864 (t 'plain))))
5865 (when (and (memq style org-highlight-links)
5866 ;; Do not confuse plain links with tags.
5867 (not (and (eq style 'plain)
5868 (let ((face (get-text-property
5869 (max (1- start) (point-min)) 'face)))
5870 (if (consp face) (memq 'org-tag face)
5871 (eq 'org-tag face))))))
5872 (let* ((link-object (save-excursion
5873 (goto-char start)
5874 (save-match-data (org-element-link-parser))))
5875 (link (org-element-property :raw-link link-object))
5876 (type (org-element-property :type link-object))
5877 (path (org-element-property :path link-object))
5878 (properties ;for link's visible part
5879 (list
5880 'face (pcase (org-link-get-parameter type :face)
5881 ((and (pred functionp) face) (funcall face path))
5882 ((and (pred facep) face) face)
5883 ((and (pred consp) face) face) ;anonymous
5884 (_ 'org-link))
5885 'mouse-face (or (org-link-get-parameter type :mouse-face)
5886 'highlight)
5887 'keymap (or (org-link-get-parameter type :keymap)
5888 org-mouse-map)
5889 'help-echo (pcase (org-link-get-parameter type :help-echo)
5890 ((and (pred stringp) echo) echo)
5891 ((and (pred functionp) echo) echo)
5892 (_ (concat "LINK: " link)))
5893 'htmlize-link (pcase (org-link-get-parameter type
5894 :htmlize-link)
5895 ((and (pred functionp) f) (funcall f))
5896 (_ `(:uri ,link)))
5897 'font-lock-multiline t)))
5898 (org-remove-flyspell-overlays-in start end)
5899 (org-rear-nonsticky-at end)
5900 (if (not (eq 'bracket style))
5901 (add-text-properties start end properties)
5902 ;; Handle invisible parts in bracket links.
5903 (remove-text-properties start end '(invisible nil))
5904 (let ((hidden
5905 (append `(invisible
5906 ,(or (org-link-get-parameter type :display)
5907 'org-link))
5908 properties))
5909 (visible-start (or (match-beginning 4) (match-beginning 2)))
5910 (visible-end (or (match-end 4) (match-end 2))))
5911 (add-text-properties start visible-start hidden)
5912 (add-text-properties visible-start visible-end properties)
5913 (add-text-properties visible-end end hidden)
5914 (org-rear-nonsticky-at visible-start)
5915 (org-rear-nonsticky-at visible-end)))
5916 (let ((f (org-link-get-parameter type :activate-func)))
5917 (when (functionp f)
5918 (funcall f start end path (eq style 'bracket))))
5919 (throw :exit t))))) ;signal success
5920 nil))
5922 (defun org-activate-code (limit)
5923 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5924 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5925 (remove-text-properties (match-beginning 0) (match-end 0)
5926 '(display t invisible t intangible t))
5929 (defcustom org-src-fontify-natively t
5930 "When non-nil, fontify code in code blocks.
5931 See also the `org-block' face."
5932 :type 'boolean
5933 :version "24.4"
5934 :package-version '(Org . "8.3")
5935 :group 'org-appearance
5936 :group 'org-babel)
5938 (defcustom org-allow-promoting-top-level-subtree nil
5939 "When non-nil, allow promoting a top level subtree.
5940 The leading star of the top level headline will be replaced
5941 by a #."
5942 :type 'boolean
5943 :version "24.1"
5944 :group 'org-appearance)
5946 (defun org-fontify-meta-lines-and-blocks (limit)
5947 (condition-case nil
5948 (org-fontify-meta-lines-and-blocks-1 limit)
5949 (error (message "org-mode fontification error in %S at %d"
5950 (current-buffer)
5951 (line-number-at-pos)))))
5953 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5954 "Fontify #+ lines and blocks."
5955 (let ((case-fold-search t))
5956 (when (re-search-forward
5957 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5958 limit t)
5959 (let ((beg (match-beginning 0))
5960 (block-start (match-end 0))
5961 (block-end nil)
5962 (lang (match-string 7))
5963 (beg1 (line-beginning-position 2))
5964 (dc1 (downcase (match-string 2)))
5965 (dc3 (downcase (match-string 3)))
5966 end end1 quoting block-type)
5967 (cond
5968 ((and (match-end 4) (equal dc3 "+begin"))
5969 ;; Truly a block
5970 (setq block-type (downcase (match-string 5))
5971 quoting (member block-type org-protecting-blocks))
5972 (when (re-search-forward
5973 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5974 nil t) ;; on purpose, we look further than LIMIT
5975 (setq end (min (point-max) (match-end 0))
5976 end1 (min (point-max) (1- (match-beginning 0))))
5977 (setq block-end (match-beginning 0))
5978 (when quoting
5979 (org-remove-flyspell-overlays-in beg1 end1)
5980 (remove-text-properties beg end
5981 '(display t invisible t intangible t)))
5982 (add-text-properties
5983 beg end '(font-lock-fontified t font-lock-multiline t))
5984 (add-text-properties beg beg1 '(face org-meta-line))
5985 (org-remove-flyspell-overlays-in beg beg1)
5986 (add-text-properties ; For end_src
5987 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5988 (org-remove-flyspell-overlays-in end1 end)
5989 (cond
5990 ((and lang (not (string= lang "")) org-src-fontify-natively)
5991 (org-src-font-lock-fontify-block lang block-start block-end)
5992 (add-text-properties beg1 block-end '(src-block t)))
5993 (quoting
5994 (add-text-properties beg1 (min (point-max) (1+ end1))
5995 (list 'face
5996 (list :inherit
5997 (let ((face-name
5998 (intern (format "org-block-%s" lang))))
5999 (append (and (facep face-name) (list face-name))
6000 '(org-block))))))) ; end of source block
6001 ((not org-fontify-quote-and-verse-blocks))
6002 ((string= block-type "quote")
6003 (add-face-text-property
6004 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6005 ((string= block-type "verse")
6006 (add-face-text-property
6007 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6008 (add-text-properties beg beg1 '(face org-block-begin-line))
6009 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6010 '(face org-block-end-line))
6012 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6013 (org-remove-flyspell-overlays-in
6014 (match-beginning 0)
6015 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6016 (add-text-properties
6017 beg (match-end 3)
6018 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6019 '(font-lock-fontified t invisible t)
6020 '(font-lock-fontified t face org-document-info-keyword)))
6021 (add-text-properties
6022 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6023 (if (string-equal dc1 "+title:")
6024 '(font-lock-fontified t face org-document-title)
6025 '(font-lock-fontified t face org-document-info))))
6026 ((string-prefix-p "+caption" dc1)
6027 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6028 (remove-text-properties (match-beginning 0) (match-end 0)
6029 '(display t invisible t intangible t))
6030 ;; Handle short captions.
6031 (save-excursion
6032 (beginning-of-line)
6033 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6034 (add-text-properties (line-beginning-position) (match-end 1)
6035 '(font-lock-fontified t face org-meta-line))
6036 (add-text-properties (match-end 0) (line-end-position)
6037 '(font-lock-fontified t face org-block))
6039 ((member dc3 '(" " ""))
6040 (org-remove-flyspell-overlays-in beg (match-end 0))
6041 (add-text-properties
6042 beg (match-end 0)
6043 '(font-lock-fontified t face font-lock-comment-face)))
6044 (t ;; just any other in-buffer setting, but not indented
6045 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6046 (remove-text-properties (match-beginning 0) (match-end 0)
6047 '(display t invisible t intangible t))
6048 (add-text-properties beg (match-end 0)
6049 '(font-lock-fontified t face org-meta-line))
6050 t))))))
6052 (defun org-fontify-drawers (limit)
6053 "Fontify drawers."
6054 (when (re-search-forward org-drawer-regexp limit t)
6055 (add-text-properties
6056 (match-beginning 0) (match-end 0)
6057 '(font-lock-fontified t face org-special-keyword))
6058 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6061 (defun org-fontify-macros (limit)
6062 "Fontify macros."
6063 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6064 (add-text-properties
6065 (match-beginning 0) (match-end 0)
6066 '(font-lock-fontified t face org-macro))
6067 (when org-hide-macro-markers
6068 (add-text-properties (match-end 2) (match-beginning 2)
6069 '(invisible t))
6070 (add-text-properties (match-beginning 1) (match-end 1)
6071 '(invisible t)))
6072 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6075 (defun org-activate-footnote-links (limit)
6076 "Add text properties for footnotes."
6077 (let ((fn (org-footnote-next-reference-or-definition limit)))
6078 (when fn
6079 (let* ((beg (nth 1 fn))
6080 (end (nth 2 fn))
6081 (label (car fn))
6082 (referencep (/= (line-beginning-position) beg)))
6083 (when (and referencep (nth 3 fn))
6084 (save-excursion
6085 (goto-char beg)
6086 (search-forward (or label "fn:"))
6087 (org-remove-flyspell-overlays-in beg (match-end 0))))
6088 (add-text-properties beg end
6089 (list 'mouse-face 'highlight
6090 'keymap org-mouse-map
6091 'help-echo
6092 (if referencep "Footnote reference"
6093 "Footnote definition")
6094 'font-lock-fontified t
6095 'font-lock-multiline t
6096 'face 'org-footnote))))))
6098 (defun org-activate-dates (limit)
6099 "Add text properties for dates."
6100 (when (and (re-search-forward org-tsr-regexp-both limit t)
6101 (not (equal (char-before (match-beginning 0)) 91)))
6102 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6103 (add-text-properties (match-beginning 0) (match-end 0)
6104 (list 'mouse-face 'highlight
6105 'keymap org-mouse-map))
6106 (org-rear-nonsticky-at (match-end 0))
6107 (when org-display-custom-times
6108 (if (match-end 3)
6109 (org-display-custom-time (match-beginning 3) (match-end 3))
6110 (org-display-custom-time (match-beginning 1) (match-end 1))))
6113 (defvar-local org-target-link-regexp nil
6114 "Regular expression matching radio targets in plain text.")
6116 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6117 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6118 border border border))
6119 "Regular expression matching a link target.")
6121 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6122 "Regular expression matching a radio target.")
6124 (defconst org-any-target-regexp
6125 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6126 "Regular expression matching any target.")
6128 (defun org-activate-target-links (limit)
6129 "Add text properties for target matches."
6130 (when org-target-link-regexp
6131 (let ((case-fold-search t))
6132 (when (re-search-forward org-target-link-regexp limit t)
6133 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6134 (add-text-properties (match-beginning 1) (match-end 1)
6135 (list 'mouse-face 'highlight
6136 'keymap org-mouse-map
6137 'help-echo "Radio target link"
6138 'org-linked-text t))
6139 (org-rear-nonsticky-at (match-end 1))
6140 t))))
6142 (defun org-update-radio-target-regexp ()
6143 "Find all radio targets in this file and update the regular expression.
6144 Also refresh fontification if needed."
6145 (interactive)
6146 (let ((old-regexp org-target-link-regexp)
6147 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6148 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6149 (targets
6150 (org-with-wide-buffer
6151 (goto-char (point-min))
6152 (let (rtn)
6153 (while (re-search-forward org-radio-target-regexp nil t)
6154 ;; Make sure point is really within the object.
6155 (backward-char)
6156 (let ((obj (org-element-context)))
6157 (when (eq (org-element-type obj) 'radio-target)
6158 (cl-pushnew (org-element-property :value obj) rtn
6159 :test #'equal))))
6160 rtn))))
6161 (setq org-target-link-regexp
6162 (and targets
6163 (concat before-re
6164 (mapconcat
6165 (lambda (x)
6166 (replace-regexp-in-string
6167 " +" "\\s-+" (regexp-quote x) t t))
6168 targets
6169 "\\|")
6170 after-re)))
6171 (unless (equal old-regexp org-target-link-regexp)
6172 ;; Clean-up cache.
6173 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6174 ((not org-target-link-regexp) old-regexp)
6176 (concat before-re
6177 (mapconcat
6178 (lambda (re)
6179 (substring re (length before-re)
6180 (- (length after-re))))
6181 (list old-regexp org-target-link-regexp)
6182 "\\|")
6183 after-re)))))
6184 (org-with-wide-buffer
6185 (goto-char (point-min))
6186 (while (re-search-forward regexp nil t)
6187 (org-element-cache-refresh (match-beginning 1)))))
6188 ;; Re fontify buffer.
6189 (when (memq 'radio org-highlight-links)
6190 (org-restart-font-lock)))))
6192 (defun org-hide-wide-columns (limit)
6193 (let (s e)
6194 (setq s (text-property-any (point) (or limit (point-max))
6195 'org-cwidth t))
6196 (when s
6197 (setq e (next-single-property-change s 'org-cwidth))
6198 (add-text-properties s e '(invisible org-cwidth))
6199 (goto-char e)
6200 t)))
6202 (defvar org-latex-and-related-regexp nil
6203 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6205 (defun org-compute-latex-and-related-regexp ()
6206 "Compute regular expression for LaTeX, entities and sub/superscript.
6207 Result depends on variable `org-highlight-latex-and-related'."
6208 (setq-local
6209 org-latex-and-related-regexp
6210 (let* ((re-sub
6211 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6212 ((eq org-use-sub-superscripts '{})
6213 (list org-match-substring-with-braces-regexp))
6214 (org-use-sub-superscripts (list org-match-substring-regexp))))
6215 (re-latex
6216 (when (memq 'latex org-highlight-latex-and-related)
6217 (let ((matchers (plist-get org-format-latex-options :matchers)))
6218 (delq nil
6219 (mapcar (lambda (x)
6220 (and (member (car x) matchers) (nth 1 x)))
6221 org-latex-regexps)))))
6222 (re-entities
6223 (when (memq 'entities org-highlight-latex-and-related)
6224 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6225 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6227 (defun org-do-latex-and-related (limit)
6228 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6229 LIMIT bounds the search for syntax to highlight. Stop at first
6230 highlighted object, if any. Return t if some highlighting was
6231 done, nil otherwise."
6232 (when (org-string-nw-p org-latex-and-related-regexp)
6233 (catch 'found
6234 (while (re-search-forward org-latex-and-related-regexp limit t)
6235 (unless
6236 (cl-some
6237 (lambda (f)
6238 (memq f '(org-code org-verbatim underline org-special-keyword)))
6239 (save-excursion
6240 (goto-char (1+ (match-beginning 0)))
6241 (face-at-point nil t)))
6242 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6243 '(?_ ?^))
6245 0)))
6246 (font-lock-prepend-text-property
6247 (+ offset (match-beginning 0)) (match-end 0)
6248 'face 'org-latex-and-related)
6249 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6250 '(font-lock-multiline t)))
6251 (throw 'found t)))
6252 nil)))
6254 (defun org-restart-font-lock ()
6255 "Restart `font-lock-mode', to force refontification."
6256 (when (and (boundp 'font-lock-mode) font-lock-mode)
6257 (font-lock-mode -1)
6258 (font-lock-mode 1)))
6260 (defun org-activate-tags (limit)
6261 (when (re-search-forward
6262 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6263 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6264 (add-text-properties (match-beginning 1) (match-end 1)
6265 (list 'mouse-face 'highlight
6266 'keymap org-mouse-map))
6267 (org-rear-nonsticky-at (match-end 1))
6270 (defun org-outline-level ()
6271 "Compute the outline level of the heading at point.
6273 If this is called at a normal headline, the level is the number
6274 of stars. Use `org-reduced-level' to remove the effect of
6275 `org-odd-levels'. Unlike to `org-current-level', this function
6276 takes into consideration inlinetasks."
6277 (org-with-wide-buffer
6278 (end-of-line)
6279 (if (re-search-backward org-outline-regexp-bol nil t)
6280 (1- (- (match-end 0) (match-beginning 0)))
6281 0)))
6283 (defvar org-font-lock-keywords nil)
6285 (defsubst org-re-property (property &optional literal allow-null value)
6286 "Return a regexp matching a PROPERTY line.
6288 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6289 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6290 non-nil, match properties even without a value.
6292 Match group 3 is set to the value when it exists. If there is no
6293 value and ALLOW-NULL is non-nil, it is set to the empty string.
6295 With optional argument VALUE, match only property lines with
6296 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6297 unless LITERAL is non-nil."
6298 (concat
6299 "^\\(?4:[ \t]*\\)"
6300 (format "\\(?1::\\(?2:%s\\):\\)"
6301 (if literal property (regexp-quote property)))
6302 (cond (value
6303 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6304 (if literal value (regexp-quote value))))
6305 (allow-null
6306 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6308 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6310 (defconst org-property-re
6311 (org-re-property "\\S-+" 'literal t)
6312 "Regular expression matching a property line.
6313 There are four matching groups:
6314 1: :PROPKEY: including the leading and trailing colon,
6315 2: PROPKEY without the leading and trailing colon,
6316 3: PROPVAL without leading or trailing spaces,
6317 4: the indentation of the current line,
6318 5: trailing whitespace.")
6320 (defvar org-font-lock-hook nil
6321 "Functions to be called for special font lock stuff.")
6323 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6325 (defvar org-font-lock-set-keywords-hook nil
6326 "Functions that can manipulate `org-font-lock-extra-keywords'.
6327 This is called after `org-font-lock-extra-keywords' is defined, but before
6328 it is installed to be used by font lock. This can be useful if something
6329 needs to be inserted at a specific position in the font-lock sequence.")
6331 (defun org-font-lock-hook (limit)
6332 "Run `org-font-lock-hook' within LIMIT."
6333 (run-hook-with-args 'org-font-lock-hook limit))
6335 (defun org-set-font-lock-defaults ()
6336 "Set font lock defaults for the current buffer."
6337 (let* ((em org-fontify-emphasized-text)
6338 (lk org-highlight-links)
6339 (org-font-lock-extra-keywords
6340 (list
6341 ;; Call the hook
6342 '(org-font-lock-hook)
6343 ;; Headlines
6344 `(,(if org-fontify-whole-heading-line
6345 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6346 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6347 (1 (org-get-level-face 1))
6348 (2 (org-get-level-face 2))
6349 (3 (org-get-level-face 3)))
6350 ;; Table lines
6351 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6352 (1 'org-table t))
6353 ;; Table internals
6354 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6355 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6356 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6357 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6358 ;; Drawers
6359 '(org-fontify-drawers)
6360 ;; Properties
6361 (list org-property-re
6362 '(1 'org-special-keyword t)
6363 '(3 'org-property-value t))
6364 ;; Link related fontification.
6365 '(org-activate-links)
6366 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6367 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6368 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6369 (when (memq 'footnote lk) '(org-activate-footnote-links))
6370 ;; Targets.
6371 (list org-any-target-regexp '(0 'org-target t))
6372 ;; Diary sexps.
6373 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6374 ;; Macro
6375 '(org-fontify-macros)
6376 '(org-hide-wide-columns (0 nil append))
6377 ;; TODO keyword
6378 (list (format org-heading-keyword-regexp-format
6379 org-todo-regexp)
6380 '(2 (org-get-todo-face 2) t))
6381 ;; DONE
6382 (if org-fontify-done-headline
6383 (list (format org-heading-keyword-regexp-format
6384 (concat
6385 "\\(?:"
6386 (mapconcat 'regexp-quote org-done-keywords "\\|")
6387 "\\)"))
6388 '(2 'org-headline-done t))
6389 nil)
6390 ;; Priorities
6391 '(org-font-lock-add-priority-faces)
6392 ;; Tags
6393 '(org-font-lock-add-tag-faces)
6394 ;; Tags groups
6395 (when (and org-group-tags org-tag-groups-alist)
6396 (list (concat org-outline-regexp-bol ".+\\(:"
6397 (regexp-opt (mapcar 'car org-tag-groups-alist))
6398 ":\\).*$")
6399 '(1 'org-tag-group prepend)))
6400 ;; Special keywords
6401 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6402 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6403 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6404 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6405 ;; Emphasis
6406 (when em '(org-do-emphasis-faces))
6407 ;; Checkboxes
6408 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6409 1 'org-checkbox prepend)
6410 (when (cdr (assq 'checkbox org-list-automatic-rules))
6411 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6412 (0 (org-get-checkbox-statistics-face) t)))
6413 ;; Description list items
6414 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6415 1 'org-list-dt prepend)
6416 ;; ARCHIVEd headings
6417 (list (concat
6418 org-outline-regexp-bol
6419 "\\(.*:" org-archive-tag ":.*\\)")
6420 '(1 'org-archived prepend))
6421 ;; Specials
6422 '(org-do-latex-and-related)
6423 '(org-fontify-entities)
6424 '(org-raise-scripts)
6425 ;; Code
6426 '(org-activate-code (1 'org-code t))
6427 ;; COMMENT
6428 (list (format
6429 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6430 org-todo-regexp
6431 org-comment-string)
6432 '(9 'org-special-keyword t))
6433 ;; Blocks and meta lines
6434 '(org-fontify-meta-lines-and-blocks))))
6435 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6436 (run-hooks 'org-font-lock-set-keywords-hook)
6437 ;; Now set the full font-lock-keywords
6438 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6439 (setq-local font-lock-defaults
6440 '(org-font-lock-keywords t nil nil backward-paragraph))
6441 (kill-local-variable 'font-lock-keywords)
6442 nil))
6444 (defun org-toggle-pretty-entities ()
6445 "Toggle the composition display of entities as UTF8 characters."
6446 (interactive)
6447 (setq-local org-pretty-entities (not org-pretty-entities))
6448 (org-restart-font-lock)
6449 (if org-pretty-entities
6450 (message "Entities are now displayed as UTF8 characters")
6451 (save-restriction
6452 (widen)
6453 (decompose-region (point-min) (point-max))
6454 (message "Entities are now displayed as plain text"))))
6456 (defvar-local org-custom-properties-overlays nil
6457 "List of overlays used for custom properties.")
6459 (defun org-toggle-custom-properties-visibility ()
6460 "Display or hide properties in `org-custom-properties'."
6461 (interactive)
6462 (if org-custom-properties-overlays
6463 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6464 (setq org-custom-properties-overlays nil))
6465 (when org-custom-properties
6466 (org-with-wide-buffer
6467 (goto-char (point-min))
6468 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6469 (while (re-search-forward regexp nil t)
6470 (let ((end (cdr (save-match-data (org-get-property-block)))))
6471 (when (and end (< (point) end))
6472 ;; Hide first custom property in current drawer.
6473 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6474 (overlay-put o 'invisible t)
6475 (overlay-put o 'org-custom-property t)
6476 (push o org-custom-properties-overlays))
6477 ;; Hide additional custom properties in the same drawer.
6478 (while (re-search-forward regexp end t)
6479 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6480 (overlay-put o 'invisible t)
6481 (overlay-put o 'org-custom-property t)
6482 (push o org-custom-properties-overlays)))))
6483 ;; Each entry is limited to a single property drawer.
6484 (outline-next-heading)))))))
6486 (defun org-fontify-entities (limit)
6487 "Find an entity to fontify."
6488 (let (ee)
6489 (when org-pretty-entities
6490 (catch 'match
6491 ;; "\_ "-family is left out on purpose. Only the first one,
6492 ;; i.e., "\_ ", could be fontified anyway, and it would be
6493 ;; confusing when adding a second white space character.
6494 (while (re-search-forward
6495 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6496 limit t)
6497 (when (and (not (org-at-comment-p))
6498 (setq ee (org-entity-get (match-string 1)))
6499 (= (length (nth 6 ee)) 1))
6500 (let* ((end (if (equal (match-string 2) "{}")
6501 (match-end 2)
6502 (match-end 1))))
6503 (add-text-properties
6504 (match-beginning 0) end
6505 (list 'font-lock-fontified t))
6506 (compose-region (match-beginning 0) end
6507 (nth 6 ee) nil)
6508 (backward-char 1)
6509 (throw 'match t))))
6510 nil))))
6512 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6513 "Fontify string S like in Org mode."
6514 (with-temp-buffer
6515 (insert s)
6516 (let ((org-odd-levels-only odd-levels))
6517 (org-mode)
6518 (org-font-lock-ensure)
6519 (buffer-string))))
6521 (defvar org-m nil)
6522 (defvar org-l nil)
6523 (defvar org-f nil)
6524 (defun org-get-level-face (n)
6525 "Get the right face for match N in font-lock matching of headlines."
6526 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6527 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6528 (if org-cycle-level-faces
6529 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6530 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6531 (cond
6532 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6533 ((eq n 2) org-f)
6534 (t (unless org-level-color-stars-only org-f))))
6536 (defun org-face-from-face-or-color (context inherit face-or-color)
6537 "Create a face list that inherits INHERIT, but sets the foreground color.
6538 When FACE-OR-COLOR is not a string, just return it."
6539 (if (stringp face-or-color)
6540 (list :inherit inherit
6541 (cdr (assoc context org-faces-easy-properties))
6542 face-or-color)
6543 face-or-color))
6545 (defun org-get-todo-face (kwd)
6546 "Get the right face for a TODO keyword KWD.
6547 If KWD is a number, get the corresponding match group."
6548 (when (numberp kwd) (setq kwd (match-string kwd)))
6549 (or (org-face-from-face-or-color
6550 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6551 (and (member kwd org-done-keywords) 'org-done)
6552 'org-todo))
6554 (defun org-get-priority-face (priority)
6555 "Get the right face for PRIORITY.
6556 PRIORITY is a character."
6557 (or (org-face-from-face-or-color
6558 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6559 'org-priority))
6561 (defun org-get-tag-face (tag)
6562 "Get the right face for TAG.
6563 If TAG is a number, get the corresponding match group."
6564 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6565 (or (org-face-from-face-or-color
6566 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6567 'org-tag)))
6569 (defun org-font-lock-add-priority-faces (limit)
6570 "Add the special priority faces."
6571 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6572 (add-text-properties
6573 (match-beginning 1) (match-end 1)
6574 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6575 'font-lock-fontified t))))
6577 (defun org-font-lock-add-tag-faces (limit)
6578 "Add the special tag faces."
6579 (when (and org-tag-faces org-tags-special-faces-re)
6580 (while (re-search-forward org-tags-special-faces-re limit t)
6581 (add-text-properties (match-beginning 1) (match-end 1)
6582 (list 'face (org-get-tag-face 1)
6583 'font-lock-fontified t))
6584 (backward-char 1))))
6586 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6587 "Remove fontification and activation overlays from links."
6588 (font-lock-default-unfontify-region beg end)
6589 (let* ((buffer-undo-list t)
6590 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6591 (inhibit-modification-hooks t)
6592 deactivate-mark buffer-file-name buffer-file-truename)
6593 (decompose-region beg end)
6594 (remove-text-properties beg end
6595 '(mouse-face t keymap t org-linked-text t
6596 invisible t intangible t
6597 org-emphasis t))
6598 (org-remove-font-lock-display-properties beg end)))
6600 (defconst org-script-display '(((raise -0.3) (height 0.7))
6601 ((raise 0.3) (height 0.7))
6602 ((raise -0.5))
6603 ((raise 0.5)))
6604 "Display properties for showing superscripts and subscripts.")
6606 (defun org-remove-font-lock-display-properties (beg end)
6607 "Remove specific display properties that have been added by font lock.
6608 The will remove the raise properties that are used to show superscripts
6609 and subscripts."
6610 (let (next prop)
6611 (while (< beg end)
6612 (setq next (next-single-property-change beg 'display nil end)
6613 prop (get-text-property beg 'display))
6614 (when (member prop org-script-display)
6615 (put-text-property beg next 'display nil))
6616 (setq beg next))))
6618 (defun org-raise-scripts (limit)
6619 "Add raise properties to sub/superscripts."
6620 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6621 (re-search-forward
6622 (if (eq org-use-sub-superscripts t)
6623 org-match-substring-regexp
6624 org-match-substring-with-braces-regexp)
6625 limit t))
6626 (let* ((pos (point)) table-p comment-p
6627 (mpos (match-beginning 3))
6628 (emph-p (get-text-property mpos 'org-emphasis))
6629 (link-p (get-text-property mpos 'mouse-face))
6630 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6631 (goto-char (point-at-bol))
6632 (setq table-p (looking-at-p org-table-dataline-regexp)
6633 comment-p (looking-at-p "^[ \t]*#[ +]"))
6634 (goto-char pos)
6635 ;; Handle a_b^c
6636 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6637 (unless (or comment-p emph-p link-p keyw-p)
6638 (put-text-property (match-beginning 3) (match-end 0)
6639 'display
6640 (if (equal (char-after (match-beginning 2)) ?^)
6641 (nth (if table-p 3 1) org-script-display)
6642 (nth (if table-p 2 0) org-script-display)))
6643 (add-text-properties (match-beginning 2) (match-end 2)
6644 (list 'invisible t
6645 'org-dwidth t 'org-dwidth-n 1))
6646 (if (and (eq (char-after (match-beginning 3)) ?{)
6647 (eq (char-before (match-end 3)) ?}))
6648 (progn
6649 (add-text-properties
6650 (match-beginning 3) (1+ (match-beginning 3))
6651 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6652 (add-text-properties
6653 (1- (match-end 3)) (match-end 3)
6654 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6655 t)))
6657 ;;;; Visibility cycling, including org-goto and indirect buffer
6659 ;;; Cycling
6661 (defvar-local org-cycle-global-status nil)
6662 (put 'org-cycle-global-status 'org-state t)
6663 (defvar-local org-cycle-subtree-status nil)
6664 (put 'org-cycle-subtree-status 'org-state t)
6666 (defvar org-inlinetask-min-level)
6668 (defun org-unlogged-message (&rest args)
6669 "Display a message, but avoid logging it in the *Messages* buffer."
6670 (let ((message-log-max nil))
6671 (apply 'message args)))
6673 ;;;###autoload
6674 (defun org-cycle (&optional arg)
6675 "TAB-action and visibility cycling for Org mode.
6677 This is the command invoked in Org mode by the `TAB' key. Its main
6678 purpose is outline visibility cycling, but it also invokes other actions
6679 in special contexts.
6681 When this function is called with a `\\[universal-argument]' prefix, rotate \
6682 the entire
6683 buffer through 3 states (global cycling)
6684 1. OVERVIEW: Show only top-level headlines.
6685 2. CONTENTS: Show all headlines of all levels, but no body text.
6686 3. SHOW ALL: Show everything.
6688 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6689 switch to the startup visibility,
6690 determined by the variable `org-startup-folded', and by any VISIBILITY
6691 properties in the buffer.
6693 With a `\\[universal-argument] \\[universal-argument] \
6694 \\[universal-argument]' prefix argument, show the entire buffer, including
6695 any drawers.
6697 When inside a table, re-align the table and move to the next field.
6699 When point is at the beginning of a headline, rotate the subtree started
6700 by this line through 3 different states (local cycling)
6701 1. FOLDED: Only the main headline is shown.
6702 2. CHILDREN: The main headline and the direct children are shown.
6703 From this state, you can move to one of the children
6704 and zoom in further.
6705 3. SUBTREE: Show the entire subtree, including body text.
6706 If there is no subtree, switch directly from CHILDREN to FOLDED.
6708 When point is at the beginning of an empty headline and the variable
6709 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6710 of the headline by demoting and promoting it to likely levels. This
6711 speeds up creation document structure by pressing `TAB' once or several
6712 times right after creating a new headline.
6714 When there is a numeric prefix, go up to a heading with level ARG, do
6715 a `show-subtree' and return to the previous cursor position. If ARG
6716 is negative, go up that many levels.
6718 When point is not at the beginning of a headline, execute the global
6719 binding for `TAB', which is re-indenting the line. See the option
6720 `org-cycle-emulate-tab' for details.
6722 As a special case, if point is at the beginning of the buffer and there is
6723 no headline in line 1, this function will act as if called with prefix arg
6724 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6725 prefix arg, but only
6726 if the variable `org-cycle-global-at-bob' is t."
6727 (interactive "P")
6728 (org-load-modules-maybe)
6729 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6730 (and org-cycle-level-after-item/entry-creation
6731 (or (org-cycle-level)
6732 (org-cycle-item-indentation))))
6733 (let* ((limit-level
6734 (or org-cycle-max-level
6735 (and (boundp 'org-inlinetask-min-level)
6736 org-inlinetask-min-level
6737 (1- org-inlinetask-min-level))))
6738 (nstars (and limit-level
6739 (if org-odd-levels-only
6740 (and limit-level (1- (* limit-level 2)))
6741 limit-level)))
6742 (org-outline-regexp
6743 (if (not (derived-mode-p 'org-mode))
6744 outline-regexp
6745 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6746 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6747 (not (looking-at org-outline-regexp))))
6748 (org-cycle-hook
6749 (if bob-special
6750 (delq 'org-optimize-window-after-visibility-change
6751 (copy-sequence org-cycle-hook))
6752 org-cycle-hook))
6753 (pos (point)))
6755 (cond
6757 ((equal arg '(16))
6758 (setq last-command 'dummy)
6759 (org-set-startup-visibility)
6760 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6762 ((equal arg '(64))
6763 (outline-show-all)
6764 (org-unlogged-message "Entire buffer visible, including drawers"))
6766 ((equal arg '(4)) (org-cycle-internal-global))
6768 ;; Try hiding block at point.
6769 ((org-hide-block-toggle-maybe))
6771 ;; Try cdlatex TAB completion
6772 ((org-try-cdlatex-tab))
6774 ;; Table: enter it or move to the next field.
6775 ((org-at-table-p 'any)
6776 (if (org-at-table.el-p)
6777 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6778 Use `\\[org-edit-special]' to edit table.el tables"))
6779 (if arg (org-table-edit-field t)
6780 (org-table-justify-field-maybe)
6781 (call-interactively 'org-table-next-field))))
6783 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6785 ;; Global cycling: delegate to `org-cycle-internal-global'.
6786 (bob-special (org-cycle-internal-global))
6788 ;; Drawers: delegate to `org-flag-drawer'.
6789 ((save-excursion
6790 (beginning-of-line 1)
6791 (looking-at org-drawer-regexp))
6792 (org-flag-drawer ; toggle block visibility
6793 (not (get-char-property (match-end 0) 'invisible))))
6795 ;; Show-subtree, ARG levels up from here.
6796 ((integerp arg)
6797 (save-excursion
6798 (org-back-to-heading)
6799 (outline-up-heading (if (< arg 0) (- arg)
6800 (- (funcall outline-level) arg)))
6801 (org-show-subtree)))
6803 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6804 ((and (featurep 'org-inlinetask)
6805 (org-inlinetask-at-task-p)
6806 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6807 (org-inlinetask-toggle-visibility))
6809 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6810 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6811 (save-excursion (move-beginning-of-line 1)
6812 (looking-at org-outline-regexp)))
6813 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6814 (org-cycle-internal-local))
6816 ;; From there: TAB emulation and template completion.
6817 (buffer-read-only (org-back-to-heading))
6819 ((run-hook-with-args-until-success
6820 'org-tab-after-check-for-cycling-hook))
6822 ((org-try-structure-completion))
6824 ((run-hook-with-args-until-success
6825 'org-tab-before-tab-emulation-hook))
6827 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6828 (or (not (bolp))
6829 (not (looking-at org-outline-regexp))))
6830 (call-interactively (global-key-binding "\t")))
6832 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6833 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6834 (or (and (eq org-cycle-emulate-tab 'white)
6835 (= (match-end 0) (point-at-eol)))
6836 (and (eq org-cycle-emulate-tab 'whitestart)
6837 (>= (match-end 0) pos))))
6839 (eq org-cycle-emulate-tab t))
6840 (call-interactively (global-key-binding "\t")))
6842 (t (save-excursion
6843 (org-back-to-heading)
6844 (org-cycle)))))))
6846 (defun org-cycle-internal-global ()
6847 "Do the global cycling action."
6848 ;; Hack to avoid display of messages for .org attachments in Gnus
6849 (let ((ga (string-match "\\*fontification" (buffer-name))))
6850 (cond
6851 ((and (eq last-command this-command)
6852 (eq org-cycle-global-status 'overview))
6853 ;; We just created the overview - now do table of contents
6854 ;; This can be slow in very large buffers, so indicate action
6855 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6856 (unless ga (org-unlogged-message "CONTENTS..."))
6857 (org-content)
6858 (unless ga (org-unlogged-message "CONTENTS...done"))
6859 (setq org-cycle-global-status 'contents)
6860 (run-hook-with-args 'org-cycle-hook 'contents))
6862 ((and (eq last-command this-command)
6863 (eq org-cycle-global-status 'contents))
6864 ;; We just showed the table of contents - now show everything
6865 (run-hook-with-args 'org-pre-cycle-hook 'all)
6866 (outline-show-all)
6867 (unless ga (org-unlogged-message "SHOW ALL"))
6868 (setq org-cycle-global-status 'all)
6869 (run-hook-with-args 'org-cycle-hook 'all))
6872 ;; Default action: go to overview
6873 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6874 (org-overview)
6875 (unless ga (org-unlogged-message "OVERVIEW"))
6876 (setq org-cycle-global-status 'overview)
6877 (run-hook-with-args 'org-cycle-hook 'overview)))))
6879 (defvar org-called-with-limited-levels nil
6880 "Non-nil when `org-with-limited-levels' is currently active.")
6882 (defun org-invisible-p (&optional pos)
6883 "Non-nil if the character after POS is invisible.
6884 If POS is nil, use `point' instead."
6885 (get-char-property (or pos (point)) 'invisible))
6887 (defun org-cycle-internal-local ()
6888 "Do the local cycling action."
6889 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6890 ;; First, determine end of headline (EOH), end of subtree or item
6891 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6892 (save-excursion
6893 (if (org-at-item-p)
6894 (progn
6895 (beginning-of-line)
6896 (setq struct (org-list-struct))
6897 (setq eoh (point-at-eol))
6898 (setq eos (org-list-get-item-end-before-blank (point) struct))
6899 (setq has-children (org-list-has-child-p (point) struct)))
6900 (org-back-to-heading)
6901 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6902 (setq eos (save-excursion (org-end-of-subtree t t)
6903 (when (bolp) (backward-char)) (point)))
6904 (setq has-children
6905 (or (save-excursion
6906 (let ((level (funcall outline-level)))
6907 (outline-next-heading)
6908 (and (org-at-heading-p t)
6909 (> (funcall outline-level) level))))
6910 (save-excursion
6911 (org-list-search-forward (org-item-beginning-re) eos t)))))
6912 ;; Determine end invisible part of buffer (EOL)
6913 (beginning-of-line 2)
6914 (while (and (not (eobp)) ;This is like `next-line'.
6915 (get-char-property (1- (point)) 'invisible))
6916 (goto-char (next-single-char-property-change (point) 'invisible))
6917 (and (eolp) (beginning-of-line 2)))
6918 (setq eol (point)))
6919 ;; Find out what to do next and set `this-command'
6920 (cond
6921 ((= eos eoh)
6922 ;; Nothing is hidden behind this heading
6923 (unless (org-before-first-heading-p)
6924 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6925 (org-unlogged-message "EMPTY ENTRY")
6926 (setq org-cycle-subtree-status nil)
6927 (save-excursion
6928 (goto-char eos)
6929 (outline-next-heading)
6930 (when (org-invisible-p) (org-flag-heading nil))))
6931 ((and (or (>= eol eos)
6932 (not (string-match "\\S-" (buffer-substring eol eos))))
6933 (or has-children
6934 (not (setq children-skipped
6935 org-cycle-skip-children-state-if-no-children))))
6936 ;; Entire subtree is hidden in one line: children view
6937 (unless (org-before-first-heading-p)
6938 (run-hook-with-args 'org-pre-cycle-hook 'children))
6939 (if (org-at-item-p)
6940 (org-list-set-item-visibility (point-at-bol) struct 'children)
6941 (org-show-entry)
6942 (org-with-limited-levels (org-show-children))
6943 ;; FIXME: This slows down the func way too much.
6944 ;; How keep drawers hidden in subtree anyway?
6945 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6946 ;; (org-cycle-hide-drawers 'subtree))
6948 ;; Fold every list in subtree to top-level items.
6949 (when (eq org-cycle-include-plain-lists 'integrate)
6950 (save-excursion
6951 (org-back-to-heading)
6952 (while (org-list-search-forward (org-item-beginning-re) eos t)
6953 (beginning-of-line 1)
6954 (let* ((struct (org-list-struct))
6955 (prevs (org-list-prevs-alist struct))
6956 (end (org-list-get-bottom-point struct)))
6957 (dolist (e (org-list-get-all-items (point) struct prevs))
6958 (org-list-set-item-visibility e struct 'folded))
6959 (goto-char (if (< end eos) end eos)))))))
6960 (org-unlogged-message "CHILDREN")
6961 (save-excursion
6962 (goto-char eos)
6963 (outline-next-heading)
6964 (when (org-invisible-p) (org-flag-heading nil)))
6965 (setq org-cycle-subtree-status 'children)
6966 (unless (org-before-first-heading-p)
6967 (run-hook-with-args 'org-cycle-hook 'children)))
6968 ((or children-skipped
6969 (and (eq last-command this-command)
6970 (eq org-cycle-subtree-status 'children)))
6971 ;; We just showed the children, or no children are there,
6972 ;; now show everything.
6973 (unless (org-before-first-heading-p)
6974 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6975 (outline-flag-region eoh eos nil)
6976 (org-unlogged-message
6977 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6978 (setq org-cycle-subtree-status 'subtree)
6979 (unless (org-before-first-heading-p)
6980 (run-hook-with-args 'org-cycle-hook 'subtree)))
6982 ;; Default action: hide the subtree.
6983 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6984 (outline-flag-region eoh eos t)
6985 (org-unlogged-message "FOLDED")
6986 (setq org-cycle-subtree-status 'folded)
6987 (unless (org-before-first-heading-p)
6988 (run-hook-with-args 'org-cycle-hook 'folded))))))
6990 ;;;###autoload
6991 (defun org-global-cycle (&optional arg)
6992 "Cycle the global visibility. For details see `org-cycle'.
6993 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6994 With a numeric prefix, show all headlines up to that level."
6995 (interactive "P")
6996 (let ((org-cycle-include-plain-lists
6997 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6998 (cond
6999 ((integerp arg)
7000 (outline-show-all)
7001 (outline-hide-sublevels arg)
7002 (setq org-cycle-global-status 'contents))
7003 ((equal arg '(4))
7004 (org-set-startup-visibility)
7005 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7007 (org-cycle '(4))))))
7009 (defun org-set-startup-visibility ()
7010 "Set the visibility required by startup options and properties."
7011 (cond
7012 ((eq org-startup-folded t)
7013 (org-overview))
7014 ((eq org-startup-folded 'content)
7015 (org-content))
7016 ((or (eq org-startup-folded 'showeverything)
7017 (eq org-startup-folded nil))
7018 (outline-show-all)))
7019 (unless (eq org-startup-folded 'showeverything)
7020 (when org-hide-block-startup (org-hide-block-all))
7021 (org-set-visibility-according-to-property 'no-cleanup)
7022 (org-cycle-hide-archived-subtrees 'all)
7023 (org-cycle-hide-drawers 'all)
7024 (org-cycle-show-empty-lines t)))
7026 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7027 "Switch subtree visibilities according to :VISIBILITY: property."
7028 (interactive)
7029 (org-with-wide-buffer
7030 (goto-char (point-min))
7031 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7032 (if (not (org-at-property-p)) (outline-next-heading)
7033 (let ((state (match-string 3)))
7034 (save-excursion
7035 (org-back-to-heading t)
7036 (outline-hide-subtree)
7037 (org-reveal)
7038 (cond
7039 ((equal state "folded")
7040 (outline-hide-subtree))
7041 ((equal state "children")
7042 (org-show-hidden-entry)
7043 (org-show-children))
7044 ((equal state "content")
7045 (save-excursion
7046 (save-restriction
7047 (org-narrow-to-subtree)
7048 (org-content))))
7049 ((member state '("all" "showall"))
7050 (outline-show-subtree)))))))
7051 (unless no-cleanup
7052 (org-cycle-hide-archived-subtrees 'all)
7053 (org-cycle-hide-drawers 'all)
7054 (org-cycle-show-empty-lines 'all))))
7056 ;; This function uses outline-regexp instead of the more fundamental
7057 ;; org-outline-regexp so that org-cycle-global works outside of Org
7058 ;; buffers, where outline-regexp is needed.
7059 (defun org-overview ()
7060 "Switch to overview mode, showing only top-level headlines.
7061 This shows all headlines with a level equal or greater than the level
7062 of the first headline in the buffer. This is important, because if the
7063 first headline is not level one, then (hide-sublevels 1) gives confusing
7064 results."
7065 (interactive)
7066 (save-excursion
7067 (let ((level
7068 (save-excursion
7069 (goto-char (point-min))
7070 (when (re-search-forward (concat "^" outline-regexp) nil t)
7071 (goto-char (match-beginning 0))
7072 (funcall outline-level)))))
7073 (and level (outline-hide-sublevels level)))))
7075 (defun org-content (&optional arg)
7076 "Show all headlines in the buffer, like a table of contents.
7077 With numerical argument N, show content up to level N."
7078 (interactive "P")
7079 (org-overview)
7080 (save-excursion
7081 ;; Visit all headings and show their offspring
7082 (and (integerp arg) (org-overview))
7083 (goto-char (point-max))
7084 (catch 'exit
7085 (while (and (progn (condition-case nil
7086 (outline-previous-visible-heading 1)
7087 (error (goto-char (point-min))))
7089 (looking-at org-outline-regexp))
7090 (if (integerp arg)
7091 (org-show-children (1- arg))
7092 (outline-show-branches))
7093 (when (bobp) (throw 'exit nil))))))
7095 (defun org-optimize-window-after-visibility-change (state)
7096 "Adjust the window after a change in outline visibility.
7097 This function is the default value of the hook `org-cycle-hook'."
7098 (when (get-buffer-window (current-buffer))
7099 (cond
7100 ((eq state 'content) nil)
7101 ((eq state 'all) nil)
7102 ((eq state 'folded) nil)
7103 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7104 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7106 (defun org-remove-empty-overlays-at (pos)
7107 "Remove outline overlays that do not contain non-white stuff."
7108 (dolist (o (overlays-at pos))
7109 (and (eq 'outline (overlay-get o 'invisible))
7110 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7111 (overlay-end o))))
7112 (delete-overlay o))))
7114 (defun org-clean-visibility-after-subtree-move ()
7115 "Fix visibility issues after moving a subtree."
7116 ;; First, find a reasonable region to look at:
7117 ;; Start two siblings above, end three below
7118 (let* ((beg (save-excursion
7119 (and (org-get-last-sibling)
7120 (org-get-last-sibling))
7121 (point)))
7122 (end (save-excursion
7123 (and (org-get-next-sibling)
7124 (org-get-next-sibling)
7125 (org-get-next-sibling))
7126 (if (org-at-heading-p)
7127 (point-at-eol)
7128 (point))))
7129 (level (looking-at "\\*+"))
7130 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7131 (save-excursion
7132 (save-restriction
7133 (narrow-to-region beg end)
7134 (when re
7135 ;; Properly fold already folded siblings
7136 (goto-char (point-min))
7137 (while (re-search-forward re nil t)
7138 (when (and (not (org-invisible-p))
7139 (save-excursion
7140 (goto-char (point-at-eol)) (org-invisible-p)))
7141 (outline-hide-entry))))
7142 (org-cycle-show-empty-lines 'overview)
7143 (org-cycle-hide-drawers 'overview)))))
7145 (defun org-cycle-show-empty-lines (state)
7146 "Show empty lines above all visible headlines.
7147 The region to be covered depends on STATE when called through
7148 `org-cycle-hook'. Lisp program can use t for STATE to get the
7149 entire buffer covered. Note that an empty line is only shown if there
7150 are at least `org-cycle-separator-lines' empty lines before the headline."
7151 (when (/= org-cycle-separator-lines 0)
7152 (save-excursion
7153 (let* ((n (abs org-cycle-separator-lines))
7154 (re (cond
7155 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7156 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7157 (t (let ((ns (number-to-string (- n 2))))
7158 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7159 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7160 beg end)
7161 (cond
7162 ((memq state '(overview contents t))
7163 (setq beg (point-min) end (point-max)))
7164 ((memq state '(children folded))
7165 (setq beg (point)
7166 end (progn (org-end-of-subtree t t)
7167 (line-beginning-position 2)))))
7168 (when beg
7169 (goto-char beg)
7170 (while (re-search-forward re end t)
7171 (unless (get-char-property (match-end 1) 'invisible)
7172 (let ((e (match-end 1))
7173 (b (if (>= org-cycle-separator-lines 0)
7174 (match-beginning 1)
7175 (save-excursion
7176 (goto-char (match-beginning 0))
7177 (skip-chars-backward " \t\n")
7178 (line-end-position)))))
7179 (outline-flag-region b e nil))))))))
7180 ;; Never hide empty lines at the end of the file.
7181 (save-excursion
7182 (goto-char (point-max))
7183 (outline-previous-heading)
7184 (outline-end-of-heading)
7185 (when (and (looking-at "[ \t\n]+")
7186 (= (match-end 0) (point-max)))
7187 (outline-flag-region (point) (match-end 0) nil))))
7189 (defun org-show-empty-lines-in-parent ()
7190 "Move to the parent and re-show empty lines before visible headlines."
7191 (save-excursion
7192 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7193 (org-cycle-show-empty-lines context))))
7195 (defun org-files-list ()
7196 "Return `org-agenda-files' list, plus all open Org files.
7197 This is useful for operations that need to scan all of a user's
7198 open and agenda-wise Org files."
7199 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7200 (dolist (buf (buffer-list))
7201 (with-current-buffer buf
7202 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7203 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7204 files))
7206 (defsubst org-entry-beginning-position ()
7207 "Return the beginning position of the current entry."
7208 (save-excursion (org-back-to-heading t) (point)))
7210 (defsubst org-entry-end-position ()
7211 "Return the end position of the current entry."
7212 (save-excursion (outline-next-heading) (point)))
7214 (defun org-cycle-hide-drawers (state &optional exceptions)
7215 "Re-hide all drawers after a visibility state change.
7216 When non-nil, optional argument EXCEPTIONS is a list of strings
7217 specifying which drawers should not be hidden."
7218 (when (and (derived-mode-p 'org-mode)
7219 (not (memq state '(overview folded contents))))
7220 (save-excursion
7221 (let* ((globalp (memq state '(contents all)))
7222 (beg (if globalp (point-min) (point)))
7223 (end (if globalp (point-max)
7224 (if (eq state 'children)
7225 (save-excursion (outline-next-heading) (point))
7226 (org-end-of-subtree t)))))
7227 (goto-char beg)
7228 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7229 (unless (member-ignore-case (match-string 1) exceptions)
7230 (let ((drawer (org-element-at-point)))
7231 (when (memq (org-element-type drawer) '(drawer property-drawer))
7232 (org-flag-drawer t drawer)
7233 ;; Make sure to skip drawer entirely or we might flag
7234 ;; it another time when matching its ending line with
7235 ;; `org-drawer-regexp'.
7236 (goto-char (org-element-property :end drawer))))))))))
7238 (defun org-flag-drawer (flag &optional element)
7239 "When FLAG is non-nil, hide the drawer we are at.
7240 Otherwise make it visible. When optional argument ELEMENT is
7241 a parsed drawer, as returned by `org-element-at-point', hide or
7242 show that drawer instead."
7243 (let ((drawer (or element
7244 (and (save-excursion
7245 (beginning-of-line)
7246 (looking-at-p org-drawer-regexp))
7247 (org-element-at-point)))))
7248 (when (memq (org-element-type drawer) '(drawer property-drawer))
7249 (let ((post (org-element-property :post-affiliated drawer)))
7250 (save-excursion
7251 (outline-flag-region
7252 (progn (goto-char post) (line-end-position))
7253 (progn (goto-char (org-element-property :end drawer))
7254 (skip-chars-backward " \r\t\n")
7255 (line-end-position))
7256 flag))
7257 ;; When the drawer is hidden away, make sure point lies in
7258 ;; a visible part of the buffer.
7259 (when (and flag (> (line-beginning-position) post))
7260 (goto-char post))))))
7262 (defun org-subtree-end-visible-p ()
7263 "Is the end of the current subtree visible?"
7264 (pos-visible-in-window-p
7265 (save-excursion (org-end-of-subtree t) (point))))
7267 (defun org-first-headline-recenter ()
7268 "Move cursor to the first headline and recenter the headline."
7269 (let ((window (get-buffer-window)))
7270 (when window
7271 (goto-char (point-min))
7272 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7273 (set-window-start window (line-beginning-position))))))
7275 ;;; Saving and restoring visibility
7277 (defun org-outline-overlay-data (&optional use-markers)
7278 "Return a list of the locations of all outline overlays.
7279 These are overlays with the `invisible' property value `outline'.
7280 The return value is a list of cons cells, with start and stop
7281 positions for each overlay.
7282 If USE-MARKERS is set, return the positions as markers."
7283 (let (beg end)
7284 (org-with-wide-buffer
7285 (delq nil
7286 (mapcar (lambda (o)
7287 (when (eq (overlay-get o 'invisible) 'outline)
7288 (setq beg (overlay-start o)
7289 end (overlay-end o))
7290 (and beg end (> end beg)
7291 (if use-markers
7292 (cons (copy-marker beg)
7293 (copy-marker end t))
7294 (cons beg end)))))
7295 (overlays-in (point-min) (point-max)))))))
7297 (defun org-set-outline-overlay-data (data)
7298 "Create visibility overlays for all positions in DATA.
7299 DATA should have been made by `org-outline-overlay-data'."
7300 (org-with-wide-buffer
7301 (outline-show-all)
7302 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7304 ;;; Folding of blocks
7306 (defvar-local org-hide-block-overlays nil
7307 "Overlays hiding blocks.")
7309 (defun org-block-map (function &optional start end)
7310 "Call FUNCTION at the head of all source blocks in the current buffer.
7311 Optional arguments START and END can be used to limit the range."
7312 (let ((start (or start (point-min)))
7313 (end (or end (point-max))))
7314 (save-excursion
7315 (goto-char start)
7316 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7317 (save-excursion
7318 (save-match-data
7319 (goto-char (match-beginning 0))
7320 (funcall function)))))))
7322 (defun org-hide-block-toggle-all ()
7323 "Toggle the visibility of all blocks in the current buffer."
7324 (org-block-map 'org-hide-block-toggle))
7326 (defun org-hide-block-all ()
7327 "Fold all blocks in the current buffer."
7328 (interactive)
7329 (org-show-block-all)
7330 (org-block-map 'org-hide-block-toggle-maybe))
7332 (defun org-show-block-all ()
7333 "Unfold all blocks in the current buffer."
7334 (interactive)
7335 (mapc #'delete-overlay org-hide-block-overlays)
7336 (setq org-hide-block-overlays nil))
7338 (defun org-hide-block-toggle-maybe ()
7339 "Toggle visibility of block at point.
7340 Unlike to `org-hide-block-toggle', this function does not throw
7341 an error. Return a non-nil value when toggling is successful."
7342 (interactive)
7343 (ignore-errors (org-hide-block-toggle)))
7345 (defun org-hide-block-toggle (&optional force)
7346 "Toggle the visibility of the current block.
7347 When optional argument FORCE is `off', make block visible. If it
7348 is non-nil, hide it unconditionally. Throw an error when not at
7349 a block. Return a non-nil value when toggling is successful."
7350 (interactive)
7351 (let ((element (org-element-at-point)))
7352 (unless (memq (org-element-type element)
7353 '(center-block comment-block dynamic-block example-block
7354 export-block quote-block special-block
7355 src-block verse-block))
7356 (user-error "Not at a block"))
7357 (let* ((start (save-excursion
7358 (goto-char (org-element-property :post-affiliated element))
7359 (line-end-position)))
7360 (end (save-excursion
7361 (goto-char (org-element-property :end element))
7362 (skip-chars-backward " \r\t\n")
7363 (line-end-position)))
7364 (overlays (overlays-at start)))
7365 (cond
7366 ;; Do nothing when not before or at the block opening line or
7367 ;; at the block closing line.
7368 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7369 ((and (not (eq force 'off))
7370 (not (memq t (mapcar
7371 (lambda (o)
7372 (eq (overlay-get o 'invisible) 'org-hide-block))
7373 overlays))))
7374 (let ((ov (make-overlay start end)))
7375 (overlay-put ov 'invisible 'org-hide-block)
7376 ;; Make the block accessible to `isearch'.
7377 (overlay-put
7378 ov 'isearch-open-invisible
7379 (lambda (ov)
7380 (when (memq ov org-hide-block-overlays)
7381 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7382 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7383 (delete-overlay ov))))
7384 (push ov org-hide-block-overlays)
7385 ;; When the block is hidden away, make sure point is left in
7386 ;; a visible part of the buffer.
7387 (when (> (line-beginning-position) start)
7388 (goto-char start)
7389 (beginning-of-line))
7390 ;; Signal successful toggling.
7392 ((or (not force) (eq force 'off))
7393 (dolist (ov overlays t)
7394 (when (memq ov org-hide-block-overlays)
7395 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7396 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7397 (delete-overlay ov))))))))
7399 ;; Remove overlays when changing major mode
7400 (add-hook 'org-mode-hook
7401 (lambda () (add-hook 'change-major-mode-hook
7402 'org-show-block-all 'append 'local)))
7404 ;;; Org-goto
7406 (defvar org-goto-window-configuration nil)
7407 (defvar org-goto-marker nil)
7408 (defvar org-goto-map)
7409 (defun org-goto-map ()
7410 "Set the keymap `org-goto'."
7411 (setq org-goto-map
7412 (let ((map (make-sparse-keymap)))
7413 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7414 mouse-drag-region universal-argument org-occur)))
7415 (dolist (cmd cmds)
7416 (substitute-key-definition cmd cmd map global-map)))
7417 (suppress-keymap map)
7418 (org-defkey map "\C-m" 'org-goto-ret)
7419 (org-defkey map [(return)] 'org-goto-ret)
7420 (org-defkey map [(left)] 'org-goto-left)
7421 (org-defkey map [(right)] 'org-goto-right)
7422 (org-defkey map [(control ?g)] 'org-goto-quit)
7423 (org-defkey map "\C-i" 'org-cycle)
7424 (org-defkey map [(tab)] 'org-cycle)
7425 (org-defkey map [(down)] 'outline-next-visible-heading)
7426 (org-defkey map [(up)] 'outline-previous-visible-heading)
7427 (if org-goto-auto-isearch
7428 (if (fboundp 'define-key-after)
7429 (define-key-after map [t] 'org-goto-local-auto-isearch)
7430 nil)
7431 (org-defkey map "q" 'org-goto-quit)
7432 (org-defkey map "n" 'outline-next-visible-heading)
7433 (org-defkey map "p" 'outline-previous-visible-heading)
7434 (org-defkey map "f" 'outline-forward-same-level)
7435 (org-defkey map "b" 'outline-backward-same-level)
7436 (org-defkey map "u" 'outline-up-heading))
7437 (org-defkey map "/" 'org-occur)
7438 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7439 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7440 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7441 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7442 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7443 map)))
7445 (defconst org-goto-help
7446 "Browse buffer copy, to find location or copy text.%s
7447 RET=jump to location C-g=quit and return to previous location
7448 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7450 (defvar org-goto-start-pos) ; dynamically scoped parameter
7452 (defun org-goto (&optional alternative-interface)
7453 "Look up a different location in the current file, keeping current visibility.
7455 When you want look-up or go to a different location in a
7456 document, the fastest way is often to fold the entire buffer and
7457 then dive into the tree. This method has the disadvantage, that
7458 the previous location will be folded, which may not be what you
7459 want.
7461 This command works around this by showing a copy of the current
7462 buffer in an indirect buffer, in overview mode. You can dive
7463 into the tree in that copy, use org-occur and incremental search
7464 to find a location. When pressing RET or `Q', the command
7465 returns to the original buffer in which the visibility is still
7466 unchanged. After RET it will also jump to the location selected
7467 in the indirect buffer and expose the headline hierarchy above.
7469 With a prefix argument, use the alternative interface: e.g., if
7470 `org-goto-interface' is `outline' use `outline-path-completion'."
7471 (interactive "P")
7472 (org-goto-map)
7473 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7474 (org-refile-use-outline-path t)
7475 (org-refile-target-verify-function nil)
7476 (interface
7477 (if (not alternative-interface)
7478 org-goto-interface
7479 (if (eq org-goto-interface 'outline)
7480 'outline-path-completion
7481 'outline)))
7482 (org-goto-start-pos (point))
7483 (selected-point
7484 (if (eq interface 'outline)
7485 (car (org-get-location (current-buffer) org-goto-help))
7486 (let ((pa (org-refile-get-location "Goto")))
7487 (org-refile-check-position pa)
7488 (nth 3 pa)))))
7489 (if selected-point
7490 (progn
7491 (org-mark-ring-push org-goto-start-pos)
7492 (goto-char selected-point)
7493 (when (or (org-invisible-p) (org-invisible-p2))
7494 (org-show-context 'org-goto)))
7495 (message "Quit"))))
7497 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7498 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7499 (defvar org-goto-local-auto-isearch-map) ; defined below
7501 (defun org-get-location (_buf help)
7502 "Let the user select a location in current buffer.
7503 This function uses a recursive edit. It returns the selected position
7504 or nil."
7505 (org-no-popups
7506 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7507 (isearch-hide-immediately nil)
7508 (isearch-search-fun-function
7509 (lambda () 'org-goto-local-search-headings))
7510 (org-goto-selected-point org-goto-exit-command))
7511 (save-excursion
7512 (save-window-excursion
7513 (delete-other-windows)
7514 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7515 (pop-to-buffer-same-window
7516 (condition-case nil
7517 (make-indirect-buffer (current-buffer) "*org-goto*")
7518 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7519 (with-output-to-temp-buffer "*Org Help*"
7520 (princ (format help (if org-goto-auto-isearch
7521 " Just type for auto-isearch."
7522 " n/p/f/b/u to navigate, q to quit."))))
7523 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7524 (setq buffer-read-only nil)
7525 (let ((org-startup-truncated t)
7526 (org-startup-folded nil)
7527 (org-startup-align-all-tables nil))
7528 (org-mode)
7529 (org-overview))
7530 (setq buffer-read-only t)
7531 (if (and (boundp 'org-goto-start-pos)
7532 (integer-or-marker-p org-goto-start-pos))
7533 (progn (goto-char org-goto-start-pos)
7534 (when (org-invisible-p)
7535 (org-show-set-visibility 'lineage)))
7536 (goto-char (point-min)))
7537 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7538 (message "Select location and press RET")
7539 (use-local-map org-goto-map)
7540 (recursive-edit)))
7541 (kill-buffer "*org-goto*")
7542 (cons org-goto-selected-point org-goto-exit-command))))
7544 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7545 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7546 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7547 (if (fboundp 'isearch-other-control-char)
7548 (progn
7549 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7550 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7551 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7552 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7553 (define-key org-goto-local-auto-isearch-map [return] nil))
7555 (defun org-goto-local-search-headings (string bound noerror)
7556 "Search and make sure that any matches are in headlines."
7557 (catch 'return
7558 (while (if isearch-forward
7559 (search-forward string bound noerror)
7560 (search-backward string bound noerror))
7561 (when (save-match-data
7562 (and (save-excursion
7563 (beginning-of-line)
7564 (looking-at org-complex-heading-regexp))
7565 (or (not (match-beginning 5))
7566 (< (point) (match-beginning 5)))))
7567 (throw 'return (point))))))
7569 (defun org-goto-local-auto-isearch ()
7570 "Start isearch."
7571 (interactive)
7572 (goto-char (point-min))
7573 (let ((keys (this-command-keys)))
7574 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7575 (isearch-mode t)
7576 (isearch-process-search-char (string-to-char keys)))))
7578 (defun org-goto-ret (&optional _arg)
7579 "Finish `org-goto' by going to the new location."
7580 (interactive "P")
7581 (setq org-goto-selected-point (point))
7582 (setq org-goto-exit-command 'return)
7583 (throw 'exit nil))
7585 (defun org-goto-left ()
7586 "Finish `org-goto' by going to the new location."
7587 (interactive)
7588 (if (org-at-heading-p)
7589 (progn
7590 (beginning-of-line 1)
7591 (setq org-goto-selected-point (point)
7592 org-goto-exit-command 'left)
7593 (throw 'exit nil))
7594 (user-error "Not on a heading")))
7596 (defun org-goto-right ()
7597 "Finish `org-goto' by going to the new location."
7598 (interactive)
7599 (if (org-at-heading-p)
7600 (progn
7601 (setq org-goto-selected-point (point)
7602 org-goto-exit-command 'right)
7603 (throw 'exit nil))
7604 (user-error "Not on a heading")))
7606 (defun org-goto-quit ()
7607 "Finish `org-goto' without cursor motion."
7608 (interactive)
7609 (setq org-goto-selected-point nil)
7610 (setq org-goto-exit-command 'quit)
7611 (throw 'exit nil))
7613 ;;; Indirect buffer display of subtrees
7615 (defvar org-indirect-dedicated-frame nil
7616 "This is the frame being used for indirect tree display.")
7617 (defvar org-last-indirect-buffer nil)
7619 (defun org-tree-to-indirect-buffer (&optional arg)
7620 "Create indirect buffer and narrow it to current subtree.
7622 With a numerical prefix ARG, go up to this level and then take that tree.
7623 If ARG is negative, go up that many levels.
7625 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7626 indirect buffer previously made with this command, to avoid proliferation of
7627 indirect buffers. However, when you call the command with a \
7628 `\\[universal-argument]' prefix, or
7629 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7630 so that you can work with several indirect buffers at the same time. If
7631 `org-indirect-buffer-display' is `dedicated-frame', the \
7632 `\\[universal-argument]' prefix also
7633 requests that a new frame be made for the new buffer, so that the dedicated
7634 frame is not changed."
7635 (interactive "P")
7636 (let ((cbuf (current-buffer))
7637 (cwin (selected-window))
7638 (pos (point))
7639 beg end level heading ibuf)
7640 (save-excursion
7641 (org-back-to-heading t)
7642 (when (numberp arg)
7643 (setq level (org-outline-level))
7644 (when (< arg 0) (setq arg (+ level arg)))
7645 (while (> (setq level (org-outline-level)) arg)
7646 (org-up-heading-safe)))
7647 (setq beg (point)
7648 heading (org-get-heading 'no-tags))
7649 (org-end-of-subtree t t)
7650 (when (org-at-heading-p) (backward-char 1))
7651 (setq end (point)))
7652 (when (and (buffer-live-p org-last-indirect-buffer)
7653 (not (eq org-indirect-buffer-display 'new-frame))
7654 (not arg))
7655 (kill-buffer org-last-indirect-buffer))
7656 (setq ibuf (org-get-indirect-buffer cbuf heading)
7657 org-last-indirect-buffer ibuf)
7658 (cond
7659 ((or (eq org-indirect-buffer-display 'new-frame)
7660 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7661 (select-frame (make-frame))
7662 (delete-other-windows)
7663 (pop-to-buffer-same-window ibuf)
7664 (org-set-frame-title heading))
7665 ((eq org-indirect-buffer-display 'dedicated-frame)
7666 (raise-frame
7667 (select-frame (or (and org-indirect-dedicated-frame
7668 (frame-live-p org-indirect-dedicated-frame)
7669 org-indirect-dedicated-frame)
7670 (setq org-indirect-dedicated-frame (make-frame)))))
7671 (delete-other-windows)
7672 (pop-to-buffer-same-window ibuf)
7673 (org-set-frame-title (concat "Indirect: " heading)))
7674 ((eq org-indirect-buffer-display 'current-window)
7675 (pop-to-buffer-same-window ibuf))
7676 ((eq org-indirect-buffer-display 'other-window)
7677 (pop-to-buffer ibuf))
7678 (t (error "Invalid value")))
7679 (narrow-to-region beg end)
7680 (outline-show-all)
7681 (goto-char pos)
7682 (run-hook-with-args 'org-cycle-hook 'all)
7683 (and (window-live-p cwin) (select-window cwin))))
7685 (defun org-get-indirect-buffer (&optional buffer heading)
7686 (setq buffer (or buffer (current-buffer)))
7687 (let ((n 1) (base (buffer-name buffer)) bname)
7688 (while (buffer-live-p
7689 (get-buffer
7690 (setq bname
7691 (concat base "-"
7692 (if heading (concat heading "-" (number-to-string n))
7693 (number-to-string n))))))
7694 (setq n (1+ n)))
7695 (condition-case nil
7696 (make-indirect-buffer buffer bname 'clone)
7697 (error (make-indirect-buffer buffer bname)))))
7699 (defun org-set-frame-title (title)
7700 "Set the title of the current frame to the string TITLE."
7701 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7703 ;;;; Structure editing
7705 ;;; Inserting headlines
7707 (defun org--line-empty-p (n)
7708 "Is the Nth next line empty?
7710 Counts the current line as N = 1 and the previous line as N = 0;
7711 see `beginning-of-line'."
7712 (save-excursion
7713 (and (not (bobp))
7714 (or (beginning-of-line n) t)
7715 (save-match-data
7716 (looking-at "[ \t]*$")))))
7718 (defun org-previous-line-empty-p ()
7719 "Is the previous line a blank line?
7720 When NEXT is non-nil, check the next line instead."
7721 (org--line-empty-p 0))
7723 (defun org-next-line-empty-p ()
7724 "Is the previous line a blank line?
7725 When NEXT is non-nil, check the next line instead."
7726 (org--line-empty-p 2))
7728 (defun org--blank-before-heading-p (&optional parent)
7729 "Non-nil when an empty line should precede a new heading here.
7730 When optional argument PARENT is non-nil, consider parent
7731 headline instead of current one."
7732 (pcase (assq 'heading org-blank-before-new-entry)
7733 (`(heading . auto)
7734 (save-excursion
7735 (org-with-limited-levels
7736 (unless (and (org-before-first-heading-p)
7737 (not (outline-next-heading)))
7738 (org-back-to-heading t)
7739 (when parent (org-up-heading-safe))
7740 (cond ((not (bobp))
7741 (org-previous-line-empty-p))
7742 ((outline-next-heading)
7743 (org-previous-line-empty-p))
7744 ;; Ignore trailing spaces on last buffer line.
7745 ((progn (skip-chars-backward " \t") (bolp))
7746 (org-previous-line-empty-p))
7747 (t nil))))))
7748 (`(heading . ,value) value)
7749 (_ nil)))
7751 (defun org-insert-heading (&optional arg invisible-ok top)
7752 "Insert a new heading or an item with the same depth at point.
7754 If point is at the beginning of a heading, insert a new heading
7755 or a new headline above the current one. When at the beginning
7756 of a regular line of text, turn it into a heading.
7758 If point is in the middle of a line, split it and create a new
7759 headline with the text in the current line after point (see
7760 `org-M-RET-may-split-line' on how to modify this behavior). As
7761 a special case, on a headline, splitting can only happen on the
7762 title itself. E.g., this excludes breaking stars or tags.
7764 With a `\\[universal-argument]' prefix, set \
7765 `org-insert-heading-respect-content' to
7766 a non-nil value for the duration of the command. This forces the
7767 insertion of a heading after the current subtree, independently
7768 on the location of point.
7770 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7771 insert the heading at the end of the tree
7772 above the current heading. For example, if point is within a
7773 2nd-level heading, then it will insert a 2nd-level heading at
7774 the end of the 1st-level parent subtree.
7776 When INVISIBLE-OK is set, stop at invisible headlines when going
7777 back. This is important for non-interactive uses of the
7778 command.
7780 When optional argument TOP is non-nil, insert a level 1 heading,
7781 unconditionally."
7782 (interactive "P")
7783 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7784 (level (org-current-level))
7785 (stars (make-string (if (and level (not top)) level 1) ?*)))
7786 (cond
7787 ((or org-insert-heading-respect-content
7788 (member arg '((4) (16)))
7789 (and (not invisible-ok)
7790 (invisible-p (max (1- (point)) (point-min)))))
7791 ;; Position point at the location of insertion.
7792 (if (not level) ;before first headline
7793 (org-with-limited-levels (outline-next-heading))
7794 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7795 ;; is nil.
7796 (org-with-limited-levels (org-back-to-heading invisible-ok))
7797 (cond ((equal arg '(16))
7798 (org-up-heading-safe)
7799 (org-end-of-subtree t t))
7801 (org-end-of-subtree t t))))
7802 (unless (bolp) (insert "\n")) ;ensure final newline
7803 (unless (and blank? (org-previous-line-empty-p))
7804 (org-N-empty-lines-before-current (if blank? 1 0)))
7805 (insert stars " \n")
7806 (forward-char -1))
7807 ;; At a headline...
7808 ((org-at-heading-p)
7809 (cond ((bolp)
7810 (when blank? (save-excursion (insert "\n")))
7811 (save-excursion (insert stars " \n"))
7812 (unless (and blank? (org-previous-line-empty-p))
7813 (org-N-empty-lines-before-current (if blank? 1 0)))
7814 (end-of-line))
7815 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7816 (org-match-line org-complex-heading-regexp)
7817 (org-pos-in-match-range (point) 4))
7818 ;; Grab the text that should moved to the new headline.
7819 ;; Preserve tags.
7820 (let ((split (delete-and-extract-region (point) (match-end 4))))
7821 (if (looking-at "[ \t]*$") (replace-match "")
7822 (org-set-tags nil t))
7823 (end-of-line)
7824 (when blank? (insert "\n"))
7825 (insert "\n" stars " ")
7826 (when (org-string-nw-p split) (insert split))
7827 (when (eobp) (save-excursion (insert "\n")))))
7829 (end-of-line)
7830 (when blank? (insert "\n"))
7831 (insert "\n" stars " ")
7832 (when (eobp) (save-excursion (insert "\n"))))))
7833 ;; On regular text, turn line into a headline or split, if
7834 ;; appropriate.
7835 ((bolp)
7836 (insert stars " ")
7837 (unless (and blank? (org-previous-line-empty-p))
7838 (org-N-empty-lines-before-current (if blank? 1 0))))
7840 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7841 (end-of-line))
7842 (insert "\n" stars " ")
7843 (unless (and blank? (org-previous-line-empty-p))
7844 (org-N-empty-lines-before-current (if blank? 1 0))))))
7845 (run-hooks 'org-insert-heading-hook))
7847 (defun org-N-empty-lines-before-current (n)
7848 "Make the number of empty lines before current exactly N.
7849 So this will delete or add empty lines."
7850 (let ((column (current-column)))
7851 (beginning-of-line)
7852 (unless (bobp)
7853 (let ((start (save-excursion
7854 (skip-chars-backward " \r\t\n")
7855 (line-end-position))))
7856 (delete-region start (line-end-position 0))))
7857 (insert (make-string n ?\n))
7858 (move-to-column column)))
7860 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7861 "Return the heading of the current entry, without the stars.
7862 When NO-TAGS is non-nil, don't include tags.
7863 When NO-TODO is non-nil, don't include TODO keywords.
7864 When NO-PRIORITY is non-nil, don't include priority cookie.
7865 When NO-COMMENT is non-nil, don't include COMMENT string."
7866 (save-excursion
7867 (org-back-to-heading t)
7868 (let ((case-fold-search nil))
7869 (looking-at org-complex-heading-regexp)
7870 (let ((todo (and (not no-todo) (match-string 2)))
7871 (priority (and (not no-priority) (match-string 3)))
7872 (headline (pcase (match-string 4)
7873 (`nil "")
7874 ((and (guard no-comment) h)
7875 (replace-regexp-in-string
7876 (eval-when-compile
7877 (format "\\`%s[ \t]+" org-comment-string))
7878 "" h))
7879 (h h)))
7880 (tags (and (not no-tags) (match-string 5))))
7881 (mapconcat #'identity
7882 (delq nil (list todo priority headline tags))
7883 " ")))))
7885 (defvar orgstruct-mode) ; defined below
7887 (defun org-heading-components ()
7888 "Return the components of the current heading.
7889 This is a list with the following elements:
7890 - the level as an integer
7891 - the reduced level, different if `org-odd-levels-only' is set.
7892 - the TODO keyword, or nil
7893 - the priority character, like ?A, or nil if no priority is given
7894 - the headline text itself, or the tags string if no headline text
7895 - the tags string, or nil."
7896 (save-excursion
7897 (org-back-to-heading t)
7898 (when (let (case-fold-search)
7899 (looking-at
7900 (if orgstruct-mode
7901 org-heading-regexp
7902 org-complex-heading-regexp)))
7903 (if orgstruct-mode
7904 (list (length (match-string 1))
7905 (org-reduced-level (length (match-string 1)))
7908 (match-string 2)
7909 nil)
7910 (list (length (match-string 1))
7911 (org-reduced-level (length (match-string 1)))
7912 (match-string-no-properties 2)
7913 (and (match-end 3) (aref (match-string 3) 2))
7914 (match-string-no-properties 4)
7915 (match-string-no-properties 5))))))
7917 (defun org-get-entry ()
7918 "Get the entry text, after heading, entire subtree."
7919 (save-excursion
7920 (org-back-to-heading t)
7921 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7923 (defun org-edit-headline (&optional heading)
7924 "Edit the current headline.
7925 Set it to HEADING when provided."
7926 (interactive)
7927 (org-with-wide-buffer
7928 (org-back-to-heading t)
7929 (let ((case-fold-search nil))
7930 (when (looking-at org-complex-heading-regexp)
7931 (let* ((old (match-string-no-properties 4))
7932 (new (save-match-data
7933 (org-trim (or heading (read-string "Edit: " old))))))
7934 (unless (equal old new)
7935 (if old (replace-match new t t nil 4)
7936 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7937 (insert " " new))
7938 (org-set-tags nil t)
7939 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7941 (defun org-insert-heading-after-current ()
7942 "Insert a new heading with same level as current, after current subtree."
7943 (interactive)
7944 (org-back-to-heading)
7945 (org-insert-heading)
7946 (org-move-subtree-down)
7947 (end-of-line 1))
7949 (defun org-insert-heading-respect-content (&optional invisible-ok)
7950 "Insert heading with `org-insert-heading-respect-content' set to t."
7951 (interactive)
7952 (org-insert-heading '(4) invisible-ok))
7954 (defun org-insert-todo-heading-respect-content (&optional force-state)
7955 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7956 (interactive)
7957 (org-insert-todo-heading force-state '(4)))
7959 (defun org-insert-todo-heading (arg &optional force-heading)
7960 "Insert a new heading with the same level and TODO state as current heading.
7962 If the heading has no TODO state, or if the state is DONE, use
7963 the first state (TODO by default). Also with one prefix arg,
7964 force first state. With two prefix args, force inserting at the
7965 end of the parent subtree.
7967 When called at a plain list item, insert a new item with an
7968 unchecked check box."
7969 (interactive "P")
7970 (when (or force-heading (not (org-insert-item 'checkbox)))
7971 (org-insert-heading (or (and (equal arg '(16)) '(16))
7972 force-heading))
7973 (save-excursion
7974 (org-back-to-heading)
7975 (outline-previous-heading)
7976 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7977 (let* ((new-mark-x
7978 (if (or (equal arg '(4))
7979 (not (match-beginning 2))
7980 (member (match-string 2) org-done-keywords))
7981 (car org-todo-keywords-1)
7982 (match-string 2)))
7983 (new-mark
7985 (run-hook-with-args-until-success
7986 'org-todo-get-default-hook new-mark-x nil)
7987 new-mark-x)))
7988 (beginning-of-line 1)
7989 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7990 (if org-treat-insert-todo-heading-as-state-change
7991 (org-todo new-mark)
7992 (insert new-mark " "))))
7993 (when org-provide-todo-statistics
7994 (org-update-parent-todo-statistics))))
7996 (defun org-insert-subheading (arg)
7997 "Insert a new subheading and demote it.
7998 Works for outline headings and for plain lists alike."
7999 (interactive "P")
8000 (org-insert-heading arg)
8001 (cond
8002 ((org-at-heading-p) (org-do-demote))
8003 ((org-at-item-p) (org-indent-item))))
8005 (defun org-insert-todo-subheading (arg)
8006 "Insert a new subheading with TODO keyword or checkbox and demote it.
8007 Works for outline headings and for plain lists alike."
8008 (interactive "P")
8009 (org-insert-todo-heading arg)
8010 (cond
8011 ((org-at-heading-p) (org-do-demote))
8012 ((org-at-item-p) (org-indent-item))))
8014 ;;; Promotion and Demotion
8016 (defvar org-after-demote-entry-hook nil
8017 "Hook run after an entry has been demoted.
8018 The cursor will be at the beginning of the entry.
8019 When a subtree is being demoted, the hook will be called for each node.")
8021 (defvar org-after-promote-entry-hook nil
8022 "Hook run after an entry has been promoted.
8023 The cursor will be at the beginning of the entry.
8024 When a subtree is being promoted, the hook will be called for each node.")
8026 (defun org-promote-subtree ()
8027 "Promote the entire subtree.
8028 See also `org-promote'."
8029 (interactive)
8030 (save-excursion
8031 (org-with-limited-levels (org-map-tree 'org-promote)))
8032 (org-fix-position-after-promote))
8034 (defun org-demote-subtree ()
8035 "Demote the entire subtree.
8036 See `org-demote' and `org-promote'."
8037 (interactive)
8038 (save-excursion
8039 (org-with-limited-levels (org-map-tree 'org-demote)))
8040 (org-fix-position-after-promote))
8042 (defun org-do-promote ()
8043 "Promote the current heading higher up the tree.
8044 If the region is active in `transient-mark-mode', promote all
8045 headings in the region."
8046 (interactive)
8047 (save-excursion
8048 (if (org-region-active-p)
8049 (org-map-region 'org-promote (region-beginning) (region-end))
8050 (org-promote)))
8051 (org-fix-position-after-promote))
8053 (defun org-do-demote ()
8054 "Demote the current heading lower down the tree.
8055 If the region is active in `transient-mark-mode', demote all
8056 headings in the region."
8057 (interactive)
8058 (save-excursion
8059 (if (org-region-active-p)
8060 (org-map-region 'org-demote (region-beginning) (region-end))
8061 (org-demote)))
8062 (org-fix-position-after-promote))
8064 (defun org-fix-position-after-promote ()
8065 "Fix cursor position and indentation after demoting/promoting."
8066 (let ((pos (point)))
8067 (when (save-excursion
8068 (beginning-of-line)
8069 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8070 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8071 (cond ((eobp) (insert " "))
8072 ((eolp) (insert " "))
8073 ((equal (char-after) ?\s) (forward-char 1))))))
8075 (defun org-current-level ()
8076 "Return the level of the current entry, or nil if before the first headline.
8077 The level is the number of stars at the beginning of the
8078 headline. Use `org-reduced-level' to remove the effect of
8079 `org-odd-levels'. Unlike to `org-outline-level', this function
8080 ignores inlinetasks."
8081 (let ((level (org-with-limited-levels (org-outline-level))))
8082 (and (> level 0) level)))
8084 (defun org-get-previous-line-level ()
8085 "Return the outline depth of the last headline before the current line.
8086 Returns 0 for the first headline in the buffer, and nil if before the
8087 first headline."
8088 (and (org-current-level)
8089 (or (and (/= (line-beginning-position) (point-min))
8090 (save-excursion (beginning-of-line 0) (org-current-level)))
8091 0)))
8093 (defun org-reduced-level (l)
8094 "Compute the effective level of a heading.
8095 This takes into account the setting of `org-odd-levels-only'."
8096 (cond
8097 ((zerop l) 0)
8098 (org-odd-levels-only (1+ (floor (/ l 2))))
8099 (t l)))
8101 (defun org-level-increment ()
8102 "Return the number of stars that will be added or removed at a
8103 time to headlines when structure editing, based on the value of
8104 `org-odd-levels-only'."
8105 (if org-odd-levels-only 2 1))
8107 (defun org-get-valid-level (level &optional change)
8108 "Rectify a level change under the influence of `org-odd-levels-only'.
8109 LEVEL is a current level, CHANGE is by how much the level should
8110 be modified. Even if CHANGE is nil, LEVEL may be returned
8111 modified because even level numbers will become the next higher
8112 odd number. Returns values greater than 0."
8113 (if org-odd-levels-only
8114 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8115 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8116 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8117 (max 1 (+ level (or change 0)))))
8119 (defun org-promote ()
8120 "Promote the current heading higher up the tree."
8121 (org-with-wide-buffer
8122 (org-back-to-heading t)
8123 (let* ((after-change-functions (remq 'flyspell-after-change-function
8124 after-change-functions))
8125 (level (save-match-data (funcall outline-level)))
8126 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8127 (diff (abs (- level (length up-head) -1))))
8128 (cond
8129 ((and (= level 1) org-allow-promoting-top-level-subtree)
8130 (replace-match "# " nil t))
8131 ((= level 1)
8132 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8133 (t (replace-match up-head nil t)))
8134 (unless (= level 1)
8135 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8136 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8137 (run-hooks 'org-after-promote-entry-hook))))
8139 (defun org-demote ()
8140 "Demote the current heading lower down the tree."
8141 (org-with-wide-buffer
8142 (org-back-to-heading t)
8143 (let* ((after-change-functions (remq 'flyspell-after-change-function
8144 after-change-functions))
8145 (level (save-match-data (funcall outline-level)))
8146 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8147 (diff (abs (- level (length down-head) -1))))
8148 (replace-match down-head nil t)
8149 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8150 (when org-adapt-indentation (org-fixup-indentation diff))
8151 (run-hooks 'org-after-demote-entry-hook))))
8153 (defun org-cycle-level ()
8154 "Cycle the level of an empty headline through possible states.
8155 This goes first to child, then to parent, level, then up the hierarchy.
8156 After top level, it switches back to sibling level."
8157 (interactive)
8158 (let ((org-adapt-indentation nil))
8159 (when (org-point-at-end-of-empty-headline)
8160 (setq this-command 'org-cycle-level) ; Only needed for caching
8161 (let ((cur-level (org-current-level))
8162 (prev-level (org-get-previous-line-level)))
8163 (cond
8164 ;; If first headline in file, promote to top-level.
8165 ((= prev-level 0)
8166 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8167 do (org-do-promote)))
8168 ;; If same level as prev, demote one.
8169 ((= prev-level cur-level)
8170 (org-do-demote))
8171 ;; If parent is top-level, promote to top level if not already.
8172 ((= prev-level 1)
8173 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8174 do (org-do-promote)))
8175 ;; If top-level, return to prev-level.
8176 ((= cur-level 1)
8177 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8178 do (org-do-demote)))
8179 ;; If less than prev-level, promote one.
8180 ((< cur-level prev-level)
8181 (org-do-promote))
8182 ;; If deeper than prev-level, promote until higher than
8183 ;; prev-level.
8184 ((> cur-level prev-level)
8185 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8186 do (org-do-promote))))
8187 t))))
8189 (defun org-map-tree (fun)
8190 "Call FUN for every heading underneath the current one."
8191 (org-back-to-heading t)
8192 (let ((level (funcall outline-level)))
8193 (save-excursion
8194 (funcall fun)
8195 (while (and (progn
8196 (outline-next-heading)
8197 (> (funcall outline-level) level))
8198 (not (eobp)))
8199 (funcall fun)))))
8201 (defun org-map-region (fun beg end)
8202 "Call FUN for every heading between BEG and END."
8203 (let ((org-ignore-region t))
8204 (save-excursion
8205 (setq end (copy-marker end))
8206 (goto-char beg)
8207 (when (and (re-search-forward org-outline-regexp-bol nil t)
8208 (< (point) end))
8209 (funcall fun))
8210 (while (and (progn
8211 (outline-next-heading)
8212 (< (point) end))
8213 (not (eobp)))
8214 (funcall fun)))))
8216 (defun org-fixup-indentation (diff)
8217 "Change the indentation in the current entry by DIFF.
8219 DIFF is an integer. Indentation is done according to the
8220 following rules:
8222 - Planning information and property drawers are always indented
8223 according to the new level of the headline;
8225 - Footnote definitions and their contents are ignored;
8227 - Inlinetasks' boundaries are not shifted;
8229 - Empty lines are ignored;
8231 - Other lines' indentation are shifted by DIFF columns, unless
8232 it would introduce a structural change in the document, in
8233 which case no shifting is done at all.
8235 Assume point is at a heading or an inlinetask beginning."
8236 (org-with-wide-buffer
8237 (narrow-to-region (line-beginning-position)
8238 (save-excursion
8239 (if (org-with-limited-levels (org-at-heading-p))
8240 (org-with-limited-levels (outline-next-heading))
8241 (org-inlinetask-goto-end))
8242 (point)))
8243 (forward-line)
8244 ;; Indent properly planning info and property drawer.
8245 (when (looking-at-p org-planning-line-re)
8246 (org-indent-line)
8247 (forward-line))
8248 (when (looking-at org-property-drawer-re)
8249 (goto-char (match-end 0))
8250 (forward-line)
8251 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8252 (catch 'no-shift
8253 (when (zerop diff) (throw 'no-shift nil))
8254 ;; If DIFF is negative, first check if a shift is possible at all
8255 ;; (e.g., it doesn't break structure). This can only happen if
8256 ;; some contents are not properly indented.
8257 (let ((case-fold-search t))
8258 (when (< diff 0)
8259 (let ((diff (- diff))
8260 (forbidden-re (concat org-outline-regexp
8261 "\\|"
8262 (substring org-footnote-definition-re 1))))
8263 (save-excursion
8264 (while (not (eobp))
8265 (cond
8266 ((looking-at-p "[ \t]*$") (forward-line))
8267 ((and (looking-at-p org-footnote-definition-re)
8268 (let ((e (org-element-at-point)))
8269 (and (eq (org-element-type e) 'footnote-definition)
8270 (goto-char (org-element-property :end e))))))
8271 ((looking-at-p org-outline-regexp) (forward-line))
8272 ;; Give up if shifting would move before column 0 or
8273 ;; if it would introduce a headline or a footnote
8274 ;; definition.
8276 (skip-chars-forward " \t")
8277 (let ((ind (current-column)))
8278 (when (or (< ind diff)
8279 (and (= ind diff) (looking-at-p forbidden-re)))
8280 (throw 'no-shift nil)))
8281 ;; Ignore contents of example blocks and source
8282 ;; blocks if their indentation is meant to be
8283 ;; preserved. Jump to block's closing line.
8284 (beginning-of-line)
8285 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8286 (let ((e (org-element-at-point)))
8287 (and (memq (org-element-type e)
8288 '(example-block src-block))
8289 (or org-src-preserve-indentation
8290 (org-element-property :preserve-indent e))
8291 (goto-char (org-element-property :end e))
8292 (progn (skip-chars-backward " \r\t\n")
8293 (beginning-of-line)
8294 t))))
8295 (forward-line))))))))
8296 ;; Shift lines but footnote definitions, inlinetasks boundaries
8297 ;; by DIFF. Also skip contents of source or example blocks
8298 ;; when indentation is meant to be preserved.
8299 (while (not (eobp))
8300 (cond
8301 ((and (looking-at-p org-footnote-definition-re)
8302 (let ((e (org-element-at-point)))
8303 (and (eq (org-element-type e) 'footnote-definition)
8304 (goto-char (org-element-property :end e))))))
8305 ((looking-at-p org-outline-regexp) (forward-line))
8306 ((looking-at-p "[ \t]*$") (forward-line))
8308 (indent-line-to (+ (org-get-indentation) diff))
8309 (beginning-of-line)
8310 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8311 (let ((e (org-element-at-point)))
8312 (and (memq (org-element-type e)
8313 '(example-block src-block))
8314 (or org-src-preserve-indentation
8315 (org-element-property :preserve-indent e))
8316 (goto-char (org-element-property :end e))
8317 (progn (skip-chars-backward " \r\t\n")
8318 (beginning-of-line)
8319 t))))
8320 (forward-line)))))))))
8322 (defun org-convert-to-odd-levels ()
8323 "Convert an Org file with all levels allowed to one with odd levels.
8324 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8325 level 5 etc."
8326 (interactive)
8327 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8328 (let ((outline-level 'org-outline-level)
8329 (org-odd-levels-only nil) n)
8330 (save-excursion
8331 (goto-char (point-min))
8332 (while (re-search-forward "^\\*\\*+ " nil t)
8333 (setq n (- (length (match-string 0)) 2))
8334 (while (>= (setq n (1- n)) 0)
8335 (org-demote))
8336 (end-of-line 1))))))
8338 (defun org-convert-to-oddeven-levels ()
8339 "Convert an Org file with only odd levels to one with odd/even levels.
8340 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8341 file contains a section with an even level, conversion would
8342 destroy the structure of the file. An error is signaled in this
8343 case."
8344 (interactive)
8345 (goto-char (point-min))
8346 ;; First check if there are no even levels
8347 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8348 (org-show-set-visibility 'canonical)
8349 (error "Not all levels are odd in this file. Conversion not possible"))
8350 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8351 (let ((outline-regexp org-outline-regexp)
8352 (outline-level 'org-outline-level)
8353 (org-odd-levels-only nil) n)
8354 (save-excursion
8355 (goto-char (point-min))
8356 (while (re-search-forward "^\\*\\*+ " nil t)
8357 (setq n (/ (1- (length (match-string 0))) 2))
8358 (while (>= (setq n (1- n)) 0)
8359 (org-promote))
8360 (end-of-line 1))))))
8362 (defun org-tr-level (n)
8363 "Make N odd if required."
8364 (if org-odd-levels-only (1+ (/ n 2)) n))
8366 ;;; Vertical tree motion, cutting and pasting of subtrees
8368 (defun org-move-subtree-up (&optional arg)
8369 "Move the current subtree up past ARG headlines of the same level."
8370 (interactive "p")
8371 (org-move-subtree-down (- (prefix-numeric-value arg))))
8373 (defun org-move-subtree-down (&optional arg)
8374 "Move the current subtree down past ARG headlines of the same level."
8375 (interactive "p")
8376 (setq arg (prefix-numeric-value arg))
8377 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8378 'org-get-last-sibling))
8379 (ins-point (make-marker))
8380 (cnt (abs arg))
8381 (col (current-column))
8382 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8383 ;; Select the tree
8384 (org-back-to-heading)
8385 (setq beg0 (point))
8386 (save-excursion
8387 (setq ne-beg (org-back-over-empty-lines))
8388 (setq beg (point)))
8389 (save-match-data
8390 (save-excursion (outline-end-of-heading)
8391 (setq folded (org-invisible-p)))
8392 (progn (org-end-of-subtree nil t)
8393 (unless (eobp) (backward-char))))
8394 (outline-next-heading)
8395 (setq ne-end (org-back-over-empty-lines))
8396 (setq end (point))
8397 (goto-char beg0)
8398 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8399 ;; include less whitespace
8400 (save-excursion
8401 (goto-char beg)
8402 (forward-line (- ne-beg ne-end))
8403 (setq beg (point))))
8404 ;; Find insertion point, with error handling
8405 (while (> cnt 0)
8406 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8407 (progn (goto-char beg0)
8408 (user-error "Cannot move past superior level or buffer limit")))
8409 (setq cnt (1- cnt)))
8410 (when (> arg 0)
8411 ;; Moving forward - still need to move over subtree
8412 (org-end-of-subtree t t)
8413 (save-excursion
8414 (org-back-over-empty-lines)
8415 (or (bolp) (newline))))
8416 (setq ne-ins (org-back-over-empty-lines))
8417 (move-marker ins-point (point))
8418 (setq txt (buffer-substring beg end))
8419 (org-save-markers-in-region beg end)
8420 (delete-region beg end)
8421 (org-remove-empty-overlays-at beg)
8422 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8423 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8424 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8425 (let ((bbb (point)))
8426 (insert-before-markers txt)
8427 (org-reinstall-markers-in-region bbb)
8428 (move-marker ins-point bbb))
8429 (or (bolp) (insert "\n"))
8430 (setq ins-end (point))
8431 (goto-char ins-point)
8432 (org-skip-whitespace)
8433 (when (and (< arg 0)
8434 (org-first-sibling-p)
8435 (> ne-ins ne-beg))
8436 ;; Move whitespace back to beginning
8437 (save-excursion
8438 (goto-char ins-end)
8439 (let ((kill-whole-line t))
8440 (kill-line (- ne-ins ne-beg)) (point)))
8441 (insert (make-string (- ne-ins ne-beg) ?\n)))
8442 (move-marker ins-point nil)
8443 (if folded
8444 (outline-hide-subtree)
8445 (org-show-entry)
8446 (org-show-children)
8447 (org-cycle-hide-drawers 'children))
8448 (org-clean-visibility-after-subtree-move)
8449 ;; move back to the initial column we were at
8450 (move-to-column col)))
8452 (defvar org-subtree-clip ""
8453 "Clipboard for cut and paste of subtrees.
8454 This is actually only a copy of the kill, because we use the normal kill
8455 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8457 (defvar org-subtree-clip-folded nil
8458 "Was the last copied subtree folded?
8459 This is used to fold the tree back after pasting.")
8461 (defun org-cut-subtree (&optional n)
8462 "Cut the current subtree into the clipboard.
8463 With prefix arg N, cut this many sequential subtrees.
8464 This is a short-hand for marking the subtree and then cutting it."
8465 (interactive "p")
8466 (org-copy-subtree n 'cut))
8468 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8469 "Copy the current subtree it in the clipboard.
8470 With prefix arg N, copy this many sequential subtrees.
8471 This is a short-hand for marking the subtree and then copying it.
8472 If CUT is non-nil, actually cut the subtree.
8473 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8474 of some markers in the region, even if CUT is non-nil. This is
8475 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8476 (interactive "p")
8477 (let (beg end folded (beg0 (point)))
8478 (if (called-interactively-p 'any)
8479 (org-back-to-heading nil) ; take what looks like a subtree
8480 (org-back-to-heading t)) ; take what is really there
8481 (setq beg (point))
8482 (skip-chars-forward " \t\r\n")
8483 (save-match-data
8484 (if nosubtrees
8485 (outline-next-heading)
8486 (save-excursion (outline-end-of-heading)
8487 (setq folded (org-invisible-p)))
8488 (ignore-errors (org-forward-heading-same-level (1- n) t))
8489 (org-end-of-subtree t t)))
8490 ;; Include the end of an inlinetask
8491 (when (and (featurep 'org-inlinetask)
8492 (looking-at-p (concat (org-inlinetask-outline-regexp)
8493 "END[ \t]*$")))
8494 (end-of-line))
8495 (setq end (point))
8496 (goto-char beg0)
8497 (when (> end beg)
8498 (setq org-subtree-clip-folded folded)
8499 (when (or cut force-store-markers)
8500 (org-save-markers-in-region beg end))
8501 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8502 (setq org-subtree-clip (current-kill 0))
8503 (message "%s: Subtree(s) with %d characters"
8504 (if cut "Cut" "Copied")
8505 (length org-subtree-clip)))))
8507 (defun org-paste-subtree (&optional level tree for-yank remove)
8508 "Paste the clipboard as a subtree, with modification of headline level.
8509 The entire subtree is promoted or demoted in order to match a new headline
8510 level.
8512 If the cursor is at the beginning of a headline, the same level as
8513 that headline is used to paste the tree.
8515 If not, the new level is derived from the *visible* headings
8516 before and after the insertion point, and taken to be the inferior headline
8517 level of the two. So if the previous visible heading is level 3 and the
8518 next is level 4 (or vice versa), level 4 will be used for insertion.
8519 This makes sure that the subtree remains an independent subtree and does
8520 not swallow low level entries.
8522 You can also force a different level, either by using a numeric prefix
8523 argument, or by inserting the heading marker by hand. For example, if the
8524 cursor is after \"*****\", then the tree will be shifted to level 5.
8526 If optional TREE is given, use this text instead of the kill ring.
8528 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8529 move back over whitespace before inserting, and move point to the end of
8530 the inserted text when done.
8532 When REMOVE is non-nil, remove the subtree from the clipboard."
8533 (interactive "P")
8534 (setq tree (or tree (and kill-ring (current-kill 0))))
8535 (unless (org-kill-is-subtree-p tree)
8536 (user-error "%s"
8537 (substitute-command-keys
8538 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8539 (org-with-limited-levels
8540 (let* ((visp (not (org-invisible-p)))
8541 (txt tree)
8542 (^re_ "\\(\\*+\\)[ \t]*")
8543 (old-level (if (string-match org-outline-regexp-bol txt)
8544 (- (match-end 0) (match-beginning 0) 1)
8545 -1))
8546 (force-level (cond (level (prefix-numeric-value level))
8547 ((and (looking-at "[ \t]*$")
8548 (string-match
8549 "^\\*+$" (buffer-substring
8550 (point-at-bol) (point))))
8551 (- (match-end 0) (match-beginning 0)))
8552 ((and (bolp)
8553 (looking-at org-outline-regexp))
8554 (- (match-end 0) (point) 1))))
8555 (previous-level (save-excursion
8556 (condition-case nil
8557 (progn
8558 (outline-previous-visible-heading 1)
8559 (if (looking-at ^re_)
8560 (- (match-end 0) (match-beginning 0) 1)
8562 (error 1))))
8563 (next-level (save-excursion
8564 (condition-case nil
8565 (progn
8566 (or (looking-at org-outline-regexp)
8567 (outline-next-visible-heading 1))
8568 (if (looking-at ^re_)
8569 (- (match-end 0) (match-beginning 0) 1)
8571 (error 1))))
8572 (new-level (or force-level (max previous-level next-level)))
8573 (shift (if (or (= old-level -1)
8574 (= new-level -1)
8575 (= old-level new-level))
8577 (- new-level old-level)))
8578 (delta (if (> shift 0) -1 1))
8579 (func (if (> shift 0) 'org-demote 'org-promote))
8580 (org-odd-levels-only nil)
8581 beg end newend)
8582 ;; Remove the forced level indicator
8583 (when force-level
8584 (delete-region (point-at-bol) (point)))
8585 ;; Paste
8586 (beginning-of-line (if (bolp) 1 2))
8587 (setq beg (point))
8588 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8589 (insert-before-markers txt)
8590 (unless (string-suffix-p "\n" txt) (insert "\n"))
8591 (setq newend (point))
8592 (org-reinstall-markers-in-region beg)
8593 (setq end (point))
8594 (goto-char beg)
8595 (skip-chars-forward " \t\n\r")
8596 (setq beg (point))
8597 (when (and (org-invisible-p) visp)
8598 (save-excursion (outline-show-heading)))
8599 ;; Shift if necessary
8600 (unless (= shift 0)
8601 (save-restriction
8602 (narrow-to-region beg end)
8603 (while (not (= shift 0))
8604 (org-map-region func (point-min) (point-max))
8605 (setq shift (+ delta shift)))
8606 (goto-char (point-min))
8607 (setq newend (point-max))))
8608 (when (or (called-interactively-p 'interactive) for-yank)
8609 (message "Clipboard pasted as level %d subtree" new-level))
8610 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8611 kill-ring
8612 (eq org-subtree-clip (current-kill 0))
8613 org-subtree-clip-folded)
8614 ;; The tree was folded before it was killed/copied
8615 (outline-hide-subtree))
8616 (and for-yank (goto-char newend))
8617 (and remove (setq kill-ring (cdr kill-ring))))))
8619 (defun org-kill-is-subtree-p (&optional txt)
8620 "Check if the current kill is an outline subtree, or a set of trees.
8621 Returns nil if kill does not start with a headline, or if the first
8622 headline level is not the largest headline level in the tree.
8623 So this will actually accept several entries of equal levels as well,
8624 which is OK for `org-paste-subtree'.
8625 If optional TXT is given, check this string instead of the current kill."
8626 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8627 (re (org-get-limited-outline-regexp))
8628 (^re (concat "^" re))
8629 (start-level (and kill
8630 (string-match
8631 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8632 kill)
8633 (- (match-end 2) (match-beginning 2) 1)))
8634 (start (1+ (or (match-beginning 2) -1))))
8635 (if (not start-level)
8636 (progn
8637 nil) ;; does not even start with a heading
8638 (catch 'exit
8639 (while (setq start (string-match ^re kill (1+ start)))
8640 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8641 (throw 'exit nil)))
8642 t))))
8644 (defvar org-markers-to-move nil
8645 "Markers that should be moved with a cut-and-paste operation.
8646 Those markers are stored together with their positions relative to
8647 the start of the region.")
8649 (defun org-save-markers-in-region (beg end)
8650 "Check markers in region.
8651 If these markers are between BEG and END, record their position relative
8652 to BEG, so that after moving the block of text, we can put the markers back
8653 into place.
8654 This function gets called just before an entry or tree gets cut from the
8655 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8656 called immediately, to move the markers with the entries."
8657 (setq org-markers-to-move nil)
8658 (when (featurep 'org-clock)
8659 (org-clock-save-markers-for-cut-and-paste beg end))
8660 (when (featurep 'org-agenda)
8661 (org-agenda-save-markers-for-cut-and-paste beg end)))
8663 (defun org-check-and-save-marker (marker beg end)
8664 "Check if MARKER is between BEG and END.
8665 If yes, remember the marker and the distance to BEG."
8666 (when (and (marker-buffer marker)
8667 (equal (marker-buffer marker) (current-buffer))
8668 (>= marker beg) (< marker end))
8669 (push (cons marker (- marker beg)) org-markers-to-move)))
8671 (defun org-reinstall-markers-in-region (beg)
8672 "Move all remembered markers to their position relative to BEG."
8673 (dolist (x org-markers-to-move)
8674 (move-marker (car x) (+ beg (cdr x))))
8675 (setq org-markers-to-move nil))
8677 (defun org-narrow-to-subtree ()
8678 "Narrow buffer to the current subtree."
8679 (interactive)
8680 (save-excursion
8681 (save-match-data
8682 (org-with-limited-levels
8683 (narrow-to-region
8684 (progn (org-back-to-heading t) (point))
8685 (progn (org-end-of-subtree t t)
8686 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8687 (point)))))))
8689 (defun org-narrow-to-block ()
8690 "Narrow buffer to the current block."
8691 (interactive)
8692 (let* ((case-fold-search t)
8693 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8694 "^[ \t]*#\\+end_.*")))
8695 (if blockp
8696 (narrow-to-region (car blockp) (cdr blockp))
8697 (user-error "Not in a block"))))
8699 (defun org-clone-subtree-with-time-shift (n &optional shift)
8700 "Clone the task (subtree) at point N times.
8701 The clones will be inserted as siblings.
8703 In interactive use, the user will be prompted for the number of
8704 clones to be produced. If the entry has a timestamp, the user
8705 will also be prompted for a time shift, which may be a repeater
8706 as used in time stamps, for example `+3d'. To disable this,
8707 you can call the function with a universal prefix argument.
8709 When a valid repeater is given and the entry contains any time
8710 stamps, the clones will become a sequence in time, with time
8711 stamps in the subtree shifted for each clone produced. If SHIFT
8712 is nil or the empty string, time stamps will be left alone. The
8713 ID property of the original subtree is removed.
8715 In each clone, all the CLOCK entries will be removed. This
8716 prevents Org from considering that the clocked times overlap.
8718 If the original subtree did contain time stamps with a repeater,
8719 the following will happen:
8720 - the repeater will be removed in each clone
8721 - an additional clone will be produced, with the current, unshifted
8722 date(s) in the entry.
8723 - the original entry will be placed *after* all the clones, with
8724 repeater intact.
8725 - the start days in the repeater in the original entry will be shifted
8726 to past the last clone.
8727 In this way you can spell out a number of instances of a repeating task,
8728 and still retain the repeater to cover future instances of the task.
8730 As described above, N+1 clones are produced when the original
8731 subtree has a repeater. Setting N to 0, then, can be used to
8732 remove the repeater from a subtree and create a shifted clone
8733 with the original repeater."
8734 (interactive "nNumber of clones to produce: ")
8735 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8736 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8737 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8738 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8739 (shift
8740 (or shift
8741 (if (and (not (equal current-prefix-arg '(4)))
8742 (save-excursion
8743 (goto-char beg)
8744 (re-search-forward org-ts-regexp-both end-of-tree t)))
8745 (read-from-minibuffer
8746 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8747 ""))) ;No time shift
8748 (doshift
8749 (and (org-string-nw-p shift)
8750 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8751 shift)
8752 (user-error "Invalid shift specification %s" shift)))))
8753 (goto-char end-of-tree)
8754 (unless (bolp) (insert "\n"))
8755 (let* ((end (point))
8756 (template (buffer-substring beg end))
8757 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8758 (shift-what (pcase (and doshift (match-string 2 shift))
8759 (`nil nil)
8760 ("d" 'day)
8761 ("w" (setq shift-n (* 7 shift-n)) 'day)
8762 ("m" 'month)
8763 ("y" 'year)
8764 (_ (error "Unsupported time unit"))))
8765 (nmin 1)
8766 (nmax n)
8767 (n-no-remove -1)
8768 (idprop (org-entry-get nil "ID")))
8769 (when (and doshift
8770 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8771 template))
8772 (delete-region beg end)
8773 (setq end beg)
8774 (setq nmin 0)
8775 (setq nmax (1+ nmax))
8776 (setq n-no-remove nmax))
8777 (goto-char end)
8778 (cl-loop for n from nmin to nmax do
8779 (insert
8780 ;; Prepare clone.
8781 (with-temp-buffer
8782 (insert template)
8783 (org-mode)
8784 (goto-char (point-min))
8785 (org-show-subtree)
8786 (and idprop (if org-clone-delete-id
8787 (org-entry-delete nil "ID")
8788 (org-id-get-create t)))
8789 (unless (= n 0)
8790 (while (re-search-forward org-clock-line-re nil t)
8791 (delete-region (line-beginning-position)
8792 (line-beginning-position 2)))
8793 (goto-char (point-min))
8794 (while (re-search-forward org-drawer-regexp nil t)
8795 (org-remove-empty-drawer-at (point))))
8796 (goto-char (point-min))
8797 (when doshift
8798 (while (re-search-forward org-ts-regexp-both nil t)
8799 (org-timestamp-change (* n shift-n) shift-what))
8800 (unless (= n n-no-remove)
8801 (goto-char (point-min))
8802 (while (re-search-forward org-ts-regexp nil t)
8803 (save-excursion
8804 (goto-char (match-beginning 0))
8805 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8806 (delete-region (match-beginning 1) (match-end 1)))))))
8807 (buffer-string)))))
8808 (goto-char beg)))
8810 ;;; Outline Sorting
8812 (defun org-sort (&optional with-case)
8813 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8814 Optional argument WITH-CASE means sort case-sensitively."
8815 (interactive "P")
8816 (org-call-with-arg
8817 (cond ((org-at-table-p) #'org-table-sort-lines)
8818 ((org-at-item-p) #'org-sort-list)
8819 (t #'org-sort-entries))
8820 with-case))
8822 (defun org-sort-remove-invisible (s)
8823 "Remove invisible part of links and emphasis markers from string S."
8824 (remove-text-properties 0 (length s) org-rm-props s)
8825 (replace-regexp-in-string
8826 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8827 (replace-regexp-in-string
8828 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8829 (org-link-display-format s)
8830 t t) t t))
8832 (defvar org-priority-regexp) ; defined later in the file
8834 (defvar org-after-sorting-entries-or-items-hook nil
8835 "Hook that is run after a bunch of entries or items have been sorted.
8836 When children are sorted, the cursor is in the parent line when this
8837 hook gets called. When a region or a plain list is sorted, the cursor
8838 will be in the first entry of the sorted region/list.")
8840 (defun org-sort-entries
8841 (&optional with-case sorting-type getkey-func compare-func property
8842 interactive?)
8843 "Sort entries on a certain level of an outline tree.
8844 If there is an active region, the entries in the region are sorted.
8845 Else, if the cursor is before the first entry, sort the top-level items.
8846 Else, the children of the entry at point are sorted.
8848 Sorting can be alphabetically, numerically, by date/time as given by
8849 a time stamp, by a property, by priority order, or by a custom function.
8851 The command prompts for the sorting type unless it has been given to the
8852 function through the SORTING-TYPE argument, which needs to be a character,
8853 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8854 the precise meaning of each character:
8856 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8857 c By creation time, which is assumed to be the first inactive time stamp
8858 at the beginning of a line.
8859 d By deadline date/time.
8860 k By clocking time.
8861 n Numerically, by converting the beginning of the entry/item to a number.
8862 o By order of TODO keywords.
8863 p By priority according to the cookie.
8864 r By the value of a property.
8865 s By scheduled date/time.
8866 t By date/time, either the first active time stamp in the entry, or, if
8867 none exist, by the first inactive one.
8869 Capital letters will reverse the sort order.
8871 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8872 called with point at the beginning of the record. It must return a
8873 value that is compatible with COMPARE-FUNC, the function used to
8874 compare entries.
8876 Comparing entries ignores case by default. However, with an optional argument
8877 WITH-CASE, the sorting considers case as well.
8879 Sorting is done against the visible part of the headlines, it ignores hidden
8880 links.
8882 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8884 A non-nil value for INTERACTIVE? is used to signal that this
8885 function is being called interactively."
8886 (interactive (list current-prefix-arg nil nil nil nil t))
8887 (let ((case-func (if with-case 'identity 'downcase))
8888 (cmstr
8889 ;; The clock marker is lost when using `sort-subr', let's
8890 ;; store the clocking string.
8891 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8892 (save-excursion
8893 (goto-char org-clock-marker)
8894 (buffer-substring-no-properties (line-beginning-position)
8895 (point)))))
8896 start beg end stars re re2
8897 txt what tmp)
8898 ;; Find beginning and end of region to sort
8899 (cond
8900 ((org-region-active-p)
8901 ;; we will sort the region
8902 (setq end (region-end)
8903 what "region")
8904 (goto-char (region-beginning))
8905 (unless (org-at-heading-p) (outline-next-heading))
8906 (setq start (point)))
8907 ((or (org-at-heading-p)
8908 (ignore-errors (progn (org-back-to-heading) t)))
8909 ;; we will sort the children of the current headline
8910 (org-back-to-heading)
8911 (setq start (point)
8912 end (progn (org-end-of-subtree t t)
8913 (or (bolp) (insert "\n"))
8914 (when (>= (org-back-over-empty-lines) 1)
8915 (forward-line 1))
8916 (point))
8917 what "children")
8918 (goto-char start)
8919 (outline-show-subtree)
8920 (outline-next-heading))
8922 ;; we will sort the top-level entries in this file
8923 (goto-char (point-min))
8924 (or (org-at-heading-p) (outline-next-heading))
8925 (setq start (point))
8926 (goto-char (point-max))
8927 (beginning-of-line 1)
8928 (when (looking-at ".*?\\S-")
8929 ;; File ends in a non-white line
8930 (end-of-line 1)
8931 (insert "\n"))
8932 (setq end (point-max))
8933 (setq what "top-level")
8934 (goto-char start)
8935 (outline-show-all)))
8937 (setq beg (point))
8938 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8940 (looking-at "\\(\\*+\\)")
8941 (setq stars (match-string 1)
8942 re (concat "^" (regexp-quote stars) " +")
8943 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8944 txt (buffer-substring beg end))
8945 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8946 (when (and (not (equal stars "*")) (string-match re2 txt))
8947 (user-error "Region to sort contains a level above the first entry"))
8949 (unless sorting-type
8950 (message
8951 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8952 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8953 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8954 what)
8955 (setq sorting-type (read-char-exclusive)))
8957 (unless getkey-func
8958 (and (= (downcase sorting-type) ?f)
8959 (setq getkey-func
8960 (or (and interactive?
8961 (org-read-function
8962 "Function for extracting keys: "))
8963 (error "Missing key extractor")))))
8965 (and (= (downcase sorting-type) ?r)
8966 (not property)
8967 (setq property
8968 (completing-read "Property: "
8969 (mapcar #'list (org-buffer-property-keys t))
8970 nil t)))
8972 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8973 (message "Sorting entries...")
8975 (save-restriction
8976 (narrow-to-region start end)
8977 (let ((dcst (downcase sorting-type))
8978 (case-fold-search nil)
8979 (now (current-time)))
8980 (sort-subr
8981 (/= dcst sorting-type)
8982 ;; This function moves to the beginning character of the "record" to
8983 ;; be sorted.
8984 (lambda nil
8985 (if (re-search-forward re nil t)
8986 (goto-char (match-beginning 0))
8987 (goto-char (point-max))))
8988 ;; This function moves to the last character of the "record" being
8989 ;; sorted.
8990 (lambda nil
8991 (save-match-data
8992 (condition-case nil
8993 (outline-forward-same-level 1)
8994 (error
8995 (goto-char (point-max))))))
8996 ;; This function returns the value that gets sorted against.
8997 (lambda nil
8998 (cond
8999 ((= dcst ?n)
9000 (if (looking-at org-complex-heading-regexp)
9001 (string-to-number (org-sort-remove-invisible (match-string 4)))
9002 nil))
9003 ((= dcst ?a)
9004 (if (looking-at org-complex-heading-regexp)
9005 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9006 nil))
9007 ((= dcst ?k)
9008 (or (get-text-property (point) :org-clock-minutes) 0))
9009 ((= dcst ?t)
9010 (let ((end (save-excursion (outline-next-heading) (point))))
9011 (if (or (re-search-forward org-ts-regexp end t)
9012 (re-search-forward org-ts-regexp-both end t))
9013 (org-time-string-to-seconds (match-string 0))
9014 (float-time now))))
9015 ((= dcst ?c)
9016 (let ((end (save-excursion (outline-next-heading) (point))))
9017 (if (re-search-forward
9018 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9019 end t)
9020 (org-time-string-to-seconds (match-string 0))
9021 (float-time now))))
9022 ((= dcst ?s)
9023 (let ((end (save-excursion (outline-next-heading) (point))))
9024 (if (re-search-forward org-scheduled-time-regexp end t)
9025 (org-time-string-to-seconds (match-string 1))
9026 (float-time now))))
9027 ((= dcst ?d)
9028 (let ((end (save-excursion (outline-next-heading) (point))))
9029 (if (re-search-forward org-deadline-time-regexp end t)
9030 (org-time-string-to-seconds (match-string 1))
9031 (float-time now))))
9032 ((= dcst ?p)
9033 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9034 (string-to-char (match-string 2))
9035 org-default-priority))
9036 ((= dcst ?r)
9037 (or (org-entry-get nil property) ""))
9038 ((= dcst ?o)
9039 (when (looking-at org-complex-heading-regexp)
9040 (let* ((m (match-string 2))
9041 (s (if (member m org-done-keywords) '- '+)))
9042 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9043 ((= dcst ?f)
9044 (if getkey-func
9045 (progn
9046 (setq tmp (funcall getkey-func))
9047 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9048 tmp)
9049 (error "Invalid key function `%s'" getkey-func)))
9050 (t (error "Invalid sorting type `%c'" sorting-type))))
9052 (cond
9053 ((= dcst ?a) 'string<)
9054 ((= dcst ?f)
9055 (or compare-func
9056 (and interactive?
9057 (org-read-function
9058 (concat "Function for comparing keys "
9059 "(empty for default `sort-subr' predicate): ")
9060 'allow-empty))))
9061 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9062 (run-hooks 'org-after-sorting-entries-or-items-hook)
9063 ;; Reset the clock marker if needed
9064 (when cmstr
9065 (save-excursion
9066 (goto-char start)
9067 (search-forward cmstr nil t)
9068 (move-marker org-clock-marker (point))))
9069 (message "Sorting entries...done")))
9071 ;;; The orgstruct minor mode
9073 ;; Define a minor mode which can be used in other modes in order to
9074 ;; integrate the Org mode structure editing commands.
9076 ;; This is really a hack, because the Org mode structure commands use
9077 ;; keys which normally belong to the major mode. Here is how it
9078 ;; works: The minor mode defines all the keys necessary to operate the
9079 ;; structure commands, but wraps the commands into a function which
9080 ;; tests if the cursor is currently at a headline or a plain list
9081 ;; item. If that is the case, the structure command is used,
9082 ;; temporarily setting many Org mode variables like regular
9083 ;; expressions for filling etc. However, when any of those keys is
9084 ;; used at a different location, function uses `key-binding' to look
9085 ;; up if the key has an associated command in another currently active
9086 ;; keymap (minor modes, major mode, global), and executes that
9087 ;; command. There might be problems if any of the keys is otherwise
9088 ;; used as a prefix key.
9090 (defcustom orgstruct-heading-prefix-regexp ""
9091 "Regexp that matches the custom prefix of Org headlines in
9092 orgstruct(++)-mode."
9093 :group 'org
9094 :version "24.4"
9095 :package-version '(Org . "8.3")
9096 :type 'regexp)
9097 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9099 (defcustom orgstruct-setup-hook nil
9100 "Hook run after orgstruct-mode-map is filled."
9101 :group 'org
9102 :version "24.4"
9103 :package-version '(Org . "8.0")
9104 :type 'hook)
9106 (defvar orgstruct-initialized nil)
9108 (defvar org-local-vars nil
9109 "List of local variables, for use by `orgstruct-mode'.")
9111 ;;;###autoload
9112 (define-minor-mode orgstruct-mode
9113 "Toggle the minor mode `orgstruct-mode'.
9114 This mode is for using Org mode structure commands in other
9115 modes. The following keys behave as if Org mode were active, if
9116 the cursor is on a headline, or on a plain list item (both as
9117 defined by Org mode)."
9118 nil " OrgStruct" (make-sparse-keymap)
9119 (funcall (if orgstruct-mode
9120 'add-to-invisibility-spec
9121 'remove-from-invisibility-spec)
9122 '(outline . t))
9123 (when orgstruct-mode
9124 (org-load-modules-maybe)
9125 (unless orgstruct-initialized
9126 (orgstruct-setup)
9127 (setq orgstruct-initialized t))))
9129 ;;;###autoload
9130 (defun turn-on-orgstruct ()
9131 "Unconditionally turn on `orgstruct-mode'."
9132 (orgstruct-mode 1))
9134 (defvar-local orgstruct-is-++ nil
9135 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9136 (defvar-local org-fb-vars nil)
9137 (defun orgstruct++-mode (&optional arg)
9138 "Toggle `orgstruct-mode', the enhanced version of it.
9139 In addition to setting orgstruct-mode, this also exports all
9140 indentation and autofilling variables from Org mode into the
9141 buffer. It will also recognize item context in multiline items."
9142 (interactive "P")
9143 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9144 (if (< arg 1)
9145 (progn (orgstruct-mode -1)
9146 (dolist (v org-fb-vars)
9147 (set (make-local-variable (car v))
9148 (if (eq (car-safe (cadr v)) 'quote)
9149 (cl-cadadr v)
9150 (nth 1 v)))))
9151 (orgstruct-mode 1)
9152 (setq org-fb-vars nil)
9153 (unless org-local-vars
9154 (setq org-local-vars (org-get-local-variables)))
9155 (let (var val)
9156 (dolist (x org-local-vars)
9157 (when (string-match
9158 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9159 \\|fill-prefix\\|indent-\\)"
9160 (symbol-name (car x)))
9161 (setq var (car x) val (nth 1 x))
9162 (push (list var `(quote ,(eval var))) org-fb-vars)
9163 (set (make-local-variable var)
9164 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9165 (setq-local orgstruct-is-++ t))))
9167 ;;;###autoload
9168 (defun turn-on-orgstruct++ ()
9169 "Unconditionally turn on `orgstruct++-mode'."
9170 (orgstruct++-mode 1))
9172 (defun orgstruct-error ()
9173 "Error when there is no default binding for a structure key."
9174 (interactive)
9175 (funcall (if (fboundp 'user-error)
9176 'user-error
9177 'error)
9178 "This key has no function outside structure elements"))
9180 (defun orgstruct-setup ()
9181 "Setup orgstruct keymap."
9182 (dolist (cell '((org-demote . t)
9183 (org-metaleft . t)
9184 (org-metaright . t)
9185 (org-promote . t)
9186 (org-shiftmetaleft . t)
9187 (org-shiftmetaright . t)
9188 org-backward-element
9189 org-backward-heading-same-level
9190 org-ctrl-c-ret
9191 org-ctrl-c-minus
9192 org-ctrl-c-star
9193 org-cycle
9194 org-force-cycle-archived
9195 org-forward-heading-same-level
9196 org-insert-heading
9197 org-insert-heading-respect-content
9198 org-kill-note-or-show-branches
9199 org-mark-subtree
9200 org-meta-return
9201 org-metadown
9202 org-metaup
9203 org-narrow-to-subtree
9204 org-promote-subtree
9205 org-reveal
9206 org-shiftdown
9207 org-shiftleft
9208 org-shiftmetadown
9209 org-shiftmetaup
9210 org-shiftright
9211 org-shifttab
9212 org-shifttab
9213 org-shiftup
9214 org-show-children
9215 org-show-subtree
9216 org-sort
9217 org-up-element
9218 outline-demote
9219 outline-next-visible-heading
9220 outline-previous-visible-heading
9221 outline-promote
9222 outline-up-heading))
9223 (let ((f (or (car-safe cell) cell))
9224 (disable-when-heading-prefix (cdr-safe cell)))
9225 (when (fboundp f)
9226 (let ((new-bindings))
9227 (dolist (binding (nconc (where-is-internal f org-mode-map)
9228 (where-is-internal f outline-mode-map)))
9229 (push binding new-bindings)
9230 ;; TODO use local-function-key-map
9231 (dolist (rep '(("<tab>" . "TAB")
9232 ("<return>" . "RET")
9233 ("<escape>" . "ESC")
9234 ("<delete>" . "DEL")))
9235 (setq binding (read-kbd-macro
9236 (let ((case-fold-search))
9237 (replace-regexp-in-string
9238 (regexp-quote (cdr rep))
9239 (car rep)
9240 (key-description binding)))))
9241 (cl-pushnew binding new-bindings :test 'equal)))
9242 (dolist (binding new-bindings)
9243 (let ((key (lookup-key orgstruct-mode-map binding)))
9244 (when (or (not key) (numberp key))
9245 (ignore-errors
9246 (org-defkey orgstruct-mode-map
9247 binding
9248 (orgstruct-make-binding
9249 f binding disable-when-heading-prefix))))))))))
9250 (run-hooks 'orgstruct-setup-hook))
9252 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9253 "Create a function for binding in the structure minor mode.
9254 FUN is the command to call inside a table. KEY is the key that
9255 should be checked in for a command to execute outside of tables.
9256 Non-nil `disable-when-heading-prefix' means to disable the command
9257 if `orgstruct-heading-prefix-regexp' is not empty."
9258 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9259 (let ((nname name)
9260 (i 0))
9261 (while (fboundp (intern nname))
9262 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9263 (setq name (intern nname)))
9264 (eval
9265 (let ((bindings '((org-heading-regexp
9266 (concat "^"
9267 orgstruct-heading-prefix-regexp
9268 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9269 (org-outline-regexp
9270 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9271 (org-outline-regexp-bol
9272 (concat "^" org-outline-regexp))
9273 (outline-regexp org-outline-regexp)
9274 (outline-heading-end-regexp "\n")
9275 (outline-level 'org-outline-level)
9276 (outline-heading-alist))))
9277 `(defun ,name (arg)
9278 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9279 "Outside of structure, run the binding of `"
9280 (key-description key) "'."
9281 (when disable-when-heading-prefix
9282 (concat
9283 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9284 "back to the default binding due to limitations of Org's implementation of\n"
9285 "`" (symbol-name fun) "'.")))
9286 (interactive "p")
9287 (let* ((disable
9288 ,(and disable-when-heading-prefix
9289 '(not (string= orgstruct-heading-prefix-regexp ""))))
9290 (fallback
9291 (or disable
9292 (not
9293 (let* ,bindings
9294 (org-context-p 'headline 'item
9295 ,(when (memq fun
9296 '(org-insert-heading
9297 org-insert-heading-respect-content
9298 org-meta-return))
9299 '(when orgstruct-is-++
9300 'item-body))))))))
9301 (if fallback
9302 (let* ((orgstruct-mode)
9303 (binding
9304 (let ((key ,key))
9305 (catch 'exit
9306 (dolist
9307 (rep
9308 '(nil
9309 ("<\\([^>]*\\)tab>" . "\\1TAB")
9310 ("<\\([^>]*\\)return>" . "\\1RET")
9311 ("<\\([^>]*\\)escape>" . "\\1ESC")
9312 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9313 nil)
9314 (when rep
9315 (setq key (read-kbd-macro
9316 (let ((case-fold-search))
9317 (replace-regexp-in-string
9318 (car rep)
9319 (cdr rep)
9320 (key-description key))))))
9321 (when (key-binding key)
9322 (throw 'exit (key-binding key))))))))
9323 (if (keymapp binding)
9324 (org-set-transient-map binding)
9325 (let ((func (or binding
9326 (unless disable
9327 'orgstruct-error))))
9328 (when func
9329 (call-interactively func)))))
9330 (org-run-like-in-org-mode
9331 (lambda ()
9332 (interactive)
9333 (let* ,bindings
9334 (call-interactively ',fun)))))))))
9335 name))
9337 (defun org-contextualize-keys (alist contexts)
9338 "Return valid elements in ALIST depending on CONTEXTS.
9340 `org-agenda-custom-commands' or `org-capture-templates' are the
9341 values used for ALIST, and `org-agenda-custom-commands-contexts'
9342 or `org-capture-templates-contexts' are the associated contexts
9343 definitions."
9344 (let ((contexts
9345 ;; normalize contexts
9346 (mapcar
9347 (lambda(c) (cond ((listp (cadr c))
9348 (list (car c) (car c) (nth 1 c)))
9349 ((string= "" (cadr c))
9350 (list (car c) (car c) (nth 2 c)))
9351 (t c)))
9352 contexts))
9353 (a alist) r s)
9354 ;; loop over all commands or templates
9355 (dolist (c a)
9356 (let (vrules repl)
9357 (cond
9358 ((not (assoc (car c) contexts))
9359 (push c r))
9360 ((and (assoc (car c) contexts)
9361 (setq vrules (org-contextualize-validate-key
9362 (car c) contexts)))
9363 (mapc (lambda (vr)
9364 (unless (equal (car vr) (cadr vr))
9365 (setq repl vr)))
9366 vrules)
9367 (if (not repl) (push c r)
9368 (push (cadr repl) s)
9369 (push
9370 (cons (car c)
9371 (cdr (or (assoc (cadr repl) alist)
9372 (error "Undefined key `%s' as contextual replacement for `%s'"
9373 (cadr repl) (car c)))))
9374 r))))))
9375 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9376 (delq
9378 (delete-dups
9379 (mapcar (lambda (x)
9380 (let ((tpl (car x)))
9381 (unless (delq
9383 (mapcar (lambda (y)
9384 (equal y tpl))
9386 x)))
9387 (reverse r))))))
9389 (defun org-contextualize-validate-key (key contexts)
9390 "Check CONTEXTS for agenda or capture KEY."
9391 (let (res)
9392 (dolist (r contexts)
9393 (dolist (rr (car (last r)))
9394 (when
9395 (and (equal key (car r))
9396 (if (functionp rr) (funcall rr)
9397 (or (and (eq (car rr) 'in-file)
9398 (buffer-file-name)
9399 (string-match (cdr rr) (buffer-file-name)))
9400 (and (eq (car rr) 'in-mode)
9401 (string-match (cdr rr) (symbol-name major-mode)))
9402 (and (eq (car rr) 'in-buffer)
9403 (string-match (cdr rr) (buffer-name)))
9404 (when (and (eq (car rr) 'not-in-file)
9405 (buffer-file-name))
9406 (not (string-match (cdr rr) (buffer-file-name))))
9407 (when (eq (car rr) 'not-in-mode)
9408 (not (string-match (cdr rr) (symbol-name major-mode))))
9409 (when (eq (car rr) 'not-in-buffer)
9410 (not (string-match (cdr rr) (buffer-name)))))))
9411 (push r res))))
9412 (delete-dups (delq nil res))))
9414 (defun org-context-p (&rest contexts)
9415 "Check if local context is any of CONTEXTS.
9416 Possible values in the list of contexts are `table', `headline', and `item'."
9417 (let ((pos (point)))
9418 (goto-char (point-at-bol))
9419 (prog1 (or (and (memq 'table contexts)
9420 (looking-at "[ \t]*|"))
9421 (and (memq 'headline contexts)
9422 (looking-at org-outline-regexp))
9423 (and (memq 'item contexts)
9424 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9425 (and (memq 'item-body contexts)
9426 (org-in-item-p)))
9427 (goto-char pos))))
9429 (defconst org-unique-local-variables
9430 '(org-element--cache
9431 org-element--cache-objects
9432 org-element--cache-sync-keys
9433 org-element--cache-sync-requests
9434 org-element--cache-sync-timer)
9435 "List of local variables that cannot be transferred to another buffer.")
9437 (defun org-get-local-variables ()
9438 "Return a list of all local variables in an Org mode buffer."
9439 (delq nil
9440 (mapcar
9441 (lambda (x)
9442 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9443 (name (car binding)))
9444 (and (not (get name 'org-state))
9445 (not (memq name org-unique-local-variables))
9446 (string-match-p
9447 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9448 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9449 (symbol-name name))
9450 binding)))
9451 (with-temp-buffer
9452 (org-mode)
9453 (buffer-local-variables)))))
9455 (defun org-clone-local-variables (from-buffer &optional regexp)
9456 "Clone local variables from FROM-BUFFER.
9457 Optional argument REGEXP selects variables to clone."
9458 (dolist (pair (buffer-local-variables from-buffer))
9459 (pcase pair
9460 (`(,name . ,value) ;ignore unbound variables
9461 (when (and (not (memq name org-unique-local-variables))
9462 (or (null regexp) (string-match-p regexp (symbol-name name))))
9463 (set (make-local-variable name) value))))))
9465 ;;;###autoload
9466 (defun org-run-like-in-org-mode (cmd)
9467 "Run a command, pretending that the current buffer is in Org mode.
9468 This will temporarily bind local variables that are typically bound in
9469 Org mode to the values they have in Org mode, and then interactively
9470 call CMD."
9471 (org-load-modules-maybe)
9472 (unless org-local-vars
9473 (setq org-local-vars (org-get-local-variables)))
9474 (let (binds)
9475 (dolist (var org-local-vars)
9476 (when (or (not (boundp (car var)))
9477 (eq (symbol-value (car var))
9478 (default-value (car var))))
9479 (push (list (car var) `(quote ,(cadr var))) binds)))
9480 (eval `(let ,binds
9481 (call-interactively (quote ,cmd))))))
9483 (defun org-get-category (&optional pos force-refresh)
9484 "Get the category applying to position POS."
9485 (save-match-data
9486 (when force-refresh (org-refresh-category-properties))
9487 (let ((pos (or pos (point))))
9488 (or (get-text-property pos 'org-category)
9489 (progn (org-refresh-category-properties)
9490 (get-text-property pos 'org-category))))))
9492 ;;; Refresh properties
9494 (defun org-refresh-properties (dprop tprop)
9495 "Refresh buffer text properties.
9496 DPROP is the drawer property and TPROP is either the
9497 corresponding text property to set, or an alist with each element
9498 being a text property (as a symbol) and a function to apply to
9499 the value of the drawer property."
9500 (let* ((case-fold-search t)
9501 (inhibit-read-only t)
9502 (inherit? (org-property-inherit-p dprop))
9503 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9504 (global (and inherit? (org--property-global-value dprop nil))))
9505 (org-with-silent-modifications
9506 (org-with-point-at 1
9507 ;; Set global values (e.g., values defined through
9508 ;; "#+PROPERTY:" keywords) to the whole buffer.
9509 (when global (put-text-property (point-min) (point-max) tprop global))
9510 ;; Set local values.
9511 (while (re-search-forward property-re nil t)
9512 (when (org-at-property-p)
9513 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9514 (outline-next-heading))))))
9516 (defun org-refresh-property (tprop p &optional inherit)
9517 "Refresh the buffer text property TPROP from the drawer property P.
9518 The refresh happens only for the current headline, or the whole
9519 sub-tree if optional argument INHERIT is non-nil."
9520 (unless (org-before-first-heading-p)
9521 (save-excursion
9522 (org-back-to-heading t)
9523 (let ((start (point))
9524 (end (save-excursion
9525 (if inherit (org-end-of-subtree t t)
9526 (or (outline-next-heading) (point-max))))))
9527 (if (symbolp tprop)
9528 ;; TPROP is a text property symbol.
9529 (put-text-property start end tprop p)
9530 ;; TPROP is an alist with (property . function) elements.
9531 (pcase-dolist (`(,prop . ,f) tprop)
9532 (put-text-property start end prop (funcall f p))))))))
9534 (defun org-refresh-category-properties ()
9535 "Refresh category text properties in the buffer."
9536 (let ((case-fold-search t)
9537 (inhibit-read-only t)
9538 (default-category
9539 (cond ((null org-category)
9540 (if buffer-file-name
9541 (file-name-sans-extension
9542 (file-name-nondirectory buffer-file-name))
9543 "???"))
9544 ((symbolp org-category) (symbol-name org-category))
9545 (t org-category))))
9546 (org-with-silent-modifications
9547 (org-with-wide-buffer
9548 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9549 ;; This is the default category for the buffer. If none is
9550 ;; found, fall-back to `org-category' or buffer file name.
9551 (put-text-property
9552 (point-min) (point-max)
9553 'org-category
9554 (catch 'buffer-category
9555 (goto-char (point-max))
9556 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9557 (let ((element (org-element-at-point)))
9558 (when (eq (org-element-type element) 'keyword)
9559 (throw 'buffer-category
9560 (org-element-property :value element)))))
9561 default-category))
9562 ;; Set sub-tree specific categories.
9563 (goto-char (point-min))
9564 (let ((regexp (org-re-property "CATEGORY")))
9565 (while (re-search-forward regexp nil t)
9566 (let ((value (match-string-no-properties 3)))
9567 (when (org-at-property-p)
9568 (put-text-property
9569 (save-excursion (org-back-to-heading t) (point))
9570 (save-excursion (org-end-of-subtree t t) (point))
9571 'org-category
9572 value)))))))))
9574 (defun org-refresh-stats-properties ()
9575 "Refresh stats text properties in the buffer."
9576 (org-with-silent-modifications
9577 (org-with-point-at 1
9578 (let ((regexp (concat org-outline-regexp-bol
9579 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9580 (while (re-search-forward regexp nil t)
9581 (let* ((numerator (string-to-number (match-string 1)))
9582 (denominator (and (match-end 2)
9583 (string-to-number (match-string 2))))
9584 (stats (cond ((not denominator) numerator) ;percent
9585 ((= denominator 0) 0)
9586 (t (/ (* numerator 100) denominator)))))
9587 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9588 'org-stats stats)))))))
9590 (defun org-refresh-effort-properties ()
9591 "Refresh effort properties"
9592 (org-refresh-properties
9593 org-effort-property
9594 '((effort . identity)
9595 (effort-minutes . org-duration-to-minutes))))
9597 ;;;; Link Stuff
9599 ;;; Link abbreviations
9601 (defun org-link-expand-abbrev (link)
9602 "Apply replacements as defined in `org-link-abbrev-alist'."
9603 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9604 (let* ((key (match-string 1 link))
9605 (as (or (assoc key org-link-abbrev-alist-local)
9606 (assoc key org-link-abbrev-alist)))
9607 (tag (and (match-end 2) (match-string 3 link)))
9608 rpl)
9609 (if (not as)
9610 link
9611 (setq rpl (cdr as))
9612 (cond
9613 ((symbolp rpl) (funcall rpl tag))
9614 ((string-match "%(\\([^)]+\\))" rpl)
9615 (replace-match
9616 (save-match-data
9617 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9618 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9619 ((string-match "%h" rpl)
9620 (replace-match (url-hexify-string (or tag "")) t t rpl))
9621 (t (concat rpl tag)))))
9622 link))
9624 ;;; Storing and inserting links
9626 (defvar org-insert-link-history nil
9627 "Minibuffer history for links inserted with `org-insert-link'.")
9629 (defvar org-stored-links nil
9630 "Contains the links stored with `org-store-link'.")
9632 (defvar org-store-link-plist nil
9633 "Plist with info about the most recently link created with `org-store-link'.")
9635 (defun org-store-link-functions ()
9636 "Return a list of functions that are called to create and store a link.
9637 The functions defined in the :store property of
9638 `org-link-parameters'.
9640 Each function will be called in turn until one returns a non-nil
9641 value. Each function should check if it is responsible for
9642 creating this link (for example by looking at the major mode).
9643 If not, it must exit and return nil. If yes, it should return
9644 a non-nil value after calling `org-store-link-props' with a list
9645 of properties and values. Special properties are:
9647 :type The link prefix, like \"http\". This must be given.
9648 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9649 This is obligatory as well.
9650 :description Optional default description for the second pair
9651 of brackets in an Org mode link. The user can still change
9652 this when inserting this link into an Org mode buffer.
9654 In addition to these, any additional properties can be specified
9655 and then used in capture templates."
9656 (cl-loop for link in org-link-parameters
9657 with store-func
9658 do (setq store-func (org-link-get-parameter (car link) :store))
9659 if store-func
9660 collect store-func))
9662 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9663 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9665 ;;;###autoload
9666 (defun org-store-link (arg)
9667 "Store an org-link to the current location.
9668 \\<org-mode-map>
9669 This link is added to `org-stored-links' and can later be inserted
9670 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9672 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9673 A single
9674 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9675 `org-gnus-prefer-web-links' for links to Usenet articles.
9677 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9678 skipping storing functions that are not
9679 part of Org core.
9681 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9682 prefix ARG forces storing a link for each line in the
9683 active region."
9684 (interactive "P")
9685 (org-load-modules-maybe)
9686 (if (and (equal arg '(64)) (org-region-active-p))
9687 (save-excursion
9688 (let ((end (region-end)))
9689 (goto-char (region-beginning))
9690 (set-mark (point))
9691 (while (< (point-at-eol) end)
9692 (move-end-of-line 1) (activate-mark)
9693 (let (current-prefix-arg)
9694 (call-interactively 'org-store-link))
9695 (move-beginning-of-line 2)
9696 (set-mark (point)))))
9697 (setq org-store-link-plist nil)
9698 (let (link cpltxt desc description search
9699 txt custom-id agenda-link sfuns sfunsn)
9700 (cond
9702 ;; Store a link using an external link type
9703 ((and (not (equal arg '(16)))
9704 (setq sfuns
9705 (delq
9706 nil (mapcar (lambda (f)
9707 (let (fs) (if (funcall f) (push f fs))))
9708 (org-store-link-functions)))
9709 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9710 (or (and (cdr sfuns)
9711 (funcall (intern
9712 (completing-read
9713 "Which function for creating the link? "
9714 sfunsn nil t (car sfunsn)))))
9715 (funcall (caar sfuns)))
9716 (setq link (plist-get org-store-link-plist :link)
9717 desc (or (plist-get org-store-link-plist
9718 :description)
9719 link))))
9721 ;; Store a link from a source code buffer.
9722 ((org-src-edit-buffer-p)
9723 (let ((coderef-format (org-src-coderef-format)))
9724 (cond ((save-excursion
9725 (beginning-of-line)
9726 (looking-at (org-src-coderef-regexp coderef-format)))
9727 (setq link (format "(%s)" (match-string-no-properties 3))))
9728 ((called-interactively-p 'any)
9729 (let ((label (read-string "Code line label: ")))
9730 (end-of-line)
9731 (setq link (format coderef-format label))
9732 (let ((gc (- 79 (length link))))
9733 (if (< (current-column) gc)
9734 (org-move-to-column gc t)
9735 (insert " ")))
9736 (insert link)
9737 (setq link (concat "(" label ")"))
9738 (setq desc nil)))
9739 (t (setq link nil)))))
9741 ;; We are in the agenda, link to referenced location
9742 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9743 (let ((m (or (get-text-property (point) 'org-hd-marker)
9744 (get-text-property (point) 'org-marker))))
9745 (when m
9746 (org-with-point-at m
9747 (setq agenda-link
9748 (if (called-interactively-p 'any)
9749 (call-interactively 'org-store-link)
9750 (org-store-link nil)))))))
9752 ((eq major-mode 'calendar-mode)
9753 (let ((cd (calendar-cursor-to-date)))
9754 (setq link
9755 (format-time-string
9756 (car org-time-stamp-formats)
9757 (apply 'encode-time
9758 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9759 nil nil nil))))
9760 (org-store-link-props :type "calendar" :date cd)))
9762 ((eq major-mode 'help-mode)
9763 (setq link (concat "help:" (save-excursion
9764 (goto-char (point-min))
9765 (looking-at "^[^ ]+")
9766 (match-string 0))))
9767 (org-store-link-props :type "help"))
9769 ((eq major-mode 'w3-mode)
9770 (setq cpltxt (if (and (buffer-name)
9771 (not (string-match "Untitled" (buffer-name))))
9772 (buffer-name)
9773 (url-view-url t))
9774 link (url-view-url t))
9775 (org-store-link-props :type "w3" :url (url-view-url t)))
9777 ((eq major-mode 'image-mode)
9778 (setq cpltxt (concat "file:"
9779 (abbreviate-file-name buffer-file-name))
9780 link cpltxt)
9781 (org-store-link-props :type "image" :file buffer-file-name))
9783 ;; In dired, store a link to the file of the current line
9784 ((derived-mode-p 'dired-mode)
9785 (let ((file (dired-get-filename nil t)))
9786 (setq file (if file
9787 (abbreviate-file-name
9788 (expand-file-name (dired-get-filename nil t)))
9789 ;; otherwise, no file so use current directory.
9790 default-directory))
9791 (setq cpltxt (concat "file:" file)
9792 link cpltxt)))
9794 ((setq search (run-hook-with-args-until-success
9795 'org-create-file-search-functions))
9796 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9797 "::" search))
9798 (setq cpltxt (or description link)))
9800 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9801 (org-with-limited-levels
9802 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9803 (cond
9804 ;; Store a link using the target at point
9805 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9806 (setq cpltxt
9807 (concat "file:"
9808 (abbreviate-file-name
9809 (buffer-file-name (buffer-base-buffer)))
9810 "::" (match-string 1))
9811 link cpltxt))
9812 ((and (featurep 'org-id)
9813 (or (eq org-id-link-to-org-use-id t)
9814 (and (called-interactively-p 'any)
9815 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9816 (and (eq org-id-link-to-org-use-id
9817 'create-if-interactive-and-no-custom-id)
9818 (not custom-id))))
9819 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9820 ;; Store a link using the ID at point
9821 (setq link (condition-case nil
9822 (prog1 (org-id-store-link)
9823 (setq desc (or (plist-get org-store-link-plist
9824 :description)
9825 "")))
9826 (error
9827 ;; Probably before first headline, link only to file
9828 (concat "file:"
9829 (abbreviate-file-name
9830 (buffer-file-name (buffer-base-buffer))))))))
9832 ;; Just link to current headline
9833 (setq cpltxt (concat "file:"
9834 (abbreviate-file-name
9835 (buffer-file-name (buffer-base-buffer)))))
9836 ;; Add a context search string
9837 (when (org-xor org-context-in-file-links
9838 (equal arg '(4)))
9839 (let* ((element (org-element-at-point))
9840 (name (org-element-property :name element)))
9841 (setq txt (cond
9842 ((org-at-heading-p) nil)
9843 (name)
9844 ((org-region-active-p)
9845 (buffer-substring (region-beginning) (region-end)))))
9846 (when (or (null txt) (string-match "\\S-" txt))
9847 (setq cpltxt
9848 (concat cpltxt "::"
9849 (condition-case nil
9850 (org-make-org-heading-search-string txt)
9851 (error "")))
9852 desc (or name
9853 (nth 4 (ignore-errors (org-heading-components)))
9854 "NONE")))))
9855 (when (string-match "::\\'" cpltxt)
9856 (setq cpltxt (substring cpltxt 0 -2)))
9857 (setq link cpltxt)))))
9859 ((buffer-file-name (buffer-base-buffer))
9860 ;; Just link to this file here.
9861 (setq cpltxt (concat "file:"
9862 (abbreviate-file-name
9863 (buffer-file-name (buffer-base-buffer)))))
9864 ;; Add a context string.
9865 (when (org-xor org-context-in-file-links
9866 (equal arg '(4)))
9867 (setq txt (if (org-region-active-p)
9868 (buffer-substring (region-beginning) (region-end))
9869 (buffer-substring (point-at-bol) (point-at-eol))))
9870 ;; Only use search option if there is some text.
9871 (when (string-match "\\S-" txt)
9872 (setq cpltxt
9873 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9874 desc "NONE")))
9875 (setq link cpltxt))
9877 ((called-interactively-p 'interactive)
9878 (user-error "No method for storing a link from this buffer"))
9880 (t (setq link nil)))
9882 ;; We're done setting link and desc, clean up
9883 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9884 (setq link (or link cpltxt)
9885 desc (or desc cpltxt))
9886 (cond ((not desc))
9887 ((equal desc "NONE") (setq desc nil))
9888 (t (setq desc
9889 (replace-regexp-in-string
9890 org-bracket-link-analytic-regexp
9891 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9892 desc))))
9893 ;; Return the link
9894 (if (not (and (or (called-interactively-p 'any)
9895 executing-kbd-macro)
9896 link))
9897 (or agenda-link (and link (org-make-link-string link desc)))
9898 (push (list link desc) org-stored-links)
9899 (message "Stored: %s" (or desc link))
9900 (when custom-id
9901 (setq link (concat "file:" (abbreviate-file-name
9902 (buffer-file-name)) "::#" custom-id))
9903 (push (list link desc) org-stored-links))
9904 (car org-stored-links)))))
9906 (defun org-store-link-props (&rest plist)
9907 "Store link properties, extract names, addresses and dates."
9908 (let ((x (plist-get plist :from)))
9909 (when x
9910 (let ((adr (mail-extract-address-components x)))
9911 (setq plist (plist-put plist :fromname (car adr)))
9912 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9913 (let ((x (plist-get plist :to)))
9914 (when x
9915 (let ((adr (mail-extract-address-components x)))
9916 (setq plist (plist-put plist :toname (car adr)))
9917 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9918 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9919 (when x
9920 (setq plist (plist-put plist :date-timestamp
9921 (format-time-string
9922 (org-time-stamp-format t) x)))
9923 (setq plist (plist-put plist :date-timestamp-inactive
9924 (format-time-string
9925 (org-time-stamp-format t t) x)))))
9926 (let ((from (plist-get plist :from))
9927 (to (plist-get plist :to)))
9928 (when (and from to org-from-is-user-regexp)
9929 (setq plist
9930 (plist-put plist :fromto
9931 (if (string-match org-from-is-user-regexp from)
9932 (concat "to %t")
9933 (concat "from %f"))))))
9934 (setq org-store-link-plist plist))
9936 (defun org-add-link-props (&rest plist)
9937 "Add these properties to the link property list."
9938 (let (key value)
9939 (while plist
9940 (setq key (pop plist) value (pop plist))
9941 (setq org-store-link-plist
9942 (plist-put org-store-link-plist key value)))))
9944 (defun org-email-link-description (&optional fmt)
9945 "Return the description part of an email link.
9946 This takes information from `org-store-link-plist' and formats it
9947 according to FMT (default from `org-email-link-description-format')."
9948 (setq fmt (or fmt org-email-link-description-format))
9949 (let* ((p org-store-link-plist)
9950 (to (plist-get p :toaddress))
9951 (from (plist-get p :fromaddress))
9952 (table
9953 (list
9954 (cons "%c" (plist-get p :fromto))
9955 (cons "%F" (plist-get p :from))
9956 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9957 (cons "%T" (plist-get p :to))
9958 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9959 (cons "%s" (plist-get p :subject))
9960 (cons "%d" (plist-get p :date))
9961 (cons "%m" (plist-get p :message-id)))))
9962 (when (string-match "%c" fmt)
9963 ;; Check if the user wrote this message
9964 (if (and org-from-is-user-regexp from to
9965 (save-match-data (string-match org-from-is-user-regexp from)))
9966 (setq fmt (replace-match "to %t" t t fmt))
9967 (setq fmt (replace-match "from %f" t t fmt))))
9968 (org-replace-escapes fmt table)))
9970 (defun org-make-org-heading-search-string (&optional string)
9971 "Make search string for the current headline or STRING."
9972 (let ((s (or string
9973 (and (derived-mode-p 'org-mode)
9974 (save-excursion
9975 (org-back-to-heading t)
9976 (org-element-property :raw-value (org-element-at-point))))))
9977 (lines org-context-in-file-links))
9978 (or string (setq s (concat "*" s))) ; Add * for headlines
9979 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9980 (when (and string (integerp lines) (> lines 0))
9981 (let ((slines (org-split-string s "\n")))
9982 (when (< lines (length slines))
9983 (setq s (mapconcat
9984 'identity
9985 (reverse (nthcdr (- (length slines) lines)
9986 (reverse slines))) "\n")))))
9987 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9989 (defun org-make-link-string (link &optional description)
9990 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9991 (unless (org-string-nw-p link) (error "Empty link"))
9992 (let ((uri (cond ((string-match org-link-types-re link)
9993 (concat (match-string 1 link)
9994 (org-link-escape (substring link (match-end 1)))))
9995 ;; For readability, url-encode internal links only
9996 ;; when absolutely needed (i.e, when they contain
9997 ;; square brackets). File links however, are
9998 ;; encoded since, e.g., spaces are significant.
9999 ((or (file-name-absolute-p link)
10000 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10001 (org-link-escape link))
10002 (t link)))
10003 (description
10004 (and (org-string-nw-p description)
10005 ;; Remove brackets from description, as they are fatal.
10006 (replace-regexp-in-string
10007 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10008 (org-trim description)))))
10009 (format "[[%s]%s]"
10011 (if description (format "[%s]" description) ""))))
10013 (defconst org-link-escape-chars
10014 ;;%20 %5B %5D %25
10015 '(?\s ?\[ ?\] ?%)
10016 "List of characters that should be escaped in a link when stored to Org.
10017 This is the list that is used for internal purposes.")
10019 (defun org-link-escape (text &optional table merge)
10020 "Return percent escaped representation of TEXT.
10021 TEXT is a string with the text to escape.
10022 Optional argument TABLE is a list with characters that should be
10023 escaped. When nil, `org-link-escape-chars' is used.
10024 If optional argument MERGE is set, merge TABLE into
10025 `org-link-escape-chars'."
10026 (let ((characters-to-encode
10027 (cond ((null table) org-link-escape-chars)
10028 (merge (append org-link-escape-chars table))
10029 (t table))))
10030 (mapconcat
10031 (lambda (c)
10032 (if (or (memq c characters-to-encode)
10033 (and org-url-hexify-p (or (< c 32) (> c 126))))
10034 (mapconcat (lambda (e) (format "%%%.2X" e))
10035 (or (encode-coding-char c 'utf-8)
10036 (error "Unable to percent escape character: %c" c))
10038 (char-to-string c)))
10039 text "")))
10041 (defun org-link-unescape (str)
10042 "Unhex hexified Unicode parts in string STR.
10043 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10044 reciprocal of `org-link-escape', which see."
10045 (if (org-string-nw-p str)
10046 (replace-regexp-in-string
10047 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10048 str))
10050 (defun org-link-unescape-compound (hex)
10051 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10052 Note: this function also decodes single byte encodings like
10053 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10054 (save-match-data
10055 (let* ((bytes (cdr (split-string hex "%")))
10056 (ret "")
10057 (eat 0)
10058 (sum 0))
10059 (while bytes
10060 (let* ((val (string-to-number (pop bytes) 16))
10061 (shift-xor
10062 (if (= 0 eat)
10063 (cond
10064 ((>= val 252) (cons 6 252))
10065 ((>= val 248) (cons 5 248))
10066 ((>= val 240) (cons 4 240))
10067 ((>= val 224) (cons 3 224))
10068 ((>= val 192) (cons 2 192))
10069 (t (cons 0 0)))
10070 (cons 6 128))))
10071 (when (>= val 192) (setq eat (car shift-xor)))
10072 (setq val (logxor val (cdr shift-xor)))
10073 (setq sum (+ (lsh sum (car shift-xor)) val))
10074 (when (> eat 0) (setq eat (- eat 1)))
10075 (cond
10076 ((= 0 eat) ;multi byte
10077 (setq ret (concat ret (char-to-string sum)))
10078 (setq sum 0))
10079 ((not bytes) ; single byte(s)
10080 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10081 ret)))
10083 (defun org-link-unescape-single-byte-sequence (hex)
10084 "Unhexify hex-encoded single byte character sequences."
10085 (mapconcat (lambda (byte)
10086 (char-to-string (string-to-number byte 16)))
10087 (cdr (split-string hex "%")) ""))
10089 (defun org-xor (a b)
10090 "Exclusive or."
10091 (if a (not b) b))
10093 (defun org-fixup-message-id-for-http (s)
10094 "Replace special characters in a message id, so it can be used in an http query."
10095 (when (string-match "%" s)
10096 (setq s (mapconcat (lambda (c)
10097 (if (eq c ?%)
10098 "%25"
10099 (char-to-string c)))
10100 s "")))
10101 (while (string-match "<" s)
10102 (setq s (replace-match "%3C" t t s)))
10103 (while (string-match ">" s)
10104 (setq s (replace-match "%3E" t t s)))
10105 (while (string-match "@" s)
10106 (setq s (replace-match "%40" t t s)))
10109 (defun org-link-prettify (link)
10110 "Return a human-readable representation of LINK.
10111 The car of LINK must be a raw link.
10112 The cdr of LINK must be either a link description or nil."
10113 (let ((desc (or (cadr link) "<no description>")))
10114 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10115 "<" (car link) ">")))
10117 ;;;###autoload
10118 (defun org-insert-link-global ()
10119 "Insert a link like Org mode does.
10120 This command can be called in any mode to insert a link in Org syntax."
10121 (interactive)
10122 (org-load-modules-maybe)
10123 (org-run-like-in-org-mode 'org-insert-link))
10125 (defun org-insert-all-links (arg &optional pre post)
10126 "Insert all links in `org-stored-links'.
10127 When a universal prefix, do not delete the links from `org-stored-links'.
10128 When `ARG' is a number, insert the last N link(s).
10129 `PRE' and `POST' are optional arguments to define a string to
10130 prepend or to append."
10131 (interactive "P")
10132 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10133 (links (copy-sequence org-stored-links))
10134 (pr (or pre "- "))
10135 (po (or post "\n"))
10136 (cnt 1) l)
10137 (if (null org-stored-links)
10138 (message "No link to insert")
10139 (while (and (or (listp arg) (>= arg cnt))
10140 (setq l (if (listp arg)
10141 (pop links)
10142 (pop org-stored-links))))
10143 (setq cnt (1+ cnt))
10144 (insert pr)
10145 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10146 (insert po)))))
10148 (defun org-insert-last-stored-link (arg)
10149 "Insert the last link stored in `org-stored-links'."
10150 (interactive "p")
10151 (org-insert-all-links arg "" "\n"))
10153 (defun org-link-fontify-links-to-this-file ()
10154 "Fontify links to the current file in `org-stored-links'."
10155 (let ((f (buffer-file-name)) a b)
10156 (setq a (mapcar (lambda(l)
10157 (let ((ll (car l)))
10158 (when (and (string-match "^file:\\(.+\\)::" ll)
10159 (equal f (expand-file-name (match-string 1 ll))))
10160 ll)))
10161 org-stored-links))
10162 (when (featurep 'org-id)
10163 (setq b (mapcar (lambda(l)
10164 (let ((ll (car l)))
10165 (when (and (string-match "^id:\\(.+\\)$" ll)
10166 (equal f (expand-file-name
10167 (or (org-id-find-id-file
10168 (match-string 1 ll)) ""))))
10169 ll)))
10170 org-stored-links)))
10171 (mapcar (lambda(l)
10172 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10173 (delq nil (append a b)))))
10175 (defvar org--links-history nil)
10176 (defun org-insert-link (&optional complete-file link-location default-description)
10177 "Insert a link. At the prompt, enter the link.
10179 Completion can be used to insert any of the link protocol prefixes in use.
10181 The history can be used to select a link previously stored with
10182 `org-store-link'. When the empty string is entered (i.e. if you just
10183 press `RET' at the prompt), the link defaults to the most recently
10184 stored link. As `SPC' triggers completion in the minibuffer, you need to
10185 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10187 You will also be prompted for a description, and if one is given, it will
10188 be displayed in the buffer instead of the link.
10190 If there is already a link at point, this command will allow you to edit
10191 link and description parts.
10193 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10194 file name can be
10195 selected using completion. The path to the file will be relative to the
10196 current directory if the file is in the current directory or a subdirectory.
10197 Otherwise, the link will be the absolute path as completed in the minibuffer
10198 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10199 option `org-link-file-path-type'.
10201 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10202 absolute path even if the file is in
10203 the current directory or below.
10205 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10206 prefix negates `org-keep-stored-link-after-insertion'.
10208 If `org-make-link-description-function' is non-nil, this function will be
10209 called with the link target, and the result will be the default
10210 link description.
10212 If the LINK-LOCATION parameter is non-nil, this value will be used as
10213 the link location instead of reading one interactively.
10215 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10216 as the default description."
10217 (interactive "P")
10218 (let* ((wcf (current-window-configuration))
10219 (origbuf (current-buffer))
10220 (region (when (org-region-active-p)
10221 (buffer-substring (region-beginning) (region-end))))
10222 (remove (and region (list (region-beginning) (region-end))))
10223 (desc region)
10224 (link link-location)
10225 (abbrevs org-link-abbrev-alist-local)
10226 entry all-prefixes auto-desc)
10227 (cond
10228 (link-location) ; specified by arg, just use it.
10229 ((org-in-regexp org-bracket-link-regexp 1)
10230 ;; We do have a link at point, and we are going to edit it.
10231 (setq remove (list (match-beginning 0) (match-end 0)))
10232 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10233 (setq link (read-string "Link: "
10234 (org-link-unescape
10235 (match-string-no-properties 1)))))
10236 ((or (org-in-regexp org-angle-link-re)
10237 (org-in-regexp org-plain-link-re))
10238 ;; Convert to bracket link
10239 (setq remove (list (match-beginning 0) (match-end 0))
10240 link (read-string "Link: "
10241 (org-unbracket-string "<" ">" (match-string 0)))))
10242 ((member complete-file '((4) (16)))
10243 ;; Completing read for file names.
10244 (setq link (org-file-complete-link complete-file)))
10246 ;; Read link, with completion for stored links.
10247 (org-link-fontify-links-to-this-file)
10248 (org-switch-to-buffer-other-window "*Org Links*")
10249 (with-current-buffer "*Org Links*"
10250 (erase-buffer)
10251 (insert "Insert a link.
10252 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10253 (when org-stored-links
10254 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10255 (insert (mapconcat 'org-link-prettify
10256 (reverse org-stored-links) "\n")))
10257 (goto-char (point-min)))
10258 (let ((cw (selected-window)))
10259 (select-window (get-buffer-window "*Org Links*" 'visible))
10260 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10261 (unless (pos-visible-in-window-p (point-max))
10262 (org-fit-window-to-buffer))
10263 (and (window-live-p cw) (select-window cw)))
10264 (setq all-prefixes (append (mapcar 'car abbrevs)
10265 (mapcar 'car org-link-abbrev-alist)
10266 (org-link-types)))
10267 (unwind-protect
10268 ;; Fake a link history, containing the stored links.
10269 (let ((org--links-history
10270 (append (mapcar #'car org-stored-links)
10271 org-insert-link-history)))
10272 (setq link
10273 (org-completing-read
10274 "Link: "
10275 (append
10276 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10277 (mapcar #'car org-stored-links))
10278 nil nil nil
10279 'org--links-history
10280 (caar org-stored-links)))
10281 (unless (org-string-nw-p link) (user-error "No link selected"))
10282 (dolist (l org-stored-links)
10283 (when (equal link (cadr l))
10284 (setq link (car l))
10285 (setq auto-desc t)))
10286 (when (or (member link all-prefixes)
10287 (and (equal ":" (substring link -1))
10288 (member (substring link 0 -1) all-prefixes)
10289 (setq link (substring link 0 -1))))
10290 (setq link (with-current-buffer origbuf
10291 (org-link-try-special-completion link)))))
10292 (set-window-configuration wcf)
10293 (kill-buffer "*Org Links*"))
10294 (setq entry (assoc link org-stored-links))
10295 (or entry (push link org-insert-link-history))
10296 (setq desc (or desc (nth 1 entry)))))
10298 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10299 (not org-keep-stored-link-after-insertion))
10300 (setq org-stored-links (delq (assoc link org-stored-links)
10301 org-stored-links)))
10303 (when (and (string-match org-plain-link-re link)
10304 (not (string-match org-ts-regexp link)))
10305 ;; URL-like link, normalize the use of angular brackets.
10306 (setq link (org-unbracket-string "<" ">" link)))
10308 ;; Check if we are linking to the current file with a search
10309 ;; option If yes, simplify the link by using only the search
10310 ;; option.
10311 (when (and buffer-file-name
10312 (let ((case-fold-search nil))
10313 (string-match "\\`file:\\(.+?\\)::" link)))
10314 (let ((path (match-string-no-properties 1 link))
10315 (search (substring-no-properties link (match-end 0))))
10316 (save-match-data
10317 (when (equal (file-truename buffer-file-name) (file-truename path))
10318 ;; We are linking to this same file, with a search option
10319 (setq link search)))))
10321 ;; Check if we can/should use a relative path. If yes, simplify the link
10322 (let ((case-fold-search nil))
10323 (when (string-match "\\`\\(file\\|docview\\):" link)
10324 (let* ((type (match-string-no-properties 0 link))
10325 (path (substring-no-properties link (match-end 0)))
10326 (origpath path))
10327 (cond
10328 ((or (eq org-link-file-path-type 'absolute)
10329 (equal complete-file '(16)))
10330 (setq path (abbreviate-file-name (expand-file-name path))))
10331 ((eq org-link-file-path-type 'noabbrev)
10332 (setq path (expand-file-name path)))
10333 ((eq org-link-file-path-type 'relative)
10334 (setq path (file-relative-name path)))
10336 (save-match-data
10337 (if (string-match (concat "^" (regexp-quote
10338 (expand-file-name
10339 (file-name-as-directory
10340 default-directory))))
10341 (expand-file-name path))
10342 ;; We are linking a file with relative path name.
10343 (setq path (substring (expand-file-name path)
10344 (match-end 0)))
10345 (setq path (abbreviate-file-name (expand-file-name path)))))))
10346 (setq link (concat type path))
10347 (when (equal desc origpath)
10348 (setq desc path)))))
10350 (if org-make-link-description-function
10351 (setq desc
10352 (or (condition-case nil
10353 (funcall org-make-link-description-function link desc)
10354 (error (progn (message "Can't get link description from `%s'"
10355 (symbol-name org-make-link-description-function))
10356 (sit-for 2) nil)))
10357 (read-string "Description: " default-description)))
10358 (if default-description (setq desc default-description)
10359 (setq desc (or (and auto-desc desc)
10360 (read-string "Description: " desc)))))
10362 (unless (string-match "\\S-" desc) (setq desc nil))
10363 (when remove (apply 'delete-region remove))
10364 (insert (org-make-link-string link desc))
10365 ;; Redisplay so as the new link has proper invisible characters.
10366 (sit-for 0)))
10368 (defun org-link-try-special-completion (type)
10369 "If there is completion support for link type TYPE, offer it."
10370 (let ((fun (org-link-get-parameter type :complete)))
10371 (if (functionp fun)
10372 (funcall fun)
10373 (read-string "Link (no completion support): " (concat type ":")))))
10375 (defun org-file-complete-link (&optional arg)
10376 "Create a file link using completion."
10377 (let ((file (read-file-name "File: "))
10378 (pwd (file-name-as-directory (expand-file-name ".")))
10379 (pwd1 (file-name-as-directory (abbreviate-file-name
10380 (expand-file-name ".")))))
10381 (cond ((equal arg '(16))
10382 (concat "file:"
10383 (abbreviate-file-name (expand-file-name file))))
10384 ((string-match
10385 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10386 (concat "file:" (match-string 1 file)))
10387 ((string-match
10388 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10389 (expand-file-name file))
10390 (concat "file:"
10391 (match-string 1 (expand-file-name file))))
10392 (t (concat "file:" file)))))
10394 (defun org-completing-read (&rest args)
10395 "Completing-read with SPACE being a normal character."
10396 (let ((enable-recursive-minibuffers t)
10397 (minibuffer-local-completion-map
10398 (copy-keymap minibuffer-local-completion-map)))
10399 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10400 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10401 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10402 'org-time-stamp-inactive)
10403 (apply #'completing-read args)))
10405 ;;; Opening/following a link
10407 (defvar org-link-search-failed nil)
10409 (defvar org-open-link-functions nil
10410 "Hook for functions finding a plain text link.
10411 These functions must take a single argument, the link content.
10412 They will be called for links that look like [[link text][description]]
10413 when LINK TEXT does not have a protocol like \"http:\" and does not look
10414 like a filename (e.g. \"./blue.png\").
10416 These functions will be called *before* Org attempts to resolve the
10417 link by doing text searches in the current buffer - so if you want a
10418 link \"[[target]]\" to still find \"<<target>>\", your function should
10419 handle this as a special case.
10421 When the function does handle the link, it must return a non-nil value.
10422 If it decides that it is not responsible for this link, it must return
10423 nil to indicate that that Org can continue with other options like
10424 exact and fuzzy text search.")
10426 (defun org-next-link (&optional search-backward)
10427 "Move forward to the next link.
10428 If the link is in hidden text, expose it."
10429 (interactive "P")
10430 (when (and org-link-search-failed (eq this-command last-command))
10431 (goto-char (point-min))
10432 (message "Link search wrapped back to beginning of buffer"))
10433 (setq org-link-search-failed nil)
10434 (let* ((pos (point))
10435 (ct (org-context))
10436 (a (assq :link ct))
10437 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10438 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10439 ((looking-at org-any-link-re)
10440 ;; Don't stay stuck at link without an org-link face
10441 (forward-char (if search-backward -1 1))))
10442 (if (funcall srch-fun org-any-link-re nil t)
10443 (progn
10444 (goto-char (match-beginning 0))
10445 (when (org-invisible-p) (org-show-context)))
10446 (goto-char pos)
10447 (setq org-link-search-failed t)
10448 (message "No further link found"))))
10450 (defun org-previous-link ()
10451 "Move backward to the previous link.
10452 If the link is in hidden text, expose it."
10453 (interactive)
10454 (funcall 'org-next-link t))
10456 (defun org-translate-link (s)
10457 "Translate a link string if a translation function has been defined."
10458 (with-temp-buffer
10459 (insert (org-trim s))
10460 (org-trim (org-element-interpret-data (org-element-context)))))
10462 (defun org-translate-link-from-planner (type path)
10463 "Translate a link from Emacs Planner syntax so that Org can follow it.
10464 This is still an experimental function, your mileage may vary."
10465 (cond
10466 ((member type '("http" "https" "news" "ftp"))
10467 ;; standard Internet links are the same.
10468 nil)
10469 ((and (equal type "irc") (string-match "^//" path))
10470 ;; Planner has two / at the beginning of an irc link, we have 1.
10471 ;; We should have zero, actually....
10472 (setq path (substring path 1)))
10473 ((and (equal type "lisp") (string-match "^/" path))
10474 ;; Planner has a slash, we do not.
10475 (setq type "elisp" path (substring path 1)))
10476 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10477 ;; A typical message link. Planner has the id after the final slash,
10478 ;; we separate it with a hash mark
10479 (setq path (concat (match-string 1 path) "#"
10480 (org-unbracket-string "<" ">" (match-string 2 path))))))
10481 (cons type path))
10483 (defun org-find-file-at-mouse (ev)
10484 "Open file link or URL at mouse."
10485 (interactive "e")
10486 (mouse-set-point ev)
10487 (org-open-at-point 'in-emacs))
10489 (defun org-open-at-mouse (ev)
10490 "Open file link or URL at mouse.
10491 See the docstring of `org-open-file' for details."
10492 (interactive "e")
10493 (mouse-set-point ev)
10494 (when (eq major-mode 'org-agenda-mode)
10495 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10496 (org-open-at-point))
10498 (defvar org-window-config-before-follow-link nil
10499 "The window configuration before following a link.
10500 This is saved in case the need arises to restore it.")
10502 ;;;###autoload
10503 (defun org-open-at-point-global ()
10504 "Follow a link or time-stamp like Org mode does.
10505 This command can be called in any mode to follow an external link
10506 or a time-stamp that has Org mode syntax. Its behavior is
10507 undefined when called on internal links (e.g., fuzzy links).
10508 Raise an error when there is nothing to follow. "
10509 (interactive)
10510 (cond ((org-in-regexp org-any-link-re)
10511 (org-open-link-from-string (match-string-no-properties 0)))
10512 ((or (org-in-regexp org-ts-regexp-both nil t)
10513 (org-in-regexp org-tsr-regexp-both nil t))
10514 (org-follow-timestamp-link))
10515 (t (user-error "No link found"))))
10517 ;;;###autoload
10518 (defun org-open-link-from-string (s &optional arg reference-buffer)
10519 "Open a link in the string S, as if it was in Org mode."
10520 (interactive "sLink: \nP")
10521 (let ((reference-buffer (or reference-buffer (current-buffer))))
10522 (with-temp-buffer
10523 (let ((org-inhibit-startup (not reference-buffer)))
10524 (org-mode)
10525 (insert s)
10526 (goto-char (point-min))
10527 (when reference-buffer
10528 (setq org-link-abbrev-alist-local
10529 (with-current-buffer reference-buffer
10530 org-link-abbrev-alist-local)))
10531 (org-open-at-point arg reference-buffer)))))
10533 (defvar org-open-at-point-functions nil
10534 "Hook that is run when following a link at point.
10536 Functions in this hook must return t if they identify and follow
10537 a link at point. If they don't find anything interesting at point,
10538 they must return nil.")
10540 (defvar org-link-search-inhibit-query nil)
10541 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10542 (defun org--open-doi-link (path)
10543 "Open a \"doi\" type link.
10544 PATH is a the path to search for, as a string."
10545 (browse-url (url-encode-url (concat org-doi-server-url path))))
10547 (defun org--open-elisp-link (path)
10548 "Open a \"elisp\" type link.
10549 PATH is the sexp to evaluate, as a string."
10550 (let ((cmd path))
10551 (if (or (and (org-string-nw-p
10552 org-confirm-elisp-link-not-regexp)
10553 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10554 (not org-confirm-elisp-link-function)
10555 (funcall org-confirm-elisp-link-function
10556 (format "Execute \"%s\" as elisp? "
10557 (org-add-props cmd nil 'face 'org-warning))))
10558 (message "%s => %s" cmd
10559 (if (eq (string-to-char cmd) ?\()
10560 (eval (read cmd))
10561 (call-interactively (read cmd))))
10562 (user-error "Abort"))))
10564 (defun org--open-help-link (path)
10565 "Open a \"help\" type link.
10566 PATH is a symbol name, as a string."
10567 (pcase (intern path)
10568 ((and (pred fboundp) variable) (describe-function variable))
10569 ((and (pred boundp) function) (describe-variable function))
10570 (name (user-error "Unknown function or variable: %s" name))))
10572 (defun org--open-shell-link (path)
10573 "Open a \"shell\" type link.
10574 PATH is the command to execute, as a string."
10575 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10576 (cmd path))
10577 (if (or (and (org-string-nw-p
10578 org-confirm-shell-link-not-regexp)
10579 (string-match
10580 org-confirm-shell-link-not-regexp cmd))
10581 (not org-confirm-shell-link-function)
10582 (funcall org-confirm-shell-link-function
10583 (format "Execute \"%s\" in shell? "
10584 (org-add-props cmd nil
10585 'face 'org-warning))))
10586 (progn
10587 (message "Executing %s" cmd)
10588 (shell-command cmd buf)
10589 (when (featurep 'midnight)
10590 (setq clean-buffer-list-kill-buffer-names
10591 (cons (buffer-name buf)
10592 clean-buffer-list-kill-buffer-names))))
10593 (user-error "Abort"))))
10595 (defun org-open-at-point (&optional arg reference-buffer)
10596 "Open link, timestamp, footnote or tags at point.
10598 When point is on a link, follow it. Normally, files will be
10599 opened by an appropriate application. If the optional prefix
10600 argument ARG is non-nil, Emacs will visit the file. With
10601 a double prefix argument, try to open outside of Emacs, in the
10602 application the system uses for this file type.
10604 When point is on a timestamp, open the agenda at the day
10605 specified.
10607 When point is a footnote definition, move to the first reference
10608 found. If it is on a reference, move to the associated
10609 definition.
10611 When point is on a headline, display a list of every link in the
10612 entry, so it is possible to pick one, or all, of them. If point
10613 is on a tag, call `org-tags-view' instead.
10615 When optional argument REFERENCE-BUFFER is non-nil, it should
10616 specify a buffer from where the link search should happen. This
10617 is used internally by `org-open-link-from-string'.
10619 On top of syntactically correct links, this function will also
10620 try to open links and time-stamps in comments, example
10621 blocks... i.e., whenever point is on something looking like
10622 a timestamp or a link."
10623 (interactive "P")
10624 ;; On a code block, open block's results.
10625 (unless (call-interactively 'org-babel-open-src-block-result)
10626 (org-load-modules-maybe)
10627 (setq org-window-config-before-follow-link (current-window-configuration))
10628 (org-remove-occur-highlights nil nil t)
10629 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10630 (let* ((context
10631 ;; Only consider supported types, even if they are not
10632 ;; the closest one.
10633 (org-element-lineage
10634 (org-element-context)
10635 '(clock footnote-definition footnote-reference headline
10636 inlinetask link timestamp)
10638 (type (org-element-type context))
10639 (value (org-element-property :value context)))
10640 (cond
10641 ;; On a headline or an inlinetask, but not on a timestamp,
10642 ;; a link, a footnote reference or on tags.
10643 ((and (memq type '(headline inlinetask))
10644 ;; Not on tags.
10645 (let ((case-fold-search nil))
10646 (and (org-match-line org-complex-heading-regexp)
10647 (or (not (match-beginning 5))
10648 (< (point) (match-beginning 5))))))
10649 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10650 (links (car data))
10651 (links-end (cdr data)))
10652 (if links
10653 (dolist (link (if (stringp links) (list links) links))
10654 (search-forward link nil links-end)
10655 (goto-char (match-beginning 0))
10656 (org-open-at-point))
10657 (require 'org-attach)
10658 (org-attach-reveal 'if-exists))))
10659 ;; On a footnote reference or at definition's label.
10660 ((or (eq type 'footnote-reference)
10661 (and (eq type 'footnote-definition)
10662 (save-excursion
10663 ;; Do not validate action when point is on the
10664 ;; spaces right after the footnote label, in
10665 ;; order to be on par with behaviour on links.
10666 (skip-chars-forward " \t")
10667 (let ((begin
10668 (org-element-property :contents-begin context)))
10669 (if begin (< (point) begin)
10670 (= (org-element-property :post-affiliated context)
10671 (line-beginning-position)))))))
10672 (org-footnote-action))
10673 ;; No valid context. Ignore catch-all types like `headline'.
10674 ;; If point is on something looking like a link or
10675 ;; a time-stamp, try opening it. It may be useful in
10676 ;; comments, example blocks...
10677 ((memq type '(footnote-definition headline inlinetask nil))
10678 (call-interactively #'org-open-at-point-global))
10679 ;; On a clock line, make sure point is on the timestamp
10680 ;; before opening it.
10681 ((and (eq type 'clock)
10682 value
10683 (>= (point) (org-element-property :begin value))
10684 (<= (point) (org-element-property :end value)))
10685 (org-follow-timestamp-link))
10686 ;; Do nothing on white spaces after an object.
10687 ((>= (point)
10688 (save-excursion
10689 (goto-char (org-element-property :end context))
10690 (skip-chars-backward " \t")
10691 (point)))
10692 (user-error "No link found"))
10693 ((eq type 'timestamp) (org-follow-timestamp-link))
10694 ;; On tags within a headline or an inlinetask.
10695 ((and (memq type '(headline inlinetask))
10696 (let ((case-fold-search nil))
10697 (save-excursion (beginning-of-line)
10698 (looking-at org-complex-heading-regexp))
10699 (and (match-beginning 5)
10700 (>= (point) (match-beginning 5)))))
10701 (org-tags-view arg (substring (match-string 5) 0 -1)))
10702 ((eq type 'link)
10703 (let ((type (org-element-property :type context))
10704 (path (org-link-unescape (org-element-property :path context))))
10705 ;; Switch back to REFERENCE-BUFFER needed when called in
10706 ;; a temporary buffer through `org-open-link-from-string'.
10707 (with-current-buffer (or reference-buffer (current-buffer))
10708 (cond
10709 ((equal type "file")
10710 (if (string-match "[*?{]" (file-name-nondirectory path))
10711 (dired path)
10712 ;; Look into `org-link-parameters' in order to find
10713 ;; a DEDICATED-FUNCTION to open file. The function
10714 ;; will be applied on raw link instead of parsed
10715 ;; link due to the limitation in `org-add-link-type'
10716 ;; ("open" function called with a single argument).
10717 ;; If no such function is found, fallback to
10718 ;; `org-open-file'.
10719 (let* ((option (org-element-property :search-option context))
10720 (app (org-element-property :application context))
10721 (dedicated-function
10722 (org-link-get-parameter
10723 (if app (concat type "+" app) type)
10724 :follow)))
10725 (if dedicated-function
10726 (funcall dedicated-function
10727 (concat path
10728 (and option (concat "::" option))))
10729 (apply #'org-open-file
10730 path
10731 (cond (arg)
10732 ((equal app "emacs") 'emacs)
10733 ((equal app "sys") 'system))
10734 (cond ((not option) nil)
10735 ((string-match-p "\\`[0-9]+\\'" option)
10736 (list (string-to-number option)))
10737 (t (list nil
10738 (org-link-unescape option)))))))))
10739 ((functionp (org-link-get-parameter type :follow))
10740 (funcall (org-link-get-parameter type :follow) path))
10741 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10742 (unless (run-hook-with-args-until-success
10743 'org-open-link-functions path)
10744 (if (not arg) (org-mark-ring-push)
10745 (switch-to-buffer-other-window
10746 (org-get-buffer-for-internal-link (current-buffer))))
10747 (let ((destination
10748 (org-with-wide-buffer
10749 (if (equal type "radio")
10750 (org-search-radio-target
10751 (org-element-property :path context))
10752 (org-link-search
10753 (if (member type '("custom-id" "coderef"))
10754 (org-element-property :raw-link context)
10755 path)
10756 ;; Prevent fuzzy links from matching
10757 ;; themselves.
10758 (and (equal type "fuzzy")
10759 (+ 2 (org-element-property :begin context)))))
10760 (point))))
10761 (unless (and (<= (point-min) destination)
10762 (>= (point-max) destination))
10763 (widen))
10764 (goto-char destination))))
10765 (t (browse-url-at-point))))))
10766 (t (user-error "No link found")))))
10767 (run-hook-with-args 'org-follow-link-hook)))
10769 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10770 "Offer links in the current entry and return the selected link.
10771 If there is only one link, return it.
10772 If NTH is an integer, return the NTH link found.
10773 If ZERO is a string, check also this string for a link, and if
10774 there is one, return it."
10775 (with-current-buffer buffer
10776 (org-with-wide-buffer
10777 (goto-char marker)
10778 (let ((cnt ?0)
10779 have-zero end links link c)
10780 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10781 (push (match-string 0 zero) links)
10782 (setq cnt (1- cnt) have-zero t))
10783 (save-excursion
10784 (org-back-to-heading t)
10785 (setq end (save-excursion (outline-next-heading) (point)))
10786 (while (re-search-forward org-any-link-re end t)
10787 (push (match-string 0) links))
10788 (setq links (org-uniquify (reverse links))))
10789 (cond
10790 ((null links)
10791 (message "No links"))
10792 ((equal (length links) 1)
10793 (setq link (car links)))
10794 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10795 (setq link (nth (if have-zero nth (1- nth)) links)))
10796 (t ; we have to select a link
10797 (save-excursion
10798 (save-window-excursion
10799 (delete-other-windows)
10800 (with-output-to-temp-buffer "*Select Link*"
10801 (dolist (l links)
10802 (cond
10803 ((not (string-match org-bracket-link-regexp l))
10804 (princ (format "[%c] %s\n" (cl-incf cnt)
10805 (org-unbracket-string "<" ">" l))))
10806 ((match-end 3)
10807 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10808 (match-string 3 l) (match-string 1 l))))
10809 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10810 (match-string 1 l)))))))
10811 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10812 (message "Select link to open, RET to open all:")
10813 (setq c (read-char-exclusive))
10814 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10815 (when (equal c ?q) (user-error "Abort"))
10816 (if (equal c ?\C-m)
10817 (setq link links)
10818 (setq nth (- c ?0))
10819 (when have-zero (setq nth (1+ nth)))
10820 (unless (and (integerp nth) (>= (length links) nth))
10821 (user-error "Invalid link selection"))
10822 (setq link (nth (1- nth) links)))))
10823 (cons link end)))))
10825 ;; TODO: These functions are deprecated since `org-open-at-point'
10826 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10827 (defun org-open-file-with-system (path)
10828 "Open file at PATH using the system way of opening it."
10829 (org-open-file path 'system))
10830 (defun org-open-file-with-emacs (path)
10831 "Open file at PATH in Emacs."
10832 (org-open-file path 'emacs))
10835 ;;; File search
10837 (defvar org-create-file-search-functions nil
10838 "List of functions to construct the right search string for a file link.
10839 These functions are called in turn with point at the location to
10840 which the link should point.
10842 A function in the hook should first test if it would like to
10843 handle this file type, for example by checking the `major-mode'
10844 or the file extension. If it decides not to handle this file, it
10845 should just return nil to give other functions a chance. If it
10846 does handle the file, it must return the search string to be used
10847 when following the link. The search string will be part of the
10848 file link, given after a double colon, and `org-open-at-point'
10849 will automatically search for it. If special measures must be
10850 taken to make the search successful, another function should be
10851 added to the companion hook `org-execute-file-search-functions',
10852 which see.
10854 A function in this hook may also use `setq' to set the variable
10855 `description' to provide a suggestion for the descriptive text to
10856 be used for this link when it gets inserted into an Org buffer
10857 with \\[org-insert-link].")
10859 (defvar org-execute-file-search-functions nil
10860 "List of functions to execute a file search triggered by a link.
10862 Functions added to this hook must accept a single argument, the
10863 search string that was part of the file link, the part after the
10864 double colon. The function must first check if it would like to
10865 handle this search, for example by checking the `major-mode' or
10866 the file extension. If it decides not to handle this search, it
10867 should just return nil to give other functions a chance. If it
10868 does handle the search, it must return a non-nil value to keep
10869 other functions from trying.
10871 Each function can access the current prefix argument through the
10872 variable `current-prefix-arg'. Note that a single prefix is used
10873 to force opening a link in Emacs, so it may be good to only use a
10874 numeric or double prefix to guide the search function.
10876 In case this is needed, a function in this hook can also restore
10877 the window configuration before `org-open-at-point' was called using:
10879 (set-window-configuration org-window-config-before-follow-link)")
10881 (defun org-search-radio-target (target)
10882 "Search a radio target matching TARGET in current buffer.
10883 White spaces are not significant."
10884 (let ((re (format "<<<%s>>>"
10885 (mapconcat #'regexp-quote
10886 (org-split-string target "[ \t\n]+")
10887 "[ \t]+\\(?:\n[ \t]*\\)?")))
10888 (origin (point)))
10889 (goto-char (point-min))
10890 (catch :radio-match
10891 (while (re-search-forward re nil t)
10892 (backward-char)
10893 (let ((object (org-element-context)))
10894 (when (eq (org-element-type object) 'radio-target)
10895 (goto-char (org-element-property :begin object))
10896 (org-show-context 'link-search)
10897 (throw :radio-match nil))))
10898 (goto-char origin)
10899 (user-error "No match for radio target: %s" target))))
10901 (defun org-link-search (s &optional avoid-pos stealth)
10902 "Search for a search string S.
10904 If S starts with \"#\", it triggers a custom ID search.
10906 If S is enclosed within parenthesis, it initiates a coderef
10907 search.
10909 If S is surrounded by forward slashes, it is interpreted as
10910 a regular expression. In Org mode files, this will create an
10911 `org-occur' sparse tree. In ordinary files, `occur' will be used
10912 to list matches. If the current buffer is in `dired-mode', grep
10913 will be used to search in all files.
10915 When AVOID-POS is given, ignore matches near that position.
10917 When optional argument STEALTH is non-nil, do not modify
10918 visibility around point, thus ignoring `org-show-context-detail'
10919 variable.
10921 Search is case-insensitive and ignores white spaces. Return type
10922 of matched result, which is either `dedicated' or `fuzzy'."
10923 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10924 (let* ((case-fold-search t)
10925 (origin (point))
10926 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10927 (starred (eq (string-to-char normalized) ?*))
10928 (words (split-string (if starred (substring s 1) s)))
10929 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10930 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10931 type)
10932 (cond
10933 ;; Check if there are any special search functions.
10934 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10935 ((eq (string-to-char s) ?#)
10936 ;; Look for a custom ID S if S starts with "#".
10937 (let* ((id (substring normalized 1))
10938 (match (org-find-property "CUSTOM_ID" id)))
10939 (if match (progn (goto-char match) (setf type 'dedicated))
10940 (error "No match for custom ID: %s" id))))
10941 ((string-match "\\`(\\(.*\\))\\'" normalized)
10942 ;; Look for coderef targets if S is enclosed within parenthesis.
10943 (let ((coderef (match-string-no-properties 1 normalized))
10944 (re (substring s-single-re 1 -1)))
10945 (goto-char (point-min))
10946 (catch :coderef-match
10947 (while (re-search-forward re nil t)
10948 (let ((element (org-element-at-point)))
10949 (when (and (memq (org-element-type element)
10950 '(example-block src-block))
10951 ;; Build proper regexp according to current
10952 ;; block's label format.
10953 (let ((label-fmt
10954 (regexp-quote
10955 (or (org-element-property :label-fmt element)
10956 org-coderef-label-format))))
10957 (save-excursion
10958 (beginning-of-line)
10959 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10960 (format label-fmt coderef))))))
10961 (setq type 'dedicated)
10962 (goto-char (match-beginning 1))
10963 (throw :coderef-match nil))))
10964 (goto-char origin)
10965 (error "No match for coderef: %s" coderef))))
10966 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10967 ;; Look for a regular expression.
10968 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10969 (match-string 1 s)))
10970 ;; From here, we handle fuzzy links.
10972 ;; Look for targets, only if not in a headline search.
10973 ((and (not starred)
10974 (let ((target (format "<<%s>>" s-multi-re)))
10975 (catch :target-match
10976 (goto-char (point-min))
10977 (while (re-search-forward target nil t)
10978 (backward-char)
10979 (let ((context (org-element-context)))
10980 (when (eq (org-element-type context) 'target)
10981 (setq type 'dedicated)
10982 (goto-char (org-element-property :begin context))
10983 (throw :target-match t))))
10984 nil))))
10985 ;; Look for elements named after S, only if not in a headline
10986 ;; search.
10987 ((and (not starred)
10988 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10989 (catch :name-match
10990 (goto-char (point-min))
10991 (while (re-search-forward name nil t)
10992 (let ((element (org-element-at-point)))
10993 (when (equal words
10994 (split-string
10995 (org-element-property :name element)))
10996 (setq type 'dedicated)
10997 (beginning-of-line)
10998 (throw :name-match t))))
10999 nil))))
11000 ;; Regular text search. Prefer headlines in Org mode buffers.
11001 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11002 ;; statistics cookies and tags.
11003 ((and (derived-mode-p 'org-mode)
11004 (let ((title-re
11005 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11006 org-outline-regexp-bol
11007 org-comment-string
11008 (mapconcat #'regexp-quote words ".+")))
11009 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11010 (comment-re (eval-when-compile
11011 (format "\\`%s[ \t]+" org-comment-string))))
11012 (goto-char (point-min))
11013 (catch :found
11014 (while (re-search-forward title-re nil t)
11015 (when (equal words
11016 (split-string
11017 (replace-regexp-in-string
11018 cookie-re ""
11019 (replace-regexp-in-string
11020 comment-re "" (org-get-heading t t t)))))
11021 (throw :found t)))
11022 nil)))
11023 (beginning-of-line)
11024 (setq type 'dedicated))
11025 ;; Offer to create non-existent headline depending on
11026 ;; `org-link-search-must-match-exact-headline'.
11027 ((and (derived-mode-p 'org-mode)
11028 (not org-link-search-inhibit-query)
11029 (eq org-link-search-must-match-exact-headline 'query-to-create)
11030 (yes-or-no-p "No match - create this as a new heading? "))
11031 (goto-char (point-max))
11032 (unless (bolp) (newline))
11033 (org-insert-heading nil t t)
11034 (insert s "\n")
11035 (beginning-of-line 0))
11036 ;; Only headlines are looked after. No need to process
11037 ;; further: throw an error.
11038 ((and (derived-mode-p 'org-mode)
11039 (or starred org-link-search-must-match-exact-headline))
11040 (goto-char origin)
11041 (error "No match for fuzzy expression: %s" normalized))
11042 ;; Regular text search.
11043 ((catch :fuzzy-match
11044 (goto-char (point-min))
11045 (while (re-search-forward s-multi-re nil t)
11046 ;; Skip match if it contains AVOID-POS or it is included in
11047 ;; a link with a description but outside the description.
11048 (unless (or (and avoid-pos
11049 (<= (match-beginning 0) avoid-pos)
11050 (> (match-end 0) avoid-pos))
11051 (and (save-match-data
11052 (org-in-regexp org-bracket-link-regexp))
11053 (match-beginning 3)
11054 (or (> (match-beginning 3) (point))
11055 (<= (match-end 3) (point)))
11056 (org-element-lineage
11057 (save-match-data (org-element-context))
11058 '(link) t)))
11059 (goto-char (match-beginning 0))
11060 (setq type 'fuzzy)
11061 (throw :fuzzy-match t)))
11062 nil))
11063 ;; All failed. Throw an error.
11064 (t (goto-char origin)
11065 (error "No match for fuzzy expression: %s" normalized)))
11066 ;; Disclose surroundings of match, if appropriate.
11067 (when (and (derived-mode-p 'org-mode) (not stealth))
11068 (org-show-context 'link-search))
11069 type))
11071 (defun org-get-buffer-for-internal-link (buffer)
11072 "Return a buffer to be used for displaying the link target of internal links."
11073 (cond
11074 ((not org-display-internal-link-with-indirect-buffer)
11075 buffer)
11076 ((string-suffix-p "(Clone)" (buffer-name buffer))
11077 (message "Buffer is already a clone, not making another one")
11078 ;; we also do not modify visibility in this case
11079 buffer)
11080 (t ; make a new indirect buffer for displaying the link
11081 (let* ((bn (buffer-name buffer))
11082 (ibn (concat bn "(Clone)"))
11083 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11084 (with-current-buffer ib (org-overview))
11085 ib))))
11087 (defun org-do-occur (regexp &optional cleanup)
11088 "Call the Emacs command `occur'.
11089 If CLEANUP is non-nil, remove the printout of the regular expression
11090 in the *Occur* buffer. This is useful if the regex is long and not useful
11091 to read."
11092 (occur regexp)
11093 (when cleanup
11094 (let ((cwin (selected-window)) win beg end)
11095 (when (setq win (get-buffer-window "*Occur*"))
11096 (select-window win))
11097 (goto-char (point-min))
11098 (when (re-search-forward "match[a-z]+" nil t)
11099 (setq beg (match-end 0))
11100 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11101 (setq end (1- (match-beginning 0)))))
11102 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11103 (goto-char (point-min))
11104 (select-window cwin))))
11106 ;;; The mark ring for links jumps
11108 (defvar org-mark-ring nil
11109 "Mark ring for positions before jumps in Org mode.")
11110 (defvar org-mark-ring-last-goto nil
11111 "Last position in the mark ring used to go back.")
11112 ;; Fill and close the ring
11113 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11114 (dotimes (_ org-mark-ring-length)
11115 (push (make-marker) org-mark-ring))
11116 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11117 org-mark-ring)
11119 (defun org-mark-ring-push (&optional pos buffer)
11120 "Put the current position or POS into the mark ring and rotate it."
11121 (interactive)
11122 (setq pos (or pos (point)))
11123 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11124 (move-marker (car org-mark-ring)
11125 (or pos (point))
11126 (or buffer (current-buffer)))
11127 (message "%s"
11128 (substitute-command-keys
11129 "Position saved to mark ring, go back with \
11130 `\\[org-mark-ring-goto]'.")))
11132 (defun org-mark-ring-goto (&optional n)
11133 "Jump to the previous position in the mark ring.
11134 With prefix arg N, jump back that many stored positions. When
11135 called several times in succession, walk through the entire ring.
11136 Org mode commands jumping to a different position in the current file,
11137 or to another Org file, automatically push the old position onto the ring."
11138 (interactive "p")
11139 (let (p m)
11140 (if (eq last-command this-command)
11141 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11142 (setq p org-mark-ring))
11143 (setq org-mark-ring-last-goto p)
11144 (setq m (car p))
11145 (pop-to-buffer-same-window (marker-buffer m))
11146 (goto-char m)
11147 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11149 (defun org-add-angle-brackets (s)
11150 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11151 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11154 ;;; Following specific links
11156 (defvar org-agenda-buffer-tmp-name)
11157 (defvar org-agenda-start-on-weekday)
11158 (defun org-follow-timestamp-link ()
11159 "Open an agenda view for the time-stamp date/range at point."
11160 (cond
11161 ((org-at-date-range-p t)
11162 (let ((org-agenda-start-on-weekday)
11163 (t1 (match-string 1))
11164 (t2 (match-string 2)) tt1 tt2)
11165 (setq tt1 (time-to-days (org-time-string-to-time t1))
11166 tt2 (time-to-days (org-time-string-to-time t2)))
11167 (let ((org-agenda-buffer-tmp-name
11168 (format "*Org Agenda(a:%s)"
11169 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11170 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11171 ((org-at-timestamp-p 'lax)
11172 (let ((org-agenda-buffer-tmp-name
11173 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11174 (org-agenda-list nil (time-to-days (org-time-string-to-time
11175 (substring (match-string 1) 0 10)))
11176 1)))
11177 (t (error "This should not happen"))))
11180 ;;; Following file links
11181 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11182 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11183 (declare-function mailcap-mime-info
11184 "mailcap" (string &optional request no-decode))
11185 (defvar org-wait nil)
11186 (defun org-open-file (path &optional in-emacs line search)
11187 "Open the file at PATH.
11188 First, this expands any special file name abbreviations. Then the
11189 configuration variable `org-file-apps' is checked if it contains an
11190 entry for this file type, and if yes, the corresponding command is launched.
11192 If no application is found, Emacs simply visits the file.
11194 With optional prefix argument IN-EMACS, Emacs will visit the file.
11195 With a double \\[universal-argument] \\[universal-argument] \
11196 prefix arg, Org tries to avoid opening in Emacs
11197 and to use an external application to visit the file.
11199 Optional LINE specifies a line to go to, optional SEARCH a string
11200 to search for. If LINE or SEARCH is given, the file will be
11201 opened in Emacs, unless an entry from org-file-apps that makes
11202 use of groups in a regexp matches.
11204 If you want to change the way frames are used when following a
11205 link, please customize `org-link-frame-setup'.
11207 If the file does not exist, an error is thrown."
11208 (let* ((file (if (equal path "")
11209 buffer-file-name
11210 (substitute-in-file-name (expand-file-name path))))
11211 (file-apps (append org-file-apps (org-default-apps)))
11212 (apps (cl-remove-if
11213 'org-file-apps-entry-match-against-dlink-p file-apps))
11214 (apps-dlink (cl-remove-if-not
11215 'org-file-apps-entry-match-against-dlink-p file-apps))
11216 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11217 (dirp (unless remp (file-directory-p file)))
11218 (file (if (and dirp org-open-directory-means-index-dot-org)
11219 (concat (file-name-as-directory file) "index.org")
11220 file))
11221 (a-m-a-p (assq 'auto-mode apps))
11222 (dfile (downcase file))
11223 ;; Reconstruct the original link from the PATH, LINE and
11224 ;; SEARCH args.
11225 (link (cond (line (concat file "::" (number-to-string line)))
11226 (search (concat file "::" search))
11227 (t file)))
11228 (dlink (downcase link))
11229 (ext
11230 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11231 (match-string 1 dfile)))
11232 (save-position-maybe
11233 (let ((old-buffer (current-buffer))
11234 (old-pos (point))
11235 (old-mode major-mode))
11236 (lambda ()
11237 (and (derived-mode-p 'org-mode)
11238 (eq old-mode 'org-mode)
11239 (or (not (eq old-buffer (current-buffer)))
11240 (not (eq old-pos (point))))
11241 (org-mark-ring-push old-pos old-buffer)))))
11242 cmd link-match-data)
11243 (cond
11244 ((member in-emacs '((16) system))
11245 (setq cmd (cdr (assq 'system apps))))
11246 (in-emacs (setq cmd 'emacs))
11248 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11249 (and dirp (cdr (assq 'directory apps)))
11250 ;; First, try matching against apps-dlink if we
11251 ;; get a match here, store the match data for
11252 ;; later.
11253 (let ((match (assoc-default dlink apps-dlink
11254 'string-match)))
11255 (if match
11256 (progn (setq link-match-data (match-data))
11257 match)
11258 (progn (setq in-emacs (or in-emacs line search))
11259 nil))) ; if we have no match in apps-dlink,
11260 ; always open the file in emacs if line or search
11261 ; is given (for backwards compatibility)
11262 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11263 'string-match)
11264 (cdr (assoc ext apps))
11265 (cdr (assq t apps))))))
11266 (when (eq cmd 'system)
11267 (setq cmd (cdr (assq 'system apps))))
11268 (when (eq cmd 'default)
11269 (setq cmd (cdr (assoc t apps))))
11270 (when (eq cmd 'mailcap)
11271 (require 'mailcap)
11272 (mailcap-parse-mailcaps)
11273 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11274 (command (mailcap-mime-info mime-type)))
11275 (if (stringp command)
11276 (setq cmd command)
11277 (setq cmd 'emacs))))
11278 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11279 (not (file-exists-p file))
11280 (not org-open-non-existing-files))
11281 (user-error "No such file: %s" file))
11282 (cond
11283 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11284 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11285 (while (string-match "['\"]%s['\"]" cmd)
11286 (setq cmd (replace-match "%s" t t cmd)))
11287 (setq cmd (replace-regexp-in-string
11288 "%s"
11289 (shell-quote-argument (convert-standard-filename file))
11291 nil t))
11293 ;; Replace "%1", "%2" etc. in command with group matches from regex
11294 (save-match-data
11295 (let ((match-index 1)
11296 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11297 (set-match-data link-match-data)
11298 (while (<= match-index number-of-groups)
11299 (let ((regex (concat "%" (number-to-string match-index)))
11300 (replace-with (match-string match-index dlink)))
11301 (while (string-match regex cmd)
11302 (setq cmd (replace-match replace-with t t cmd))))
11303 (setq match-index (+ match-index 1)))))
11305 (save-window-excursion
11306 (message "Running %s...done" cmd)
11307 (start-process-shell-command cmd nil cmd)
11308 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11309 ((or (stringp cmd)
11310 (eq cmd 'emacs))
11311 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11312 (widen)
11313 (cond (line (org-goto-line line)
11314 (when (derived-mode-p 'org-mode) (org-reveal)))
11315 (search (condition-case err
11316 (org-link-search search)
11317 ;; Save position before error-ing out so user
11318 ;; can easily move back to the original buffer.
11319 (error (funcall save-position-maybe)
11320 (error (nth 1 err)))))))
11321 ((functionp cmd)
11322 (save-match-data
11323 (set-match-data link-match-data)
11324 (condition-case nil
11325 (funcall cmd file link)
11326 ;; FIXME: Remove this check when most default installations
11327 ;; of Emacs have at least Org 9.0.
11328 ((debug wrong-number-of-arguments wrong-type-argument
11329 invalid-function)
11330 (user-error "Please see Org News for version 9.0 about \
11331 `org-file-apps'--Lisp error: %S" cmd)))))
11332 ((consp cmd)
11333 ;; FIXME: Remove this check when most default installations of
11334 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11335 ;; fall back to `org-link-frame-setup' for an old usage of
11336 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11337 (user-error "Please see Org News for version 9.0 about \
11338 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11339 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11340 (funcall save-position-maybe)))
11342 (defun org-file-apps-entry-match-against-dlink-p (entry)
11343 "This function returns non-nil if `entry' uses a regular
11344 expression which should be matched against the whole link by
11345 org-open-file.
11347 It assumes that is the case when the entry uses a regular
11348 expression which has at least one grouping construct and the
11349 action is either a lisp form or a command string containing
11350 `%1', i.e. using at least one subexpression match as a
11351 parameter."
11352 (let ((selector (car entry))
11353 (action (cdr entry)))
11354 (if (stringp selector)
11355 (and (> (regexp-opt-depth selector) 0)
11356 (or (and (stringp action)
11357 (string-match "%[0-9]" action))
11358 (consp action)))
11359 nil)))
11361 (defun org-default-apps ()
11362 "Return the default applications for this operating system."
11363 (cond
11364 ((eq system-type 'darwin)
11365 org-file-apps-defaults-macosx)
11366 ((eq system-type 'windows-nt)
11367 org-file-apps-defaults-windowsnt)
11368 (t org-file-apps-defaults-gnu)))
11370 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11371 "Convert extensions to regular expressions in the cars of LIST.
11372 Also, weed out any non-string entries, because the return value is used
11373 only for regexp matching.
11374 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11375 point to the symbol `emacs', indicating that the file should
11376 be opened in Emacs."
11377 (append
11378 (delq nil
11379 (mapcar (lambda (x)
11380 (unless (not (stringp (car x)))
11381 (if (string-match "\\W" (car x))
11383 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11384 list))
11385 (when add-auto-mode
11386 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11388 (defvar ange-ftp-name-format)
11389 (defun org-file-remote-p (file)
11390 "Test whether FILE specifies a location on a remote system.
11391 Return non-nil if the location is indeed remote.
11393 For example, the filename \"/user@host:/foo\" specifies a location
11394 on the system \"/user@host:\"."
11395 (cond ((fboundp 'file-remote-p)
11396 (file-remote-p file))
11397 ((fboundp 'tramp-handle-file-remote-p)
11398 (tramp-handle-file-remote-p file))
11399 ((and (boundp 'ange-ftp-name-format)
11400 (string-match (car ange-ftp-name-format) file))
11401 t)))
11404 ;;;; Refiling
11406 (defun org-get-org-file ()
11407 "Read a filename, with default directory `org-directory'."
11408 (let ((default (or org-default-notes-file remember-data-file)))
11409 (read-file-name (format "File name [%s]: " default)
11410 (file-name-as-directory org-directory)
11411 default)))
11413 (defun org-notes-order-reversed-p ()
11414 "Check if the current file should receive notes in reversed order."
11415 (cond
11416 ((not org-reverse-note-order) nil)
11417 ((eq t org-reverse-note-order) t)
11418 ((not (listp org-reverse-note-order)) nil)
11419 (t (catch 'exit
11420 (dolist (entry org-reverse-note-order)
11421 (when (string-match (car entry) buffer-file-name)
11422 (throw 'exit (cdr entry))))))))
11424 (defvar org-refile-target-table nil
11425 "The list of refile targets, created by `org-refile'.")
11427 (defvar org-agenda-new-buffers nil
11428 "Buffers created to visit agenda files.")
11430 (defvar org-refile-cache nil
11431 "Cache for refile targets.")
11433 (defvar org-refile-markers nil
11434 "All the markers used for caching refile locations.")
11436 (defun org-refile-marker (pos)
11437 "Get a new refile marker, but only if caching is in use."
11438 (if (not org-refile-use-cache)
11440 (let ((m (make-marker)))
11441 (move-marker m pos)
11442 (push m org-refile-markers)
11443 m)))
11445 (defun org-refile-cache-clear ()
11446 "Clear the refile cache and disable all the markers."
11447 (dolist (m org-refile-markers) (move-marker m nil))
11448 (setq org-refile-markers nil)
11449 (setq org-refile-cache nil)
11450 (message "Refile cache has been cleared"))
11452 (defun org-refile-cache-check-set (set)
11453 "Check if all the markers in the cache still have live buffers."
11454 (let (marker)
11455 (catch 'exit
11456 (while (and set (setq marker (nth 3 (pop set))))
11457 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11458 (when (and marker (null (marker-buffer marker)))
11459 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11460 (sit-for 3)
11461 (throw 'exit nil)))
11462 t)))
11464 (defun org-refile-cache-put (set &rest identifiers)
11465 "Push the refile targets SET into the cache, under IDENTIFIERS."
11466 (let* ((key (sha1 (prin1-to-string identifiers)))
11467 (entry (assoc key org-refile-cache)))
11468 (if entry
11469 (setcdr entry set)
11470 (push (cons key set) org-refile-cache))))
11472 (defun org-refile-cache-get (&rest identifiers)
11473 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11474 (cond
11475 ((not org-refile-cache) nil)
11476 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11478 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11479 org-refile-cache))))
11480 (and set (org-refile-cache-check-set set) set)))))
11482 (defvar org-outline-path-cache nil
11483 "Alist between buffer positions and outline paths.
11484 It value is an alist (POSITION . PATH) where POSITION is the
11485 buffer position at the beginning of an entry and PATH is a list
11486 of strings describing the outline path for that entry, in reverse
11487 order.")
11489 (defun org-refile-get-targets (&optional default-buffer)
11490 "Produce a table with refile targets."
11491 (let ((case-fold-search nil)
11492 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11493 (entries (or org-refile-targets '((nil . (:level . 1)))))
11494 targets tgs files desc descre)
11495 (message "Getting targets...")
11496 (with-current-buffer (or default-buffer (current-buffer))
11497 (dolist (entry entries)
11498 (setq files (car entry) desc (cdr entry))
11499 (cond
11500 ((null files) (setq files (list (current-buffer))))
11501 ((eq files 'org-agenda-files)
11502 (setq files (org-agenda-files 'unrestricted)))
11503 ((and (symbolp files) (fboundp files))
11504 (setq files (funcall files)))
11505 ((and (symbolp files) (boundp files))
11506 (setq files (symbol-value files))))
11507 (when (stringp files) (setq files (list files)))
11508 (cond
11509 ((eq (car desc) :tag)
11510 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11511 ((eq (car desc) :todo)
11512 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11513 ((eq (car desc) :regexp)
11514 (setq descre (cdr desc)))
11515 ((eq (car desc) :level)
11516 (setq descre (concat "^\\*\\{" (number-to-string
11517 (if org-odd-levels-only
11518 (1- (* 2 (cdr desc)))
11519 (cdr desc)))
11520 "\\}[ \t]")))
11521 ((eq (car desc) :maxlevel)
11522 (setq descre (concat "^\\*\\{1," (number-to-string
11523 (if org-odd-levels-only
11524 (1- (* 2 (cdr desc)))
11525 (cdr desc)))
11526 "\\}[ \t]")))
11527 (t (error "Bad refiling target description %s" desc)))
11528 (dolist (f files)
11529 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11531 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11532 (progn
11533 (when (bufferp f)
11534 (setq f (buffer-file-name (buffer-base-buffer f))))
11535 (setq f (and f (expand-file-name f)))
11536 (when (eq org-refile-use-outline-path 'file)
11537 (push (list (file-name-nondirectory f) f nil nil) tgs))
11538 (when (eq org-refile-use-outline-path 'buffer-name)
11539 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11540 (when (eq org-refile-use-outline-path 'full-file-path)
11541 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11542 (org-with-wide-buffer
11543 (goto-char (point-min))
11544 (setq org-outline-path-cache nil)
11545 (while (re-search-forward descre nil t)
11546 (beginning-of-line)
11547 (let ((case-fold-search nil))
11548 (looking-at org-complex-heading-regexp))
11549 (let ((begin (point))
11550 (heading (match-string-no-properties 4)))
11551 (unless (or (and
11552 org-refile-target-verify-function
11553 (not
11554 (funcall org-refile-target-verify-function)))
11555 (not heading))
11556 (let ((re (format org-complex-heading-regexp-format
11557 (regexp-quote heading)))
11558 (target
11559 (if (not org-refile-use-outline-path) heading
11560 (mapconcat
11561 #'identity
11562 (append
11563 (pcase org-refile-use-outline-path
11564 (`file (list (file-name-nondirectory
11565 (buffer-file-name
11566 (buffer-base-buffer)))))
11567 (`full-file-path
11568 (list (buffer-file-name
11569 (buffer-base-buffer))))
11570 (`buffer-name
11571 (list (buffer-name
11572 (buffer-base-buffer))))
11573 (_ nil))
11574 (mapcar (lambda (s) (replace-regexp-in-string
11575 "/" "\\/" s nil t))
11576 (org-get-outline-path t t)))
11577 "/"))))
11578 (push (list target f re (org-refile-marker (point)))
11579 tgs)))
11580 (when (= (point) begin)
11581 ;; Verification function has not moved point.
11582 (end-of-line)))))))
11583 (when org-refile-use-cache
11584 (org-refile-cache-put tgs (buffer-file-name) descre))
11585 (setq targets (append tgs targets))))))
11586 (message "Getting targets...done")
11587 (delete-dups (nreverse targets))))
11589 (defun org--get-outline-path-1 (&optional use-cache)
11590 "Return outline path to current headline.
11592 Outline path is a list of strings, in reverse order. When
11593 optional argument USE-CACHE is non-nil, make use of a cache. See
11594 `org-get-outline-path' for details.
11596 Assume buffer is widened and point is on a headline."
11597 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11598 (let ((p (point))
11599 (heading (let ((case-fold-search nil))
11600 (looking-at org-complex-heading-regexp)
11601 (if (not (match-end 4)) ""
11602 ;; Remove statistics cookies.
11603 (org-trim
11604 (org-link-display-format
11605 (replace-regexp-in-string
11606 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11607 (match-string-no-properties 4))))))))
11608 (if (org-up-heading-safe)
11609 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11610 (when use-cache
11611 (push (cons p path) org-outline-path-cache))
11612 path)
11613 ;; This is a new root node. Since we assume we are moving
11614 ;; forward, we can drop previous cache so as to limit number
11615 ;; of associations there.
11616 (let ((path (list heading)))
11617 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11618 path)))))
11620 (defun org-get-outline-path (&optional with-self use-cache)
11621 "Return the outline path to the current entry.
11623 An outline path is a list of ancestors for current headline, as
11624 a list of strings. Statistics cookies are removed and links are
11625 replaced with their description, if any, or their path otherwise.
11627 When optional argument WITH-SELF is non-nil, the path also
11628 includes the current headline.
11630 When optional argument USE-CACHE is non-nil, cache outline paths
11631 between calls to this function so as to avoid backtracking. This
11632 argument is useful when planning to find more than one outline
11633 path in the same document. In that case, there are two
11634 conditions to satisfy:
11635 - `org-outline-path-cache' is set to nil before starting the
11636 process;
11637 - outline paths are computed by increasing buffer positions."
11638 (org-with-wide-buffer
11639 (and (or (and with-self (org-back-to-heading t))
11640 (org-up-heading-safe))
11641 (reverse (org--get-outline-path-1 use-cache)))))
11643 (defun org-format-outline-path (path &optional width prefix separator)
11644 "Format the outline path PATH for display.
11645 WIDTH is the maximum number of characters that is available.
11646 PREFIX is a prefix to be included in the returned string,
11647 such as the file name.
11648 SEPARATOR is inserted between the different parts of the path,
11649 the default is \"/\"."
11650 (setq width (or width 79))
11651 (setq path (delq nil path))
11652 (unless (> width 0)
11653 (user-error "Argument `width' must be positive"))
11654 (setq separator (or separator "/"))
11655 (let* ((org-odd-levels-only nil)
11656 (fpath (concat
11657 prefix (and prefix path separator)
11658 (mapconcat
11659 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11660 (cl-loop for head in path
11661 for n from 0
11662 collect (org-add-props
11663 head nil 'face
11664 (nth (% n org-n-level-faces) org-level-faces)))
11665 separator))))
11666 (when (> (length fpath) width)
11667 (if (< width 7)
11668 ;; It's unlikely that `width' will be this small, but don't
11669 ;; waste characters by adding ".." if it is.
11670 (setq fpath (substring fpath 0 width))
11671 (setf (substring fpath (- width 2)) "..")))
11672 fpath))
11674 (defun org-display-outline-path (&optional file current separator just-return-string)
11675 "Display the current outline path in the echo area.
11677 If FILE is non-nil, prepend the output with the file name.
11678 If CURRENT is non-nil, append the current heading to the output.
11679 SEPARATOR is passed through to `org-format-outline-path'. It separates
11680 the different parts of the path and defaults to \"/\".
11681 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11682 (interactive "P")
11683 (let* (case-fold-search
11684 (bfn (buffer-file-name (buffer-base-buffer)))
11685 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11686 res)
11687 (when current (setq path (append path
11688 (save-excursion
11689 (org-back-to-heading t)
11690 (when (looking-at org-complex-heading-regexp)
11691 (list (match-string 4)))))))
11692 (setq res
11693 (org-format-outline-path
11694 path
11695 (1- (frame-width))
11696 (and file bfn (concat (file-name-nondirectory bfn) separator))
11697 separator))
11698 (if just-return-string
11699 (org-no-properties res)
11700 (org-unlogged-message "%s" res))))
11702 (defvar org-refile-history nil
11703 "History for refiling operations.")
11705 (defvar org-after-refile-insert-hook nil
11706 "Hook run after `org-refile' has inserted its stuff at the new location.
11707 Note that this is still *before* the stuff will be removed from
11708 the *old* location.")
11710 (defvar org-capture-last-stored-marker)
11711 (defvar org-refile-keep nil
11712 "Non-nil means `org-refile' will copy instead of refile.")
11714 (defun org-copy ()
11715 "Like `org-refile', but copy."
11716 (interactive)
11717 (let ((org-refile-keep t))
11718 (funcall 'org-refile nil nil nil "Copy")))
11720 (defun org-refile (&optional arg default-buffer rfloc msg)
11721 "Move the entry or entries at point to another heading.
11723 The list of target headings is compiled using the information in
11724 `org-refile-targets', which see.
11726 At the target location, the entry is filed as a subitem of the
11727 target heading. Depending on `org-reverse-note-order', the new
11728 subitem will either be the first or the last subitem.
11730 If there is an active region, all entries in that region will be
11731 refiled. However, the region must fulfill the requirement that
11732 the first heading sets the top-level of the moved text.
11734 With a `\\[universal-argument]' ARG, the command will only visit the target \
11735 location
11736 and not actually move anything.
11738 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11739 location where the last
11740 refiling operation has put the subtree.
11742 With a numeric prefix argument of `2', refile to the running clock.
11744 With a numeric prefix argument of `3', emulate `org-refile-keep'
11745 being set to t and copy to the target location, don't move it.
11746 Beware that keeping refiled entries may result in duplicated ID
11747 properties.
11749 RFLOC can be a refile location obtained in a different way.
11751 MSG is a string to replace \"Refile\" in the default prompt with
11752 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11754 See also `org-refile-use-outline-path'.
11756 If you are using target caching (see `org-refile-use-cache'), you
11757 have to clear the target cache in order to find new targets.
11758 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11759 prefix argument (`C-u C-u C-u C-c C-w')."
11760 (interactive "P")
11761 (if (member arg '(0 (64)))
11762 (org-refile-cache-clear)
11763 (let* ((actionmsg (cond (msg msg)
11764 ((equal arg 3) "Refile (and keep)")
11765 (t "Refile")))
11766 (regionp (org-region-active-p))
11767 (region-start (and regionp (region-beginning)))
11768 (region-end (and regionp (region-end)))
11769 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11770 pos it nbuf file level reversed)
11771 (setq last-command nil)
11772 (when regionp
11773 (goto-char region-start)
11774 (or (bolp) (goto-char (point-at-bol)))
11775 (setq region-start (point))
11776 (unless (or (org-kill-is-subtree-p
11777 (buffer-substring region-start region-end))
11778 (prog1 org-refile-active-region-within-subtree
11779 (let ((s (point-at-eol)))
11780 (org-toggle-heading)
11781 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11782 (user-error "The region is not a (sequence of) subtree(s)")))
11783 (if (equal arg '(16))
11784 (org-refile-goto-last-stored)
11785 (when (or
11786 (and (equal arg 2)
11787 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11788 (prog1
11789 (setq it (list (or org-clock-heading "running clock")
11790 (buffer-file-name
11791 (marker-buffer org-clock-hd-marker))
11793 (marker-position org-clock-hd-marker)))
11794 (setq arg nil)))
11795 (setq it
11796 (or rfloc
11797 (let (heading-text)
11798 (save-excursion
11799 (unless (and arg (listp arg))
11800 (org-back-to-heading t)
11801 (setq heading-text
11802 (replace-regexp-in-string
11803 org-bracket-link-regexp
11804 "\\3"
11805 (or (nth 4 (org-heading-components))
11806 ""))))
11807 (org-refile-get-location
11808 (cond ((and arg (listp arg)) "Goto")
11809 (regionp (concat actionmsg " region to"))
11810 (t (concat actionmsg " subtree \""
11811 heading-text "\" to")))
11812 default-buffer
11813 (and (not (equal '(4) arg))
11814 org-refile-allow-creating-parent-nodes)))))))
11815 (setq file (nth 1 it)
11816 pos (nth 3 it))
11817 (when (and (not arg)
11819 (equal (buffer-file-name) file)
11820 (if regionp
11821 (and (>= pos region-start)
11822 (<= pos region-end))
11823 (and (>= pos (point))
11824 (< pos (save-excursion
11825 (org-end-of-subtree t t))))))
11826 (error "Cannot refile to position inside the tree or region"))
11827 (setq nbuf (or (find-buffer-visiting file)
11828 (find-file-noselect file)))
11829 (if (and arg (not (equal arg 3)))
11830 (progn
11831 (pop-to-buffer-same-window nbuf)
11832 (goto-char pos)
11833 (org-show-context 'org-goto))
11834 (if regionp
11835 (progn
11836 (org-kill-new (buffer-substring region-start region-end))
11837 (org-save-markers-in-region region-start region-end))
11838 (org-copy-subtree 1 nil t))
11839 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11840 (find-file-noselect file)))
11841 (setq reversed (org-notes-order-reversed-p))
11842 (org-with-wide-buffer
11843 (if pos
11844 (progn
11845 (goto-char pos)
11846 (setq level (org-get-valid-level (funcall outline-level) 1))
11847 (goto-char
11848 (if reversed
11849 (or (outline-next-heading) (point-max))
11850 (or (save-excursion (org-get-next-sibling))
11851 (org-end-of-subtree t t)
11852 (point-max)))))
11853 (setq level 1)
11854 (if (not reversed)
11855 (goto-char (point-max))
11856 (goto-char (point-min))
11857 (or (outline-next-heading) (goto-char (point-max)))))
11858 (unless (bolp) (newline))
11859 (org-paste-subtree level nil nil t)
11860 (when org-log-refile
11861 (org-add-log-setup 'refile nil nil org-log-refile)
11862 (unless (eq org-log-refile 'note)
11863 (save-excursion (org-add-log-note))))
11864 (and org-auto-align-tags
11865 (let ((org-loop-over-headlines-in-active-region nil))
11866 (org-set-tags nil t)))
11867 (let ((bookmark-name (plist-get org-bookmark-names-plist
11868 :last-refile)))
11869 (when bookmark-name
11870 (with-demoted-errors
11871 (bookmark-set bookmark-name))))
11872 ;; If we are refiling for capture, make sure that the
11873 ;; last-capture pointers point here
11874 (when (bound-and-true-p org-capture-is-refiling)
11875 (let ((bookmark-name (plist-get org-bookmark-names-plist
11876 :last-capture-marker)))
11877 (when bookmark-name
11878 (with-demoted-errors
11879 (bookmark-set bookmark-name))))
11880 (move-marker org-capture-last-stored-marker (point)))
11881 (when (fboundp 'deactivate-mark) (deactivate-mark))
11882 (run-hooks 'org-after-refile-insert-hook)))
11883 (unless org-refile-keep
11884 (if regionp
11885 (delete-region (point) (+ (point) (- region-end region-start)))
11886 (delete-region
11887 (and (org-back-to-heading t) (point))
11888 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11889 (when (featurep 'org-inlinetask)
11890 (org-inlinetask-remove-END-maybe))
11891 (setq org-markers-to-move nil)
11892 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11894 (defun org-refile-goto-last-stored ()
11895 "Go to the location where the last refile was stored."
11896 (interactive)
11897 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11898 (message "This is the location of the last refile"))
11900 (defun org-refile--get-location (refloc tbl)
11901 "When user refile to REFLOC, find the associated target in TBL.
11902 Also check `org-refile-target-table'."
11903 (car (delq
11905 (mapcar
11906 (lambda (r) (or (assoc r tbl)
11907 (assoc r org-refile-target-table)))
11908 (list (replace-regexp-in-string "/$" "" refloc)
11909 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11911 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11912 "Prompt the user for a refile location, using PROMPT.
11913 PROMPT should not be suffixed with a colon and a space, because
11914 this function appends the default value from
11915 `org-refile-history' automatically, if that is not empty."
11916 (let ((org-refile-targets org-refile-targets)
11917 (org-refile-use-outline-path org-refile-use-outline-path))
11918 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11919 (unless org-refile-target-table
11920 (user-error "No refile targets"))
11921 (let* ((cbuf (current-buffer))
11922 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11923 (cfunc (if (and org-refile-use-outline-path
11924 org-outline-path-complete-in-steps)
11925 #'org-olpath-completing-read
11926 #'completing-read))
11927 (extra (if org-refile-use-outline-path "/" ""))
11928 (cbnex (concat (buffer-name) extra))
11929 (filename (and cfn (expand-file-name cfn)))
11930 (tbl (mapcar
11931 (lambda (x)
11932 (if (and (not (member org-refile-use-outline-path
11933 '(file full-file-path)))
11934 (not (equal filename (nth 1 x))))
11935 (cons (concat (car x) extra " ("
11936 (file-name-nondirectory (nth 1 x)) ")")
11937 (cdr x))
11938 (cons (concat (car x) extra) (cdr x))))
11939 org-refile-target-table))
11940 (completion-ignore-case t)
11941 cdef
11942 (prompt (concat prompt
11943 (or (and (car org-refile-history)
11944 (concat " (default " (car org-refile-history) ")"))
11945 (and (assoc cbnex tbl) (setq cdef cbnex)
11946 (concat " (default " cbnex ")"))) ": "))
11947 pa answ parent-target child parent old-hist)
11948 (setq old-hist org-refile-history)
11949 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11950 nil 'org-refile-history (or cdef (car org-refile-history))))
11951 (if (setq pa (org-refile--get-location answ tbl))
11952 (progn
11953 (org-refile-check-position pa)
11954 (when (or (not org-refile-history)
11955 (not (eq old-hist org-refile-history))
11956 (not (equal (car pa) (car org-refile-history))))
11957 (setq org-refile-history
11958 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11959 org-refile-history
11960 (cdr org-refile-history))))
11961 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11962 (pop org-refile-history)))
11964 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11965 (progn
11966 (setq parent (match-string 1 answ)
11967 child (match-string 2 answ))
11968 (setq parent-target (org-refile--get-location parent tbl))
11969 (when (and parent-target
11970 (or (eq new-nodes t)
11971 (and (eq new-nodes 'confirm)
11972 (y-or-n-p (format "Create new node \"%s\"? "
11973 child)))))
11974 (org-refile-new-child parent-target child)))
11975 (user-error "Invalid target location")))))
11977 (declare-function org-string-nw-p "org-macs" (s))
11978 (defun org-refile-check-position (refile-pointer)
11979 "Check if the refile pointer matches the headline to which it points."
11980 (let* ((file (nth 1 refile-pointer))
11981 (re (nth 2 refile-pointer))
11982 (pos (nth 3 refile-pointer))
11983 buffer)
11984 (if (and (not (markerp pos)) (not file))
11985 (user-error "Please indicate a target file in the refile path")
11986 (when (org-string-nw-p re)
11987 (setq buffer (if (markerp pos)
11988 (marker-buffer pos)
11989 (or (find-buffer-visiting file)
11990 (find-file-noselect file))))
11991 (with-current-buffer buffer
11992 (org-with-wide-buffer
11993 (goto-char pos)
11994 (beginning-of-line 1)
11995 (unless (looking-at-p re)
11996 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11998 (defun org-refile-new-child (parent-target child)
11999 "Use refile target PARENT-TARGET to add new CHILD below it."
12000 (unless parent-target
12001 (error "Cannot find parent for new node"))
12002 (let ((file (nth 1 parent-target))
12003 (pos (nth 3 parent-target))
12004 level)
12005 (with-current-buffer (or (find-buffer-visiting file)
12006 (find-file-noselect file))
12007 (org-with-wide-buffer
12008 (if pos
12009 (goto-char pos)
12010 (goto-char (point-max))
12011 (unless (bolp) (newline)))
12012 (when (looking-at org-outline-regexp)
12013 (setq level (funcall outline-level))
12014 (org-end-of-subtree t t))
12015 (org-back-over-empty-lines)
12016 (insert "\n" (make-string
12017 (if pos (org-get-valid-level level 1) 1) ?*)
12018 " " child "\n")
12019 (beginning-of-line 0)
12020 (list (concat (car parent-target) "/" child) file "" (point))))))
12022 (defun org-olpath-completing-read (prompt collection &rest args)
12023 "Read an outline path like a file name."
12024 (let ((thetable collection))
12025 (apply #'completing-read
12026 prompt
12027 (lambda (string predicate &optional flag)
12028 (cond
12029 ((eq flag nil) (try-completion string thetable))
12030 ((eq flag t)
12031 (let ((l (length string)))
12032 (mapcar (lambda (x)
12033 (let ((r (substring x l))
12034 (f (if (string-match " ([^)]*)$" x)
12035 (match-string 0 x)
12036 "")))
12037 (if (string-match "/" r)
12038 (concat string (substring r 0 (match-end 0)) f)
12039 x)))
12040 (all-completions string thetable predicate))))
12041 ;; Exact match?
12042 ((eq flag 'lambda) (assoc string thetable))))
12043 args)))
12045 ;;;; Dynamic blocks
12047 (defun org-find-dblock (name)
12048 "Find the first dynamic block with name NAME in the buffer.
12049 If not found, stay at current position and return nil."
12050 (let ((case-fold-search t) pos)
12051 (save-excursion
12052 (goto-char (point-min))
12053 (setq pos (and (re-search-forward
12054 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12055 (match-beginning 0))))
12056 (when pos (goto-char pos))
12057 pos))
12059 (defun org-create-dblock (plist)
12060 "Create a dynamic block section, with parameters taken from PLIST.
12061 PLIST must contain a :name entry which is used as the name of the block."
12062 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12063 (end-of-line 1)
12064 (newline))
12065 (let ((col (current-column))
12066 (name (plist-get plist :name)))
12067 (insert "#+BEGIN: " name)
12068 (while plist
12069 (if (eq (car plist) :name)
12070 (setq plist (cddr plist))
12071 (insert " " (prin1-to-string (pop plist)))))
12072 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12073 (beginning-of-line -2)))
12075 (defun org-prepare-dblock ()
12076 "Prepare dynamic block for refresh.
12077 This empties the block, puts the cursor at the insert position and returns
12078 the property list including an extra property :name with the block name."
12079 (unless (looking-at org-dblock-start-re)
12080 (user-error "Not at a dynamic block"))
12081 (let* ((begdel (1+ (match-end 0)))
12082 (name (org-no-properties (match-string 1)))
12083 (params (append (list :name name)
12084 (read (concat "(" (match-string 3) ")")))))
12085 (save-excursion
12086 (beginning-of-line 1)
12087 (skip-chars-forward " \t")
12088 (setq params (plist-put params :indentation-column (current-column))))
12089 (unless (re-search-forward org-dblock-end-re nil t)
12090 (error "Dynamic block not terminated"))
12091 (setq params
12092 (append params
12093 (list :content (buffer-substring
12094 begdel (match-beginning 0)))))
12095 (delete-region begdel (match-beginning 0))
12096 (goto-char begdel)
12097 (open-line 1)
12098 params))
12100 (defun org-map-dblocks (&optional command)
12101 "Apply COMMAND to all dynamic blocks in the current buffer.
12102 If COMMAND is not given, use `org-update-dblock'."
12103 (let ((cmd (or command 'org-update-dblock)))
12104 (save-excursion
12105 (goto-char (point-min))
12106 (while (re-search-forward org-dblock-start-re nil t)
12107 (goto-char (match-beginning 0))
12108 (save-excursion
12109 (condition-case nil
12110 (funcall cmd)
12111 (error (message "Error during update of dynamic block"))))
12112 (unless (re-search-forward org-dblock-end-re nil t)
12113 (error "Dynamic block not terminated"))))))
12115 (defun org-dblock-update (&optional arg)
12116 "User command for updating dynamic blocks.
12117 Update the dynamic block at point. With prefix ARG, update all dynamic
12118 blocks in the buffer."
12119 (interactive "P")
12120 (if arg
12121 (org-update-all-dblocks)
12122 (or (looking-at org-dblock-start-re)
12123 (org-beginning-of-dblock))
12124 (org-update-dblock)))
12126 (defun org-update-dblock ()
12127 "Update the dynamic block at point.
12128 This means to empty the block, parse for parameters and then call
12129 the correct writing function."
12130 (interactive)
12131 (save-excursion
12132 (let* ((win (selected-window))
12133 (pos (point))
12134 (line (org-current-line))
12135 (params (org-prepare-dblock))
12136 (name (plist-get params :name))
12137 (indent (plist-get params :indentation-column))
12138 (cmd (intern (concat "org-dblock-write:" name))))
12139 (message "Updating dynamic block `%s' at line %d..." name line)
12140 (funcall cmd params)
12141 (message "Updating dynamic block `%s' at line %d...done" name line)
12142 (goto-char pos)
12143 (when (and indent (> indent 0))
12144 (setq indent (make-string indent ?\ ))
12145 (save-excursion
12146 (select-window win)
12147 (org-beginning-of-dblock)
12148 (forward-line 1)
12149 (while (not (looking-at org-dblock-end-re))
12150 (insert indent)
12151 (beginning-of-line 2))
12152 (when (looking-at org-dblock-end-re)
12153 (and (looking-at "[ \t]+")
12154 (replace-match ""))
12155 (insert indent)))))))
12157 (defun org-beginning-of-dblock ()
12158 "Find the beginning of the dynamic block at point.
12159 Error if there is no such block at point."
12160 (let ((pos (point))
12161 beg)
12162 (end-of-line 1)
12163 (if (and (re-search-backward org-dblock-start-re nil t)
12164 (setq beg (match-beginning 0))
12165 (re-search-forward org-dblock-end-re nil t)
12166 (> (match-end 0) pos))
12167 (goto-char beg)
12168 (goto-char pos)
12169 (error "Not in a dynamic block"))))
12171 (defun org-update-all-dblocks ()
12172 "Update all dynamic blocks in the buffer.
12173 This function can be used in a hook."
12174 (interactive)
12175 (when (derived-mode-p 'org-mode)
12176 (org-map-dblocks 'org-update-dblock)))
12179 ;;;; Completion
12181 (declare-function org-export-backend-options "ox" (cl-x) t)
12182 (defun org-get-export-keywords ()
12183 "Return a list of all currently understood export keywords.
12184 Export keywords include options, block names, attributes and
12185 keywords relative to each registered export back-end."
12186 (let (keywords)
12187 (dolist (backend
12188 (bound-and-true-p org-export-registered-backends)
12189 (delq nil keywords))
12190 ;; Back-end name (for keywords, like #+LATEX:)
12191 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12192 (dolist (option-entry (org-export-backend-options backend))
12193 ;; Back-end options.
12194 (push (nth 1 option-entry) keywords)))))
12196 (defconst org-options-keywords
12197 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12198 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12199 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12200 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12201 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12203 (defcustom org-structure-template-alist
12204 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12205 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12206 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12207 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12208 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12209 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12210 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12211 ("L" "#+LaTeX: ")
12212 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12213 ("H" "#+HTML: ")
12214 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12215 ("A" "#+ASCII: ")
12216 ("i" "#+INDEX: ?")
12217 ("I" "#+INCLUDE: %file ?"))
12218 "Structure completion elements.
12219 This is a list of abbreviation keys and values. The value gets inserted
12220 if you type `<' followed by the key and then press the completion key,
12221 usually `TAB'. %file will be replaced by a file name after prompting
12222 for the file using completion. The cursor will be placed at the position
12223 of the `?' in the template.
12224 There are two templates for each key, the first uses the original Org syntax,
12225 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12226 the default when the /org-mtags.el/ module has been loaded. See also the
12227 variable `org-mtags-prefer-muse-templates'."
12228 :group 'org-completion
12229 :type '(repeat
12230 (list
12231 (string :tag "Key")
12232 (string :tag "Template")))
12233 :version "26.1"
12234 :package-version '(Org . "8.3"))
12236 (defun org-try-structure-completion ()
12237 "Try to complete a structure template before point.
12238 This looks for strings like \"<e\" on an otherwise empty line and
12239 expands them."
12240 (let ((l (buffer-substring (point-at-bol) (point)))
12242 (when (and (looking-at "[ \t]*$")
12243 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12244 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12245 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12246 (match-beginning 1)) a)
12247 t)))
12249 (defun org-complete-expand-structure-template (start cell)
12250 "Expand a structure template."
12251 (let ((rpl (nth 1 cell))
12252 (ind ""))
12253 (delete-region start (point))
12254 (when (string-match "\\`[ \t]*#\\+" rpl)
12255 (cond
12256 ((bolp))
12257 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12258 (setq ind (buffer-substring (point-at-bol) (point))))
12259 (t (newline))))
12260 (setq start (point))
12261 (when (string-match "%file" rpl)
12262 (setq rpl (replace-match
12263 (concat
12264 "\""
12265 (save-match-data
12266 (abbreviate-file-name (read-file-name "Include file: ")))
12267 "\"")
12268 t t rpl)))
12269 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12270 (concat "\n" ind)))
12271 (insert rpl)
12272 (when (re-search-backward "\\?" start t) (delete-char 1))))
12274 ;;;; TODO, DEADLINE, Comments
12276 (defun org-toggle-comment ()
12277 "Change the COMMENT state of an entry."
12278 (interactive)
12279 (save-excursion
12280 (org-back-to-heading)
12281 (let ((case-fold-search nil))
12282 (looking-at org-complex-heading-regexp))
12283 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12284 (skip-chars-forward " \t")
12285 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12286 (if (org-in-commented-heading-p t)
12287 (delete-region (point)
12288 (progn (search-forward " " (line-end-position) 'move)
12289 (skip-chars-forward " \t")
12290 (point)))
12291 (insert org-comment-string)
12292 (unless (eolp) (insert " ")))))
12294 (defvar org-last-todo-state-is-todo nil
12295 "This is non-nil when the last TODO state change led to a TODO state.
12296 If the last change removed the TODO tag or switched to DONE, then
12297 this is nil.")
12299 (defvar org-setting-tags nil) ; dynamically skipped
12301 (defvar org-todo-setup-filter-hook nil
12302 "Hook for functions that pre-filter todo specs.
12303 Each function takes a todo spec and returns either nil or the spec
12304 transformed into canonical form." )
12306 (defvar org-todo-get-default-hook nil
12307 "Hook for functions that get a default item for todo.
12308 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12309 nil or a string to be used for the todo mark." )
12311 (defvar org-agenda-headline-snapshot-before-repeat)
12313 (defun org-current-effective-time ()
12314 "Return current time adjusted for `org-extend-today-until' variable."
12315 (let* ((ct (org-current-time))
12316 (dct (decode-time ct))
12317 (ct1
12318 (cond
12319 (org-use-last-clock-out-time-as-effective-time
12320 (or (org-clock-get-last-clock-out-time) ct))
12321 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12322 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12323 (t ct))))
12324 ct1))
12326 (defun org-todo-yesterday (&optional arg)
12327 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12328 (interactive "P")
12329 (if (eq major-mode 'org-agenda-mode)
12330 (apply 'org-agenda-todo-yesterday arg)
12331 (let* ((org-use-effective-time t)
12332 (hour (nth 2 (decode-time (org-current-time))))
12333 (org-extend-today-until (1+ hour)))
12334 (org-todo arg))))
12336 (defvar org-block-entry-blocking ""
12337 "First entry preventing the TODO state change.")
12339 (defun org-cancel-repeater ()
12340 "Cancel a repeater by setting its numeric value to zero."
12341 (interactive)
12342 (save-excursion
12343 (org-back-to-heading t)
12344 (let ((bound1 (point))
12345 (bound0 (save-excursion (outline-next-heading) (point))))
12346 (when (and (re-search-forward
12347 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12348 org-deadline-time-regexp "\\)\\|\\("
12349 org-ts-regexp "\\)")
12350 bound0 t)
12351 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12352 bound1 t))
12353 (replace-match "0" t nil nil 1)))))
12355 (defvar org-state)
12356 (defvar org-blocked-by-checkboxes)
12357 (defun org-todo (&optional arg)
12358 "Change the TODO state of an item.
12360 The state of an item is given by a keyword at the start of the heading,
12361 like
12362 *** TODO Write paper
12363 *** DONE Call mom
12365 The different keywords are specified in the variable `org-todo-keywords'.
12366 By default the available states are \"TODO\" and \"DONE\". So, for this
12367 example: when the item starts with TODO, it is changed to DONE.
12368 When it starts with DONE, the DONE is removed. And when neither TODO nor
12369 DONE are present, add TODO at the beginning of the heading.
12371 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12372 state.
12373 With numeric prefix ARG, switch to that state.
12374 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12375 next set of TODO \
12376 keywords (nextset).
12377 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12378 prefix, circumvent any state blocking.
12379 With a numeric prefix arg of 0, inhibit note taking for the change.
12380 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12382 When called through ELisp, arg is also interpreted in the following way:
12383 `none' -> empty state
12384 \"\" -> switch to empty state
12385 `done' -> switch to DONE
12386 `nextset' -> switch to the next set of keywords
12387 `previousset' -> switch to the previous set of keywords
12388 \"WAITING\" -> switch to the specified keyword, but only if it
12389 really is a member of `org-todo-keywords'."
12390 (interactive "P")
12391 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12392 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12393 'region-start-level 'region))
12394 org-loop-over-headlines-in-active-region)
12395 (org-map-entries
12396 `(org-todo ,arg)
12397 org-loop-over-headlines-in-active-region
12398 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12399 (when (equal arg '(16)) (setq arg 'nextset))
12400 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12401 (let ((org-blocker-hook org-blocker-hook)
12402 commentp
12403 case-fold-search)
12404 (when (equal arg '(64))
12405 (setq arg nil org-blocker-hook nil))
12406 (when (and org-blocker-hook
12407 (or org-inhibit-blocking
12408 (org-entry-get nil "NOBLOCKING")))
12409 (setq org-blocker-hook nil))
12410 (save-excursion
12411 (catch 'exit
12412 (org-back-to-heading t)
12413 (when (org-in-commented-heading-p t)
12414 (org-toggle-comment)
12415 (setq commentp t))
12416 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12417 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12418 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12419 (let* ((match-data (match-data))
12420 (startpos (point-at-bol))
12421 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12422 (org-log-done org-log-done)
12423 (org-log-repeat org-log-repeat)
12424 (org-todo-log-states org-todo-log-states)
12425 (org-inhibit-logging
12426 (if (equal arg 0)
12427 (progn (setq arg nil) 'note) org-inhibit-logging))
12428 (this (match-string 1))
12429 (hl-pos (match-beginning 0))
12430 (head (org-get-todo-sequence-head this))
12431 (ass (assoc head org-todo-kwd-alist))
12432 (interpret (nth 1 ass))
12433 (done-word (nth 3 ass))
12434 (final-done-word (nth 4 ass))
12435 (org-last-state (or this ""))
12436 (completion-ignore-case t)
12437 (member (member this org-todo-keywords-1))
12438 (tail (cdr member))
12439 (org-state (cond
12440 ((and org-todo-key-trigger
12441 (or (and (equal arg '(4))
12442 (eq org-use-fast-todo-selection 'prefix))
12443 (and (not arg) org-use-fast-todo-selection
12444 (not (eq org-use-fast-todo-selection
12445 'prefix)))))
12446 ;; Use fast selection.
12447 (org-fast-todo-selection))
12448 ((and (equal arg '(4))
12449 (or (not org-use-fast-todo-selection)
12450 (not org-todo-key-trigger)))
12451 ;; Read a state with completion.
12452 (completing-read
12453 "State: " (mapcar #'list org-todo-keywords-1)
12454 nil t))
12455 ((eq arg 'right)
12456 (if this
12457 (if tail (car tail) nil)
12458 (car org-todo-keywords-1)))
12459 ((eq arg 'left)
12460 (unless (equal member org-todo-keywords-1)
12461 (if this
12462 (nth (- (length org-todo-keywords-1)
12463 (length tail) 2)
12464 org-todo-keywords-1)
12465 (org-last org-todo-keywords-1))))
12466 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12467 (setq arg nil))) ;hack to fall back to cycling
12468 (arg
12469 ;; User or caller requests a specific state.
12470 (cond
12471 ((equal arg "") nil)
12472 ((eq arg 'none) nil)
12473 ((eq arg 'done) (or done-word (car org-done-keywords)))
12474 ((eq arg 'nextset)
12475 (or (car (cdr (member head org-todo-heads)))
12476 (car org-todo-heads)))
12477 ((eq arg 'previousset)
12478 (let ((org-todo-heads (reverse org-todo-heads)))
12479 (or (car (cdr (member head org-todo-heads)))
12480 (car org-todo-heads))))
12481 ((car (member arg org-todo-keywords-1)))
12482 ((stringp arg)
12483 (user-error "State `%s' not valid in this file" arg))
12484 ((nth (1- (prefix-numeric-value arg))
12485 org-todo-keywords-1))))
12486 ((null member) (or head (car org-todo-keywords-1)))
12487 ((equal this final-done-word) nil) ;-> make empty
12488 ((null tail) nil) ;-> first entry
12489 ((memq interpret '(type priority))
12490 (if (eq this-command last-command)
12491 (car tail)
12492 (if (> (length tail) 0)
12493 (or done-word (car org-done-keywords))
12494 nil)))
12496 (car tail))))
12497 (org-state (or
12498 (run-hook-with-args-until-success
12499 'org-todo-get-default-hook org-state org-last-state)
12500 org-state))
12501 (next (if org-state (concat " " org-state " ") " "))
12502 (change-plist (list :type 'todo-state-change :from this :to org-state
12503 :position startpos))
12504 dolog now-done-p)
12505 (when org-blocker-hook
12506 (let (org-blocked-by-checkboxes block-reason)
12507 (setq org-last-todo-state-is-todo
12508 (not (member this org-done-keywords)))
12509 (unless (save-excursion
12510 (save-match-data
12511 (org-with-wide-buffer
12512 (run-hook-with-args-until-failure
12513 'org-blocker-hook change-plist))))
12514 (setq block-reason (if org-blocked-by-checkboxes
12515 "contained checkboxes"
12516 (format "\"%s\"" org-block-entry-blocking)))
12517 (if (called-interactively-p 'interactive)
12518 (user-error "TODO state change from %s to %s blocked (by %s)"
12519 this org-state block-reason)
12520 ;; Fail silently.
12521 (message "TODO state change from %s to %s blocked (by %s)"
12522 this org-state block-reason)
12523 (throw 'exit nil)))))
12524 (store-match-data match-data)
12525 (replace-match next t t)
12526 (cond ((equal this org-state)
12527 (message "TODO state was already %s" (org-trim next)))
12528 ((not (pos-visible-in-window-p hl-pos))
12529 (message "TODO state changed to %s" (org-trim next))))
12530 (unless head
12531 (setq head (org-get-todo-sequence-head org-state)
12532 ass (assoc head org-todo-kwd-alist)
12533 interpret (nth 1 ass)
12534 done-word (nth 3 ass)
12535 final-done-word (nth 4 ass)))
12536 (when (memq arg '(nextset previousset))
12537 (message "Keyword-Set %d/%d: %s"
12538 (- (length org-todo-sets) -1
12539 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12540 (length org-todo-sets)
12541 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12542 (setq org-last-todo-state-is-todo
12543 (not (member org-state org-done-keywords)))
12544 (setq now-done-p (and (member org-state org-done-keywords)
12545 (not (member this org-done-keywords))))
12546 (and logging (org-local-logging logging))
12547 (when (and (or org-todo-log-states org-log-done)
12548 (not (eq org-inhibit-logging t))
12549 (not (memq arg '(nextset previousset))))
12550 ;; We need to look at recording a time and note.
12551 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12552 (nth 2 (assoc this org-todo-log-states))))
12553 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12554 (setq dolog 'time))
12555 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12556 (and org-state
12557 (member org-state org-not-done-keywords)
12558 (not (member this org-not-done-keywords))))
12559 ;; This is now a todo state and was not one before
12560 ;; If there was a CLOSED time stamp, get rid of it.
12561 (org-add-planning-info nil nil 'closed))
12562 (when (and now-done-p org-log-done)
12563 ;; It is now done, and it was not done before.
12564 (org-add-planning-info 'closed (org-current-effective-time))
12565 (when (and (not dolog) (eq 'note org-log-done))
12566 (org-add-log-setup 'done org-state this 'note)))
12567 (when (and org-state dolog)
12568 ;; This is a non-nil state, and we need to log it.
12569 (org-add-log-setup 'state org-state this dolog)))
12570 ;; Fixup tag positioning.
12571 (org-todo-trigger-tag-changes org-state)
12572 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12573 (when org-provide-todo-statistics
12574 (org-update-parent-todo-statistics))
12575 (run-hooks 'org-after-todo-state-change-hook)
12576 (when (and arg (not (member org-state org-done-keywords)))
12577 (setq head (org-get-todo-sequence-head org-state)))
12578 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12579 ;; Do we need to trigger a repeat?
12580 (when now-done-p
12581 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12582 ;; This is for the agenda, take a snapshot of the headline.
12583 (save-match-data
12584 (setq org-agenda-headline-snapshot-before-repeat
12585 (org-get-heading))))
12586 (org-auto-repeat-maybe org-state))
12587 ;; Fixup cursor location if close to the keyword.
12588 (when (and (outline-on-heading-p)
12589 (not (bolp))
12590 (save-excursion (beginning-of-line 1)
12591 (looking-at org-todo-line-regexp))
12592 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12593 (goto-char (or (match-end 2) (match-end 1)))
12594 (and (looking-at " ") (just-one-space)))
12595 (when org-trigger-hook
12596 (save-excursion
12597 (run-hook-with-args 'org-trigger-hook change-plist)))
12598 (when commentp (org-toggle-comment))))))))
12600 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12601 "Block turning an entry into a TODO, using the hierarchy.
12602 This checks whether the current task should be blocked from state
12603 changes. Such blocking occurs when:
12605 1. The task has children which are not all in a completed state.
12607 2. A task has a parent with the property :ORDERED:, and there
12608 are siblings prior to the current task with incomplete
12609 status.
12611 3. The parent of the task is blocked because it has siblings that should
12612 be done first, or is child of a block grandparent TODO entry."
12614 (if (not org-enforce-todo-dependencies)
12615 t ; if locally turned off don't block
12616 (catch 'dont-block
12617 ;; If this is not a todo state change, or if this entry is already DONE,
12618 ;; do not block
12619 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12620 (member (plist-get change-plist :from)
12621 (cons 'done org-done-keywords))
12622 (member (plist-get change-plist :to)
12623 (cons 'todo org-not-done-keywords))
12624 (not (plist-get change-plist :to)))
12625 (throw 'dont-block t))
12626 ;; If this task has children, and any are undone, it's blocked
12627 (save-excursion
12628 (org-back-to-heading t)
12629 (let ((this-level (funcall outline-level)))
12630 (outline-next-heading)
12631 (let ((child-level (funcall outline-level)))
12632 (while (and (not (eobp))
12633 (> child-level this-level))
12634 ;; this todo has children, check whether they are all
12635 ;; completed
12636 (when (and (not (org-entry-is-done-p))
12637 (org-entry-is-todo-p))
12638 (setq org-block-entry-blocking (org-get-heading))
12639 (throw 'dont-block nil))
12640 (outline-next-heading)
12641 (setq child-level (funcall outline-level))))))
12642 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12643 ;; any previous siblings are undone, it's blocked
12644 (save-excursion
12645 (org-back-to-heading t)
12646 (let* ((pos (point))
12647 (parent-pos (and (org-up-heading-safe) (point)))
12648 (case-fold-search nil))
12649 (unless parent-pos (throw 'dont-block t)) ; no parent
12650 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12651 (forward-line 1)
12652 (re-search-forward org-not-done-heading-regexp pos t))
12653 (setq org-block-entry-blocking (match-string 0))
12654 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12655 ;; Search further up the hierarchy, to see if an ancestor is blocked
12656 (while t
12657 (goto-char parent-pos)
12658 (unless (looking-at org-not-done-heading-regexp)
12659 (throw 'dont-block t)) ; do not block, parent is not a TODO
12660 (setq pos (point))
12661 (setq parent-pos (and (org-up-heading-safe) (point)))
12662 (unless parent-pos (throw 'dont-block t)) ; no parent
12663 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12664 (forward-line 1)
12665 (re-search-forward org-not-done-heading-regexp pos t)
12666 (setq org-block-entry-blocking (org-get-heading)))
12667 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12669 (defcustom org-track-ordered-property-with-tag nil
12670 "Should the ORDERED property also be shown as a tag?
12671 The ORDERED property decides if an entry should require subtasks to be
12672 completed in sequence. Since a property is not very visible, setting
12673 this option means that toggling the ORDERED property with the command
12674 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12675 not relevant for the behavior, but it makes things more visible.
12677 Note that toggling the tag with tags commands will not change the property
12678 and therefore not influence behavior!
12680 This can be t, meaning the tag ORDERED should be used, It can also be a
12681 string to select a different tag for this task."
12682 :group 'org-todo
12683 :type '(choice
12684 (const :tag "No tracking" nil)
12685 (const :tag "Track with ORDERED tag" t)
12686 (string :tag "Use other tag")))
12688 (defun org-toggle-ordered-property ()
12689 "Toggle the ORDERED property of the current entry.
12690 For better visibility, you can track the value of this property with a tag.
12691 See variable `org-track-ordered-property-with-tag'."
12692 (interactive)
12693 (let* ((t1 org-track-ordered-property-with-tag)
12694 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12695 (save-excursion
12696 (org-back-to-heading)
12697 (if (org-entry-get nil "ORDERED")
12698 (progn
12699 (org-delete-property "ORDERED")
12700 (and tag (org-toggle-tag tag 'off))
12701 (message "Subtasks can be completed in arbitrary order"))
12702 (org-entry-put nil "ORDERED" "t")
12703 (and tag (org-toggle-tag tag 'on))
12704 (message "Subtasks must be completed in sequence")))))
12706 (defun org-block-todo-from-checkboxes (change-plist)
12707 "Block turning an entry into a TODO, using checkboxes.
12708 This checks whether the current task should be blocked from state
12709 changes because there are unchecked boxes in this entry."
12710 (if (not org-enforce-todo-checkbox-dependencies)
12711 t ; if locally turned off don't block
12712 (catch 'dont-block
12713 ;; If this is not a todo state change, or if this entry is already DONE,
12714 ;; do not block
12715 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12716 (member (plist-get change-plist :from)
12717 (cons 'done org-done-keywords))
12718 (member (plist-get change-plist :to)
12719 (cons 'todo org-not-done-keywords))
12720 (not (plist-get change-plist :to)))
12721 (throw 'dont-block t))
12722 ;; If this task has checkboxes that are not checked, it's blocked
12723 (save-excursion
12724 (org-back-to-heading t)
12725 (let ((beg (point)) end)
12726 (outline-next-heading)
12727 (setq end (point))
12728 (goto-char beg)
12729 (when (org-list-search-forward
12730 (concat (org-item-beginning-re)
12731 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12732 "\\[[- ]\\]")
12733 end t)
12734 (when (boundp 'org-blocked-by-checkboxes)
12735 (setq org-blocked-by-checkboxes t))
12736 (throw 'dont-block nil))))
12737 t))) ; do not block
12739 (defun org-entry-blocked-p ()
12740 "Non-nil if entry at point is blocked."
12741 (and (not (org-entry-get nil "NOBLOCKING"))
12742 (member (org-entry-get nil "TODO") org-not-done-keywords)
12743 (not (run-hook-with-args-until-failure
12744 'org-blocker-hook
12745 (list :type 'todo-state-change
12746 :position (point)
12747 :from 'todo
12748 :to 'done)))))
12750 (defun org-update-statistics-cookies (all)
12751 "Update the statistics cookie, either from TODO or from checkboxes.
12752 This should be called with the cursor in a line with a statistics
12753 cookie. When called with a \\[universal-argument] prefix, update
12754 all statistics cookies in the buffer."
12755 (interactive "P")
12756 (if all
12757 (progn
12758 (org-update-checkbox-count 'all)
12759 (org-map-entries 'org-update-parent-todo-statistics))
12760 (if (not (org-at-heading-p))
12761 (org-update-checkbox-count)
12762 (let ((pos (point-marker))
12763 end l1 l2)
12764 (ignore-errors (org-back-to-heading t))
12765 (if (not (org-at-heading-p))
12766 (org-update-checkbox-count)
12767 (setq l1 (org-outline-level))
12768 (setq end (save-excursion
12769 (outline-next-heading)
12770 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12771 (point)))
12772 (if (and (save-excursion
12773 (re-search-forward
12774 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12775 (not (save-excursion (re-search-forward
12776 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12777 (org-update-checkbox-count)
12778 (if (and l2 (> l2 l1))
12779 (progn
12780 (goto-char end)
12781 (org-update-parent-todo-statistics))
12782 (goto-char pos)
12783 (beginning-of-line 1)
12784 (while (re-search-forward
12785 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12786 (point-at-eol) t)
12787 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12788 (goto-char pos)
12789 (move-marker pos nil)))))
12791 (defvar org-entry-property-inherited-from) ;; defined below
12792 (defun org-update-parent-todo-statistics ()
12793 "Update any statistics cookie in the parent of the current headline.
12794 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12795 the entire subtree and this will travel up the hierarchy and update
12796 statistics everywhere."
12797 (let* ((prop (save-excursion (org-up-heading-safe)
12798 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12799 (recursive (or (not org-hierarchical-todo-statistics)
12800 (and prop (string-match "\\<recursive\\>" prop))))
12801 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12803 (first t)
12804 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12805 level ltoggle l1 new ndel
12806 (cnt-all 0) (cnt-done 0) is-percent kwd
12807 checkbox-beg cookie-present)
12808 (catch 'exit
12809 (save-excursion
12810 (beginning-of-line 1)
12811 (setq ltoggle (funcall outline-level))
12812 ;; Three situations are to consider:
12814 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12815 ;; to the top-level ancestor on the headline;
12817 ;; 2. If parent has "recursive" property, repeat up to the
12818 ;; headline setting that property, taking inheritance into
12819 ;; account;
12821 ;; 3. Else, move up to direct parent and proceed only once.
12822 (while (and (setq level (org-up-heading-safe))
12823 (or recursive first)
12824 (>= (point) lim))
12825 (setq first nil cookie-present nil)
12826 (unless (and level
12827 (not (string-match
12828 "\\<checkbox\\>"
12829 (downcase (or (org-entry-get nil "COOKIE_DATA")
12830 "")))))
12831 (throw 'exit nil))
12832 (while (re-search-forward box-re (point-at-eol) t)
12833 (setq cnt-all 0 cnt-done 0 cookie-present t)
12834 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12835 (save-match-data
12836 (unless (outline-next-heading) (throw 'exit nil))
12837 (while (and (looking-at org-complex-heading-regexp)
12838 (> (setq l1 (length (match-string 1))) level))
12839 (setq kwd (and (or recursive (= l1 ltoggle))
12840 (match-string 2)))
12841 (if (or (eq org-provide-todo-statistics 'all-headlines)
12842 (and (eq org-provide-todo-statistics t)
12843 (or (member kwd org-done-keywords)))
12844 (and (listp org-provide-todo-statistics)
12845 (stringp (car org-provide-todo-statistics))
12846 (or (member kwd org-provide-todo-statistics)
12847 (member kwd org-done-keywords)))
12848 (and (listp org-provide-todo-statistics)
12849 (listp (car org-provide-todo-statistics))
12850 (or (member kwd (car org-provide-todo-statistics))
12851 (and (member kwd org-done-keywords)
12852 (member kwd (cadr org-provide-todo-statistics))))))
12853 (setq cnt-all (1+ cnt-all))
12854 (and (eq org-provide-todo-statistics t)
12856 (setq cnt-all (1+ cnt-all))))
12857 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12858 (member kwd org-done-keywords))
12859 (and (listp org-provide-todo-statistics)
12860 (listp (car org-provide-todo-statistics))
12861 (member kwd org-done-keywords)
12862 (member kwd (cadr org-provide-todo-statistics)))
12863 (and (listp org-provide-todo-statistics)
12864 (stringp (car org-provide-todo-statistics))
12865 (member kwd org-done-keywords)))
12866 (setq cnt-done (1+ cnt-done)))
12867 (outline-next-heading)))
12868 (setq new
12869 (if is-percent
12870 (format "[%d%%]" (floor (* 100.0 cnt-done)
12871 (max 1 cnt-all)))
12872 (format "[%d/%d]" cnt-done cnt-all))
12873 ndel (- (match-end 0) checkbox-beg))
12874 (goto-char checkbox-beg)
12875 (insert new)
12876 (delete-region (point) (+ (point) ndel))
12877 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12878 (when cookie-present
12879 (run-hook-with-args 'org-after-todo-statistics-hook
12880 cnt-done (- cnt-all cnt-done))))))
12881 (run-hooks 'org-todo-statistics-hook)))
12883 (defvar org-after-todo-statistics-hook nil
12884 "Hook that is called after a TODO statistics cookie has been updated.
12885 Each function is called with two arguments: the number of not-done entries
12886 and the number of done entries.
12888 For example, the following function, when added to this hook, will switch
12889 an entry to DONE when all children are done, and back to TODO when new
12890 entries are set to a TODO status. Note that this hook is only called
12891 when there is a statistics cookie in the headline!
12893 (defun org-summary-todo (n-done n-not-done)
12894 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12895 (let (org-log-done org-log-states) ; turn off logging
12896 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12899 (defvar org-todo-statistics-hook nil
12900 "Hook that is run whenever Org thinks TODO statistics should be updated.
12901 This hook runs even if there is no statistics cookie present, in which case
12902 `org-after-todo-statistics-hook' would not run.")
12904 (defun org-todo-trigger-tag-changes (state)
12905 "Apply the changes defined in `org-todo-state-tags-triggers'."
12906 (let ((l org-todo-state-tags-triggers)
12907 changes)
12908 (when (or (not state) (equal state ""))
12909 (setq changes (append changes (cdr (assoc "" l)))))
12910 (when (and (stringp state) (> (length state) 0))
12911 (setq changes (append changes (cdr (assoc state l)))))
12912 (when (member state org-not-done-keywords)
12913 (setq changes (append changes (cdr (assq 'todo l)))))
12914 (when (member state org-done-keywords)
12915 (setq changes (append changes (cdr (assq 'done l)))))
12916 (dolist (c changes)
12917 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12919 (defun org-local-logging (value)
12920 "Get logging settings from a property VALUE."
12921 ;; Directly set the variables, they are already local.
12922 (setq org-log-done nil
12923 org-log-repeat nil
12924 org-todo-log-states nil)
12925 (dolist (w (org-split-string value))
12926 (let (a)
12927 (cond
12928 ((setq a (assoc w org-startup-options))
12929 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12930 (set (nth 1 a) (nth 2 a))))
12931 ((setq a (org-extract-log-state-settings w))
12932 (and (member (car a) org-todo-keywords-1)
12933 (push a org-todo-log-states)))))))
12935 (defun org-get-todo-sequence-head (kwd)
12936 "Return the head of the TODO sequence to which KWD belongs.
12937 If KWD is not set, check if there is a text property remembering the
12938 right sequence."
12939 (let (p)
12940 (cond
12941 ((not kwd)
12942 (or (get-text-property (point-at-bol) 'org-todo-head)
12943 (progn
12944 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12945 nil (point-at-eol)))
12946 (get-text-property p 'org-todo-head))))
12947 ((not (member kwd org-todo-keywords-1))
12948 (car org-todo-keywords-1))
12949 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12951 (defun org-fast-todo-selection ()
12952 "Fast TODO keyword selection with single keys.
12953 Returns the new TODO keyword, or nil if no state change should occur."
12954 (let* ((fulltable org-todo-key-alist)
12955 (done-keywords org-done-keywords) ;; needed for the faces.
12956 (maxlen (apply 'max (mapcar
12957 (lambda (x)
12958 (if (stringp (car x)) (string-width (car x)) 0))
12959 fulltable)))
12960 (expert nil)
12961 (fwidth (+ maxlen 3 1 3))
12962 (ncol (/ (- (window-width) 4) fwidth))
12963 tg cnt e c tbl
12964 groups ingroup)
12965 (save-excursion
12966 (save-window-excursion
12967 (if expert
12968 (set-buffer (get-buffer-create " *Org todo*"))
12969 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12970 (erase-buffer)
12971 (setq-local org-done-keywords done-keywords)
12972 (setq tbl fulltable cnt 0)
12973 (while (setq e (pop tbl))
12974 (cond
12975 ((equal e '(:startgroup))
12976 (push '() groups) (setq ingroup t)
12977 (unless (= cnt 0)
12978 (setq cnt 0)
12979 (insert "\n"))
12980 (insert "{ "))
12981 ((equal e '(:endgroup))
12982 (setq ingroup nil cnt 0)
12983 (insert "}\n"))
12984 ((equal e '(:newline))
12985 (unless (= cnt 0)
12986 (setq cnt 0)
12987 (insert "\n")
12988 (setq e (car tbl))
12989 (while (equal (car tbl) '(:newline))
12990 (insert "\n")
12991 (setq tbl (cdr tbl)))))
12993 (setq tg (car e) c (cdr e))
12994 (when ingroup (push tg (car groups)))
12995 (setq tg (org-add-props tg nil 'face
12996 (org-get-todo-face tg)))
12997 (when (and (= cnt 0) (not ingroup)) (insert " "))
12998 (insert "[" c "] " tg (make-string
12999 (- fwidth 4 (length tg)) ?\ ))
13000 (when (= (setq cnt (1+ cnt)) ncol)
13001 (insert "\n")
13002 (when ingroup (insert " "))
13003 (setq cnt 0)))))
13004 (insert "\n")
13005 (goto-char (point-min))
13006 (unless expert (org-fit-window-to-buffer))
13007 (message "[a-z..]:Set [SPC]:clear")
13008 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13009 (cond
13010 ((or (= c ?\C-g)
13011 (and (= c ?q) (not (rassoc c fulltable))))
13012 (setq quit-flag t))
13013 ((= c ?\ ) nil)
13014 ((setq e (rassoc c fulltable) tg (car e))
13016 (t (setq quit-flag t)))))))
13018 (defun org-entry-is-todo-p ()
13019 (member (org-get-todo-state) org-not-done-keywords))
13021 (defun org-entry-is-done-p ()
13022 (member (org-get-todo-state) org-done-keywords))
13024 (defun org-get-todo-state ()
13025 "Return the TODO keyword of the current subtree."
13026 (save-excursion
13027 (org-back-to-heading t)
13028 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13029 (match-end 2)
13030 (match-string 2))))
13032 (defun org-at-date-range-p (&optional inactive-ok)
13033 "Non-nil if point is inside a date range.
13035 When optional argument INACTIVE-OK is non-nil, also consider
13036 inactive time ranges.
13038 When this function returns a non-nil value, match data is set
13039 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13040 on INACTIVE-OK."
13041 (interactive)
13042 (save-excursion
13043 (catch 'exit
13044 (let ((pos (point)))
13045 (skip-chars-backward "^[<\r\n")
13046 (skip-chars-backward "<[")
13047 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13048 (>= (match-end 0) pos)
13049 (throw 'exit t))
13050 (skip-chars-backward "^<[\r\n")
13051 (skip-chars-backward "<[")
13052 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13053 (>= (match-end 0) pos)
13054 (throw 'exit t)))
13055 nil)))
13057 (defun org-get-repeat (&optional timestamp)
13058 "Check if there is a time-stamp with repeater in this entry.
13060 Return the repeater, as a string, or nil. Also return nil when
13061 this function is called before first heading.
13063 When optional argument TIMESTAMP is a string, extract the
13064 repeater from there instead."
13065 (save-match-data
13066 (cond (timestamp
13067 (and (string-match org-repeat-re timestamp)
13068 (match-string-no-properties 1 timestamp)))
13069 ((org-before-first-heading-p) nil)
13071 (save-excursion
13072 (org-back-to-heading t)
13073 (let ((end (org-entry-end-position)))
13074 (catch :repeat
13075 (while (re-search-forward org-repeat-re end t)
13076 (when (save-match-data (org-at-timestamp-p 'agenda))
13077 (throw :repeat (match-string-no-properties 1)))))))))))
13079 (defvar org-last-changed-timestamp)
13080 (defvar org-last-inserted-timestamp)
13081 (defvar org-log-post-message)
13082 (defvar org-log-note-purpose)
13083 (defvar org-log-note-how nil)
13084 (defvar org-log-note-extra)
13085 (defun org-auto-repeat-maybe (done-word)
13086 "Check if the current headline contains a repeated time-stamp.
13088 If yes, set TODO state back to what it was and change the base date
13089 of repeating deadline/scheduled time stamps to new date.
13091 This function is run automatically after each state change to a DONE state."
13092 (let* ((repeat (org-get-repeat))
13093 (aa (assoc org-last-state org-todo-kwd-alist))
13094 (interpret (nth 1 aa))
13095 (head (nth 2 aa))
13096 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13097 (msg "Entry repeats: ")
13098 (org-log-done nil)
13099 (org-todo-log-states nil)
13100 (end (copy-marker (org-entry-end-position))))
13101 (unwind-protect
13102 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13103 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13104 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13105 org-todo-repeat-to-state)))
13106 (org-todo (cond
13107 ((and to-state (member to-state org-todo-keywords-1))
13108 to-state)
13109 ((eq interpret 'type) org-last-state)
13110 (head)
13111 (t 'none))))
13112 (org-back-to-heading t)
13113 (org-add-planning-info nil nil 'closed)
13114 ;; When `org-log-repeat' is non-nil or entry contains
13115 ;; a clock, set LAST_REPEAT property.
13116 (when (or org-log-repeat
13117 (catch :clock
13118 (while (re-search-forward org-clock-line-re end t)
13119 (when (org-at-clock-log-p) (throw :clock t)))))
13120 (org-entry-put nil "LAST_REPEAT" (format-time-string
13121 (org-time-stamp-format t t)
13122 (current-time))))
13123 (when org-log-repeat
13124 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13125 (memq 'org-add-log-note post-command-hook))
13126 ;; We are already setup for some record.
13127 (when (eq org-log-repeat 'note)
13128 ;; Make sure we take a note, not only a time stamp.
13129 (setq org-log-note-how 'note))
13130 ;; Set up for taking a record.
13131 (org-add-log-setup 'state
13132 (or done-word (car org-done-keywords))
13133 org-last-state
13134 org-log-repeat)))
13135 (let ((planning-re (regexp-opt
13136 (list org-scheduled-string org-deadline-string))))
13137 (while (re-search-forward org-ts-regexp end t)
13138 (let* ((ts (match-string 0))
13139 (planning? (org-at-planning-p))
13140 (type (if (not planning?) "Plain:"
13141 (save-excursion
13142 (re-search-backward
13143 planning-re (line-beginning-position) t)
13144 (match-string 0)))))
13145 (cond
13146 ;; Ignore fake time-stamps (e.g., within comments).
13147 ((not (org-at-timestamp-p 'agenda)))
13148 ;; Time-stamps without a repeater are usually
13149 ;; skipped. However, a SCHEDULED time-stamp without
13150 ;; one is removed, as they are no longer relevant.
13151 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13152 ts))
13153 (when (equal type org-scheduled-string)
13154 (org-remove-timestamp-with-keyword type)))
13156 (let ((n (string-to-number (match-string 2 ts)))
13157 (what (match-string 3 ts)))
13158 (when (equal what "w") (setq n (* n 7) what "d"))
13159 (when (and (equal what "h")
13160 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13161 ts)))
13162 (user-error
13163 "Cannot repeat in Repeat in %d hour(s) because no hour \
13164 has been set"
13166 ;; Preparation, see if we need to modify the start
13167 ;; date for the change.
13168 (when (match-end 1)
13169 (let ((time (save-match-data
13170 (org-time-string-to-time ts))))
13171 (cond
13172 ((equal (match-string 1 ts) ".")
13173 ;; Shift starting date to today
13174 (org-timestamp-change
13175 (- (org-today) (time-to-days time))
13176 'day))
13177 ((equal (match-string 1 ts) "+")
13178 (let ((nshiftmax 10)
13179 (nshift 0))
13180 (while (or (= nshift 0)
13181 (not (time-less-p (current-time) time)))
13182 (when (= (cl-incf nshift) nshiftmax)
13183 (or (y-or-n-p
13184 (format "%d repeater intervals were not \
13185 enough to shift date past today. Continue? "
13186 nshift))
13187 (user-error "Abort")))
13188 (org-timestamp-change n (cdr (assoc what whata)))
13189 (org-in-regexp org-ts-regexp3)
13190 (setq ts (match-string 1))
13191 (setq time
13192 (save-match-data
13193 (org-time-string-to-time ts)))))
13194 (org-timestamp-change (- n) (cdr (assoc what whata)))
13195 ;; Rematch, so that we have everything in place
13196 ;; for the real shift.
13197 (org-in-regexp org-ts-regexp3)
13198 (setq ts (match-string 1))
13199 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13200 ts)))))
13201 (save-excursion
13202 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13203 (setq msg
13204 (concat
13205 msg type " " org-last-changed-timestamp " "))))))))
13206 (setq org-log-post-message msg)
13207 (message "%s" msg))
13208 (set-marker end nil))))
13210 (defun org-show-todo-tree (arg)
13211 "Make a compact tree which shows all headlines marked with TODO.
13212 The tree will show the lines where the regexp matches, and all higher
13213 headlines above the match.
13214 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13215 With a numeric prefix N, construct a sparse tree for the Nth element
13216 of `org-todo-keywords-1'."
13217 (interactive "P")
13218 (let ((case-fold-search nil)
13219 (kwd-re
13220 (cond ((null arg) org-not-done-regexp)
13221 ((equal arg '(4))
13222 (let ((kwd
13223 (completing-read "Keyword (or KWD1|KWD2|...): "
13224 (mapcar #'list org-todo-keywords-1))))
13225 (concat "\\("
13226 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13227 "\\)\\>")))
13228 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13229 (regexp-quote (nth (1- (prefix-numeric-value arg))
13230 org-todo-keywords-1)))
13231 (t (user-error "Invalid prefix argument: %s" arg)))))
13232 (message "%d TODO entries found"
13233 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13235 (defun org--deadline-or-schedule (arg type time)
13236 "Insert DEADLINE or SCHEDULE information in current entry.
13237 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13238 `org-schedule' for information about ARG and TIME arguments."
13239 (let* ((deadline? (eq type 'deadline))
13240 (keyword (if deadline? org-deadline-string org-scheduled-string))
13241 (log (if deadline? org-log-redeadline org-log-reschedule))
13242 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13243 (old-date-time (and old-date (org-time-string-to-time old-date)))
13244 ;; Save repeater cookie from either TIME or current scheduled
13245 ;; time stamp. We are going to insert it back at the end of
13246 ;; the process.
13247 (repeater (or (and (org-string-nw-p time)
13248 ;; We use `org-repeat-re' because we need
13249 ;; to tell the difference between a real
13250 ;; repeater and a time delta, e.g. "+2d".
13251 (string-match org-repeat-re time)
13252 (match-string 1 time))
13253 (and (org-string-nw-p old-date)
13254 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13255 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13256 old-date)
13257 (match-string 1 old-date)))))
13258 (pcase arg
13259 (`(4)
13260 (when (and old-date log)
13261 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13262 nil old-date log))
13263 (org-remove-timestamp-with-keyword keyword)
13264 (message (if deadline? "Item no longer has a deadline."
13265 "Item is no longer scheduled.")))
13266 (`(16)
13267 (save-excursion
13268 (org-back-to-heading t)
13269 (let ((regexp (if deadline? org-deadline-time-regexp
13270 org-scheduled-time-regexp)))
13271 (if (not (re-search-forward regexp (line-end-position 2) t))
13272 (user-error (if deadline? "No deadline information to update"
13273 "No scheduled information to update"))
13274 (let* ((rpl0 (match-string 1))
13275 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13276 (msg (if deadline? "Warn starting from" "Delay until")))
13277 (replace-match
13278 (concat keyword
13279 " <" rpl
13280 (format " -%dd"
13281 (abs (- (time-to-days
13282 (save-match-data
13283 (org-read-date
13284 nil t nil msg old-date-time)))
13285 (time-to-days old-date-time))))
13286 ">") t t))))))
13288 (org-add-planning-info type time 'closed)
13289 (when (and old-date
13291 (not (equal old-date org-last-inserted-timestamp)))
13292 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13293 org-last-inserted-timestamp
13294 old-date
13295 log))
13296 (when repeater
13297 (save-excursion
13298 (org-back-to-heading t)
13299 (when (re-search-forward
13300 (concat keyword " " org-last-inserted-timestamp)
13301 (line-end-position 2)
13303 (goto-char (1- (match-end 0)))
13304 (insert " " repeater)
13305 (setq org-last-inserted-timestamp
13306 (concat (substring org-last-inserted-timestamp 0 -1)
13307 " " repeater
13308 (substring org-last-inserted-timestamp -1))))))
13309 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13310 org-last-inserted-timestamp)))))
13312 (defun org-deadline (arg &optional time)
13313 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13314 With one universal prefix argument, remove any deadline from the item.
13315 With two universal prefix arguments, prompt for a warning delay.
13316 With argument TIME, set the deadline at the corresponding date. TIME
13317 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13318 (interactive "P")
13319 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13320 (org-map-entries
13321 (lambda () (org--deadline-or-schedule arg 'deadline time))
13323 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13324 'region-start-level
13325 'region)
13326 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13327 (org--deadline-or-schedule arg 'deadline time)))
13329 (defun org-schedule (arg &optional time)
13330 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13331 With one universal prefix argument, remove any scheduling date from the item.
13332 With two universal prefix arguments, prompt for a delay cookie.
13333 With argument TIME, scheduled at the corresponding date. TIME can
13334 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13335 (interactive "P")
13336 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13337 (org-map-entries
13338 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13340 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13341 'region-start-level
13342 'region)
13343 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13344 (org--deadline-or-schedule arg 'scheduled time)))
13346 (defun org-get-scheduled-time (pom &optional inherit)
13347 "Get the scheduled time as a time tuple, of a format suitable
13348 for calling org-schedule with, or if there is no scheduling,
13349 returns nil."
13350 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13351 (when time
13352 (apply 'encode-time (org-parse-time-string time)))))
13354 (defun org-get-deadline-time (pom &optional inherit)
13355 "Get the deadline as a time tuple, of a format suitable for
13356 calling org-deadline with, or if there is no scheduling, returns
13357 nil."
13358 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13359 (when time
13360 (apply 'encode-time (org-parse-time-string time)))))
13362 (defun org-remove-timestamp-with-keyword (keyword)
13363 "Remove all time stamps with KEYWORD in the current entry."
13364 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13365 beg)
13366 (save-excursion
13367 (org-back-to-heading t)
13368 (setq beg (point))
13369 (outline-next-heading)
13370 (while (re-search-backward re beg t)
13371 (replace-match "")
13372 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13373 (equal (char-before) ?\ ))
13374 (backward-delete-char 1)
13375 (when (string-match "^[ \t]*$" (buffer-substring
13376 (point-at-bol) (point-at-eol)))
13377 (delete-region (point-at-bol)
13378 (min (point-max) (1+ (point-at-eol))))))))))
13380 (defvar org-time-was-given) ; dynamically scoped parameter
13381 (defvar org-end-time-was-given) ; dynamically scoped parameter
13383 (defun org-at-planning-p ()
13384 "Non-nil when point is on a planning info line."
13385 ;; This is as accurate and faster than `org-element-at-point' since
13386 ;; planning info location is fixed in the section.
13387 (org-with-wide-buffer
13388 (beginning-of-line)
13389 (and (looking-at-p org-planning-line-re)
13390 (eq (point)
13391 (ignore-errors
13392 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13393 (org-back-to-heading t)
13394 (org-with-limited-levels (org-back-to-heading t)))
13395 (line-beginning-position 2))))))
13397 (defun org-add-planning-info (what &optional time &rest remove)
13398 "Insert new timestamp with keyword in the planning line.
13399 WHAT indicates what kind of time stamp to add. It is a symbol
13400 among `closed', `deadline', `scheduled' and nil. TIME indicates
13401 the time to use. If none is given, the user is prompted for
13402 a date. REMOVE indicates what kind of entries to remove. An old
13403 WHAT entry will also be removed."
13404 (let (org-time-was-given org-end-time-was-given default-time default-input)
13405 (catch 'exit
13406 (when (and (memq what '(scheduled deadline))
13407 (or (not time)
13408 (and (stringp time)
13409 (string-match "^[-+]+[0-9]" time))))
13410 ;; Try to get a default date/time from existing timestamp
13411 (save-excursion
13412 (org-back-to-heading t)
13413 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13414 (when (re-search-forward (if (eq what 'scheduled)
13415 org-scheduled-time-regexp
13416 org-deadline-time-regexp)
13417 end t)
13418 (setq ts (match-string 1)
13419 default-time (apply 'encode-time (org-parse-time-string ts))
13420 default-input (and ts (org-get-compact-tod ts)))))))
13421 (when what
13422 (setq time
13423 (if (stringp time)
13424 ;; This is a string (relative or absolute), set
13425 ;; proper date.
13426 (apply #'encode-time
13427 (org-read-date-analyze
13428 time default-time (decode-time default-time)))
13429 ;; If necessary, get the time from the user
13430 (or time (org-read-date nil 'to-time nil nil
13431 default-time default-input)))))
13433 (org-with-wide-buffer
13434 (org-back-to-heading t)
13435 (forward-line)
13436 (unless (bolp) (insert "\n"))
13437 (cond ((looking-at-p org-planning-line-re)
13438 ;; Move to current indentation.
13439 (skip-chars-forward " \t")
13440 ;; Check if we have to remove something.
13441 (dolist (type (if what (cons what remove) remove))
13442 (save-excursion
13443 (when (re-search-forward
13444 (cl-case type
13445 (closed org-closed-time-regexp)
13446 (deadline org-deadline-time-regexp)
13447 (scheduled org-scheduled-time-regexp)
13448 (otherwise
13449 (error "Invalid planning type: %s" type)))
13450 (line-end-position) t)
13451 ;; Delete until next keyword or end of line.
13452 (delete-region
13453 (match-beginning 0)
13454 (if (re-search-forward org-keyword-time-not-clock-regexp
13455 (line-end-position)
13457 (match-beginning 0)
13458 (line-end-position))))))
13459 ;; If there is nothing more to add and no more keyword
13460 ;; is left, remove the line completely.
13461 (if (and (looking-at-p "[ \t]*$") (not what))
13462 (delete-region (line-beginning-position)
13463 (line-beginning-position 2))
13464 ;; If we removed last keyword, do not leave trailing
13465 ;; white space at the end of line.
13466 (let ((p (point)))
13467 (save-excursion
13468 (end-of-line)
13469 (unless (= (skip-chars-backward " \t" p) 0)
13470 (delete-region (point) (line-end-position)))))))
13471 ((not what) (throw 'exit nil)) ; Nothing to do.
13472 (t (insert-before-markers "\n")
13473 (backward-char 1)
13474 (when org-adapt-indentation
13475 (indent-to-column (1+ (org-outline-level))))))
13476 (when what
13477 ;; Insert planning keyword.
13478 (insert (cl-case what
13479 (closed org-closed-string)
13480 (deadline org-deadline-string)
13481 (scheduled org-scheduled-string)
13482 (otherwise (error "Invalid planning type: %s" what)))
13483 " ")
13484 ;; Insert associated timestamp.
13485 (let ((ts (org-insert-time-stamp
13486 time
13487 (or org-time-was-given
13488 (and (eq what 'closed) org-log-done-with-time))
13489 (eq what 'closed)
13490 nil nil (list org-end-time-was-given))))
13491 (unless (eolp) (insert " "))
13492 ts))))))
13494 (defvar org-log-note-marker (make-marker)
13495 "Marker pointing at the entry where the note is to be inserted.")
13496 (defvar org-log-note-purpose nil)
13497 (defvar org-log-note-state nil)
13498 (defvar org-log-note-previous-state nil)
13499 (defvar org-log-note-extra nil)
13500 (defvar org-log-note-window-configuration nil)
13501 (defvar org-log-note-return-to (make-marker))
13502 (defvar org-log-note-effective-time nil
13503 "Remembered current time so that dynamically scoped
13504 `org-extend-today-until' affects timestamps in state change log")
13506 (defvar org-log-post-message nil
13507 "Message to be displayed after a log note has been stored.
13508 The auto-repeater uses this.")
13510 (defun org-add-note ()
13511 "Add a note to the current entry.
13512 This is done in the same way as adding a state change note."
13513 (interactive)
13514 (org-add-log-setup 'note))
13516 (defun org-log-beginning (&optional create)
13517 "Return expected start of log notes in current entry.
13518 When optional argument CREATE is non-nil, the function creates
13519 a drawer to store notes, if necessary. Returned position ignores
13520 narrowing."
13521 (org-with-wide-buffer
13522 (let ((drawer (org-log-into-drawer)))
13523 (cond
13524 (drawer
13525 (org-end-of-meta-data)
13526 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13527 (end (if (org-at-heading-p) (point)
13528 (save-excursion (outline-next-heading) (point))))
13529 (case-fold-search t))
13530 (catch 'exit
13531 ;; Try to find existing drawer.
13532 (while (re-search-forward regexp end t)
13533 (let ((element (org-element-at-point)))
13534 (when (eq (org-element-type element) 'drawer)
13535 (let ((cend (org-element-property :contents-end element)))
13536 (when (and (not org-log-states-order-reversed) cend)
13537 (goto-char cend)))
13538 (throw 'exit nil))))
13539 ;; No drawer found. Create one, if permitted.
13540 (when create
13541 (unless (bolp) (insert "\n"))
13542 (let ((beg (point)))
13543 (insert ":" drawer ":\n:END:\n")
13544 (org-indent-region beg (point)))
13545 (end-of-line -1)))))
13547 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13548 (skip-chars-forward " \t\n")
13549 (beginning-of-line)
13550 (unless org-log-states-order-reversed
13551 (org-skip-over-state-notes)
13552 (skip-chars-backward " \t\n")
13553 (forward-line)))))
13554 (if (bolp) (point) (line-beginning-position 2))))
13556 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13557 "Set up the post command hook to take a note.
13558 If this is about to TODO state change, the new state is expected in STATE.
13559 HOW is an indicator what kind of note should be created.
13560 EXTRA is additional text that will be inserted into the notes buffer."
13561 (move-marker org-log-note-marker (point))
13562 (setq org-log-note-purpose purpose
13563 org-log-note-state state
13564 org-log-note-previous-state prev-state
13565 org-log-note-how how
13566 org-log-note-extra extra
13567 org-log-note-effective-time (org-current-effective-time))
13568 (add-hook 'post-command-hook 'org-add-log-note 'append))
13570 (defun org-skip-over-state-notes ()
13571 "Skip past the list of State notes in an entry."
13572 (when (ignore-errors (goto-char (org-in-item-p)))
13573 (let* ((struct (org-list-struct))
13574 (prevs (org-list-prevs-alist struct))
13575 (regexp
13576 (concat "[ \t]*- +"
13577 (replace-regexp-in-string
13578 " +" " +"
13579 (org-replace-escapes
13580 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13581 `(("%d" . ,org-ts-regexp-inactive)
13582 ("%D" . ,org-ts-regexp)
13583 ("%s" . "\"\\S-+\"")
13584 ("%S" . "\"\\S-+\"")
13585 ("%t" . ,org-ts-regexp-inactive)
13586 ("%T" . ,org-ts-regexp)
13587 ("%u" . ".*?")
13588 ("%U" . ".*?")))))))
13589 (while (looking-at-p regexp)
13590 (goto-char (or (org-list-get-next-item (point) struct prevs)
13591 (org-list-get-item-end (point) struct)))))))
13593 (defun org-add-log-note (&optional _purpose)
13594 "Pop up a window for taking a note, and add this note later."
13595 (remove-hook 'post-command-hook 'org-add-log-note)
13596 (setq org-log-note-window-configuration (current-window-configuration))
13597 (delete-other-windows)
13598 (move-marker org-log-note-return-to (point))
13599 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13600 (goto-char org-log-note-marker)
13601 (org-switch-to-buffer-other-window "*Org Note*")
13602 (erase-buffer)
13603 (if (memq org-log-note-how '(time state))
13604 (let (current-prefix-arg) (org-store-log-note))
13605 (let ((org-inhibit-startup t)) (org-mode))
13606 (insert (format "# Insert note for %s.
13607 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13608 (cond
13609 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13610 ((eq org-log-note-purpose 'done) "closed todo item")
13611 ((eq org-log-note-purpose 'state)
13612 (format "state change from \"%s\" to \"%s\""
13613 (or org-log-note-previous-state "")
13614 (or org-log-note-state "")))
13615 ((eq org-log-note-purpose 'reschedule)
13616 "rescheduling")
13617 ((eq org-log-note-purpose 'delschedule)
13618 "no longer scheduled")
13619 ((eq org-log-note-purpose 'redeadline)
13620 "changing deadline")
13621 ((eq org-log-note-purpose 'deldeadline)
13622 "removing deadline")
13623 ((eq org-log-note-purpose 'refile)
13624 "refiling")
13625 ((eq org-log-note-purpose 'note)
13626 "this entry")
13627 (t (error "This should not happen")))))
13628 (when org-log-note-extra (insert org-log-note-extra))
13629 (setq-local org-finish-function 'org-store-log-note)
13630 (run-hooks 'org-log-buffer-setup-hook)))
13632 (defvar org-note-abort nil) ; dynamically scoped
13633 (defun org-store-log-note ()
13634 "Finish taking a log note, and insert it to where it belongs."
13635 (let ((txt (prog1 (buffer-string)
13636 (kill-buffer)))
13637 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13638 lines)
13639 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13640 (setq txt (replace-match "" t t txt)))
13641 (when (string-match "\\s-+\\'" txt)
13642 (setq txt (replace-match "" t t txt)))
13643 (setq lines (org-split-string txt "\n"))
13644 (when (org-string-nw-p note)
13645 (setq note
13646 (org-replace-escapes
13647 note
13648 (list (cons "%u" (user-login-name))
13649 (cons "%U" user-full-name)
13650 (cons "%t" (format-time-string
13651 (org-time-stamp-format 'long 'inactive)
13652 org-log-note-effective-time))
13653 (cons "%T" (format-time-string
13654 (org-time-stamp-format 'long nil)
13655 org-log-note-effective-time))
13656 (cons "%d" (format-time-string
13657 (org-time-stamp-format nil 'inactive)
13658 org-log-note-effective-time))
13659 (cons "%D" (format-time-string
13660 (org-time-stamp-format nil nil)
13661 org-log-note-effective-time))
13662 (cons "%s" (cond
13663 ((not org-log-note-state) "")
13664 ((string-match-p org-ts-regexp
13665 org-log-note-state)
13666 (format "\"[%s]\""
13667 (substring org-log-note-state 1 -1)))
13668 (t (format "\"%s\"" org-log-note-state))))
13669 (cons "%S"
13670 (cond
13671 ((not org-log-note-previous-state) "")
13672 ((string-match-p org-ts-regexp
13673 org-log-note-previous-state)
13674 (format "\"[%s]\""
13675 (substring
13676 org-log-note-previous-state 1 -1)))
13677 (t (format "\"%s\""
13678 org-log-note-previous-state)))))))
13679 (when lines (setq note (concat note " \\\\")))
13680 (push note lines))
13681 (when (and lines (not (or current-prefix-arg org-note-abort)))
13682 (with-current-buffer (marker-buffer org-log-note-marker)
13683 (org-with-wide-buffer
13684 ;; Find location for the new note.
13685 (goto-char org-log-note-marker)
13686 (set-marker org-log-note-marker nil)
13687 ;; Note associated to a clock is to be located right after
13688 ;; the clock. Do not move point.
13689 (unless (eq org-log-note-purpose 'clock-out)
13690 (goto-char (org-log-beginning t)))
13691 ;; Make sure point is at the beginning of an empty line.
13692 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13693 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13694 ;; In an existing list, add a new item at the top level.
13695 ;; Otherwise, indent line like a regular one.
13696 (let ((itemp (org-in-item-p)))
13697 (if itemp
13698 (indent-line-to
13699 (let ((struct (save-excursion
13700 (goto-char itemp) (org-list-struct))))
13701 (org-list-get-ind (org-list-get-top-point struct) struct)))
13702 (org-indent-line)))
13703 (insert (org-list-bullet-string "-") (pop lines))
13704 (let ((ind (org-list-item-body-column (line-beginning-position))))
13705 (dolist (line lines)
13706 (insert "\n")
13707 (indent-line-to ind)
13708 (insert line)))
13709 (message "Note stored")
13710 (org-back-to-heading t)
13711 (org-cycle-hide-drawers 'children))
13712 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13713 ;; from within `org-add-log-note' because `buffer-undo-list'
13714 ;; is then modified outside of `org-with-remote-undo'.
13715 (when (eq this-command 'org-agenda-todo)
13716 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13717 ;; Don't add undo information when called from `org-agenda-todo'.
13718 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13719 (set-window-configuration org-log-note-window-configuration)
13720 (with-current-buffer (marker-buffer org-log-note-return-to)
13721 (goto-char org-log-note-return-to))
13722 (move-marker org-log-note-return-to nil)
13723 (when org-log-post-message (message "%s" org-log-post-message))))
13725 (defun org-remove-empty-drawer-at (pos)
13726 "Remove an empty drawer at position POS.
13727 POS may also be a marker."
13728 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13729 (org-with-wide-buffer
13730 (goto-char pos)
13731 (let ((drawer (org-element-at-point)))
13732 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13733 (not (org-element-property :contents-begin drawer)))
13734 (delete-region (org-element-property :begin drawer)
13735 (progn (goto-char (org-element-property :end drawer))
13736 (skip-chars-backward " \r\t\n")
13737 (forward-line)
13738 (point))))))))
13740 (defvar org-ts-type nil)
13741 (defun org-sparse-tree (&optional arg type)
13742 "Create a sparse tree, prompt for the details.
13743 This command can create sparse trees. You first need to select the type
13744 of match used to create the tree:
13746 t Show all TODO entries.
13747 T Show entries with a specific TODO keyword.
13748 m Show entries selected by a tags/property match.
13749 p Enter a property name and its value (both with completion on existing
13750 names/values) and show entries with that property.
13751 r Show entries matching a regular expression (`/' can be used as well).
13752 b Show deadlines and scheduled items before a date.
13753 a Show deadlines and scheduled items after a date.
13754 d Show deadlines due within `org-deadline-warning-days'.
13755 D Show deadlines and scheduled items between a date range."
13756 (interactive "P")
13757 (setq type (or type org-sparse-tree-default-date-type))
13758 (setq org-ts-type type)
13759 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13760 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13761 \[c]ycle through date types: %s"
13762 (cl-case type
13763 (all "all timestamps")
13764 (scheduled "only scheduled")
13765 (deadline "only deadline")
13766 (active "only active timestamps")
13767 (inactive "only inactive timestamps")
13768 (closed "with a closed time-stamp")
13769 (otherwise "scheduled/deadline")))
13770 (let ((answer (read-char-exclusive)))
13771 (cl-case answer
13773 (org-sparse-tree
13775 (cadr
13776 (memq type '(nil all scheduled deadline active inactive closed)))))
13777 (?d (call-interactively 'org-check-deadlines))
13778 (?b (call-interactively 'org-check-before-date))
13779 (?a (call-interactively 'org-check-after-date))
13780 (?D (call-interactively 'org-check-dates-range))
13781 (?t (call-interactively 'org-show-todo-tree))
13782 (?T (org-show-todo-tree '(4)))
13783 (?m (call-interactively 'org-match-sparse-tree))
13784 ((?p ?P)
13785 (let* ((kwd (completing-read
13786 "Property: " (mapcar #'list (org-buffer-property-keys))))
13787 (value (completing-read
13788 "Value: " (mapcar #'list (org-property-values kwd)))))
13789 (unless (string-match "\\`{.*}\\'" value)
13790 (setq value (concat "\"" value "\"")))
13791 (org-match-sparse-tree arg (concat kwd "=" value))))
13792 ((?r ?R ?/) (call-interactively 'org-occur))
13793 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13795 (defvar-local org-occur-highlights nil
13796 "List of overlays used for occur matches.")
13797 (defvar-local org-occur-parameters nil
13798 "Parameters of the active org-occur calls.
13799 This is a list, each call to org-occur pushes as cons cell,
13800 containing the regular expression and the callback, onto the list.
13801 The list can contain several entries if `org-occur' has been called
13802 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13803 will only contain one set of parameters. When the highlights are
13804 removed (for example with `C-c C-c', or with the next edit (depending
13805 on `org-remove-highlights-with-change'), this variable is emptied
13806 as well.")
13808 (defun org-occur (regexp &optional keep-previous callback)
13809 "Make a compact tree which shows all matches of REGEXP.
13811 The tree will show the lines where the regexp matches, and any other context
13812 defined in `org-show-context-detail', which see.
13814 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13815 done by a previous call to `org-occur' will be kept, to allow stacking of
13816 calls to this command.
13818 Optional argument CALLBACK can be a function of no argument. In this case,
13819 it is called with point at the end of the match, match data being set
13820 accordingly. Current match is shown only if the return value is non-nil.
13821 The function must neither move point nor alter narrowing."
13822 (interactive "sRegexp: \nP")
13823 (when (equal regexp "")
13824 (user-error "Regexp cannot be empty"))
13825 (unless keep-previous
13826 (org-remove-occur-highlights nil nil t))
13827 (push (cons regexp callback) org-occur-parameters)
13828 (let ((cnt 0))
13829 (save-excursion
13830 (goto-char (point-min))
13831 (when (or (not keep-previous) ; do not want to keep
13832 (not org-occur-highlights)) ; no previous matches
13833 ;; hide everything
13834 (org-overview))
13835 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13836 (isearch-no-upper-case-p regexp t)
13837 org-occur-case-fold-search)))
13838 (while (re-search-forward regexp nil t)
13839 (when (or (not callback)
13840 (save-match-data (funcall callback)))
13841 (setq cnt (1+ cnt))
13842 (when org-highlight-sparse-tree-matches
13843 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13844 (org-show-context 'occur-tree)))))
13845 (when org-remove-highlights-with-change
13846 (add-hook 'before-change-functions 'org-remove-occur-highlights
13847 nil 'local))
13848 (unless org-sparse-tree-open-archived-trees
13849 (org-hide-archived-subtrees (point-min) (point-max)))
13850 (run-hooks 'org-occur-hook)
13851 (when (called-interactively-p 'interactive)
13852 (message "%d match(es) for regexp %s" cnt regexp))
13853 cnt))
13855 (defun org-occur-next-match (&optional n _reset)
13856 "Function for `next-error-function' to find sparse tree matches.
13857 N is the number of matches to move, when negative move backwards.
13858 This function always goes back to the starting point when no
13859 match is found."
13860 (let* ((limit (if (< n 0) (point-min) (point-max)))
13861 (search-func (if (< n 0)
13862 'previous-single-char-property-change
13863 'next-single-char-property-change))
13864 (n (abs n))
13865 (pos (point))
13867 (catch 'exit
13868 (while (setq p1 (funcall search-func (point) 'org-type))
13869 (when (equal p1 limit)
13870 (goto-char pos)
13871 (user-error "No more matches"))
13872 (when (equal (get-char-property p1 'org-type) 'org-occur)
13873 (setq n (1- n))
13874 (when (= n 0)
13875 (goto-char p1)
13876 (throw 'exit (point))))
13877 (goto-char p1))
13878 (goto-char p1)
13879 (user-error "No more matches"))))
13881 (defun org-show-context (&optional key)
13882 "Make sure point and context are visible.
13883 Optional argument KEY, when non-nil, is a symbol. See
13884 `org-show-context-detail' for allowed values and how much is to
13885 be shown."
13886 (org-show-set-visibility
13887 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13888 ((cdr (assq key org-show-context-detail)))
13889 (t (cdr (assq 'default org-show-context-detail))))))
13891 (defun org-show-set-visibility (detail)
13892 "Set visibility around point according to DETAIL.
13893 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13894 `tree', `canonical' or t. See `org-show-context-detail' for more
13895 information."
13896 ;; Show current heading and possibly its entry, following headline
13897 ;; or all children.
13898 (if (and (org-at-heading-p) (not (eq detail 'local)))
13899 (org-flag-heading nil)
13900 (org-show-entry)
13901 ;; If point is hidden within a drawer or a block, make sure to
13902 ;; expose it.
13903 (dolist (o (overlays-at (point)))
13904 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13905 (delete-overlay o)))
13906 (unless (org-before-first-heading-p)
13907 (org-with-limited-levels
13908 (cl-case detail
13909 ((tree canonical t) (org-show-children))
13910 ((nil minimal ancestors))
13911 (t (save-excursion
13912 (outline-next-heading)
13913 (org-flag-heading nil)))))))
13914 ;; Show all siblings.
13915 (when (eq detail 'lineage) (org-show-siblings))
13916 ;; Show ancestors, possibly with their children.
13917 (when (memq detail '(ancestors lineage tree canonical t))
13918 (save-excursion
13919 (while (org-up-heading-safe)
13920 (org-flag-heading nil)
13921 (when (memq detail '(canonical t)) (org-show-entry))
13922 (when (memq detail '(tree canonical t)) (org-show-children))))))
13924 (defvar org-reveal-start-hook nil
13925 "Hook run before revealing a location.")
13927 (defun org-reveal (&optional siblings)
13928 "Show current entry, hierarchy above it, and the following headline.
13930 This can be used to show a consistent set of context around
13931 locations exposed with `org-show-context'.
13933 With optional argument SIBLINGS, on each level of the hierarchy all
13934 siblings are shown. This repairs the tree structure to what it would
13935 look like when opened with hierarchical calls to `org-cycle'.
13937 With a \\[universal-argument] \\[universal-argument] prefix, \
13938 go to the parent and show the entire tree."
13939 (interactive "P")
13940 (run-hooks 'org-reveal-start-hook)
13941 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13942 ((equal siblings '(16))
13943 (save-excursion
13944 (when (org-up-heading-safe)
13945 (org-show-subtree)
13946 (run-hook-with-args 'org-cycle-hook 'subtree))))
13947 (t (org-show-set-visibility 'lineage))))
13949 (defun org-highlight-new-match (beg end)
13950 "Highlight from BEG to END and mark the highlight is an occur headline."
13951 (let ((ov (make-overlay beg end)))
13952 (overlay-put ov 'face 'secondary-selection)
13953 (overlay-put ov 'org-type 'org-occur)
13954 (push ov org-occur-highlights)))
13956 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13957 "Remove the occur highlights from the buffer.
13958 BEG and END are ignored. If NOREMOVE is nil, remove this function
13959 from the `before-change-functions' in the current buffer."
13960 (interactive)
13961 (unless org-inhibit-highlight-removal
13962 (mapc #'delete-overlay org-occur-highlights)
13963 (setq org-occur-highlights nil)
13964 (setq org-occur-parameters nil)
13965 (unless noremove
13966 (remove-hook 'before-change-functions
13967 'org-remove-occur-highlights 'local))))
13969 ;;;; Priorities
13971 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13972 "Regular expression matching the priority indicator.")
13974 (defvar org-remove-priority-next-time nil)
13976 (defun org-priority-up ()
13977 "Increase the priority of the current item."
13978 (interactive)
13979 (org-priority 'up))
13981 (defun org-priority-down ()
13982 "Decrease the priority of the current item."
13983 (interactive)
13984 (org-priority 'down))
13986 (defun org-priority (&optional action _show)
13987 "Change the priority of an item.
13988 ACTION can be `set', `up', `down', or a character."
13989 (interactive "P")
13990 (if (equal action '(4))
13991 (org-show-priority)
13992 (unless org-enable-priority-commands
13993 (user-error "Priority commands are disabled"))
13994 (setq action (or action 'set))
13995 (let (current new news have remove)
13996 (save-excursion
13997 (org-back-to-heading t)
13998 (when (looking-at org-priority-regexp)
13999 (setq current (string-to-char (match-string 2))
14000 have t))
14001 (cond
14002 ((eq action 'remove)
14003 (setq remove t new ?\ ))
14004 ((or (eq action 'set)
14005 (integerp action))
14006 (if (not (eq action 'set))
14007 (setq new action)
14008 (message "Priority %c-%c, SPC to remove: "
14009 org-highest-priority org-lowest-priority)
14010 (save-match-data
14011 (setq new (read-char-exclusive))))
14012 (when (and (= (upcase org-highest-priority) org-highest-priority)
14013 (= (upcase org-lowest-priority) org-lowest-priority))
14014 (setq new (upcase new)))
14015 (cond ((equal new ?\ ) (setq remove t))
14016 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14017 (user-error "Priority must be between `%c' and `%c'"
14018 org-highest-priority org-lowest-priority))))
14019 ((eq action 'up)
14020 (setq new (if have
14021 (1- current) ; normal cycling
14022 ;; last priority was empty
14023 (if (eq last-command this-command)
14024 org-lowest-priority ; wrap around empty to lowest
14025 ;; default
14026 (if org-priority-start-cycle-with-default
14027 org-default-priority
14028 (1- org-default-priority))))))
14029 ((eq action 'down)
14030 (setq new (if have
14031 (1+ current) ; normal cycling
14032 ;; last priority was empty
14033 (if (eq last-command this-command)
14034 org-highest-priority ; wrap around empty to highest
14035 ;; default
14036 (if org-priority-start-cycle-with-default
14037 org-default-priority
14038 (1+ org-default-priority))))))
14039 (t (user-error "Invalid action")))
14040 (when (or (< (upcase new) org-highest-priority)
14041 (> (upcase new) org-lowest-priority))
14042 (if (and (memq action '(up down))
14043 (not have) (not (eq last-command this-command)))
14044 ;; `new' is from default priority
14045 (error
14046 "The default can not be set, see `org-default-priority' why")
14047 ;; normal cycling: `new' is beyond highest/lowest priority
14048 ;; and is wrapped around to the empty priority
14049 (setq remove t)))
14050 (setq news (format "%c" new))
14051 (if have
14052 (if remove
14053 (replace-match "" t t nil 1)
14054 (replace-match news t t nil 2))
14055 (if remove
14056 (user-error "No priority cookie found in line")
14057 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14058 (if (match-end 2)
14059 (progn
14060 (goto-char (match-end 2))
14061 (insert " [#" news "]"))
14062 (goto-char (match-beginning 3))
14063 (insert "[#" news "] "))))
14064 (org-set-tags nil 'align))
14065 (if remove
14066 (message "Priority removed")
14067 (message "Priority of current item set to %s" news)))))
14069 (defun org-show-priority ()
14070 "Show the priority of the current item.
14071 This priority is composed of the main priority given with the [#A] cookies,
14072 and by additional input from the age of a schedules or deadline entry."
14073 (interactive)
14074 (let ((pri (if (eq major-mode 'org-agenda-mode)
14075 (org-get-at-bol 'priority)
14076 (save-excursion
14077 (save-match-data
14078 (beginning-of-line)
14079 (and (looking-at org-heading-regexp)
14080 (org-get-priority (match-string 0))))))))
14081 (message "Priority is %d" (if pri pri -1000))))
14083 (defun org-get-priority (s)
14084 "Find priority cookie and return priority."
14085 (save-match-data
14086 (if (functionp org-get-priority-function)
14087 (funcall org-get-priority-function)
14088 (if (not (string-match org-priority-regexp s))
14089 (* 1000 (- org-lowest-priority org-default-priority))
14090 (* 1000 (- org-lowest-priority
14091 (string-to-char (match-string 2 s))))))))
14093 ;;;; Tags
14095 (defvar org-agenda-archives-mode)
14096 (defvar org-map-continue-from nil
14097 "Position from where mapping should continue.
14098 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14100 (defvar org-scanner-tags nil
14101 "The current tag list while the tags scanner is running.")
14103 (defvar org-trust-scanner-tags nil
14104 "Should `org-get-tags-at' use the tags for the scanner.
14105 This is for internal dynamical scoping only.
14106 When this is non-nil, the function `org-get-tags-at' will return the value
14107 of `org-scanner-tags' instead of building the list by itself. This
14108 can lead to large speed-ups when the tags scanner is used in a file with
14109 many entries, and when the list of tags is retrieved, for example to
14110 obtain a list of properties. Building the tags list for each entry in such
14111 a file becomes an N^2 operation - but with this variable set, it scales
14112 as N.")
14114 (defvar org--matcher-tags-todo-only nil)
14116 (defun org-scan-tags (action matcher todo-only &optional start-level)
14117 "Scan headline tags with inheritance and produce output ACTION.
14119 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14120 or `agenda' to produce an entry list for an agenda view. It can also be
14121 a Lisp form or a function that should be called at each matched headline, in
14122 this case the return value is a list of all return values from these calls.
14124 MATCHER is a function accepting three arguments, returning
14125 a non-nil value whenever a given set of tags qualifies a headline
14126 for inclusion. See `org-make-tags-matcher' for more information.
14127 As a special case, it can also be set to t (respectively nil) in
14128 order to match all (respectively none) headline.
14130 When TODO-ONLY is non-nil, only lines with a not-done TODO
14131 keyword are included in the output.
14133 START-LEVEL can be a string with asterisks, reducing the scope to
14134 headlines matching this string."
14135 (require 'org-agenda)
14136 (let* ((re (concat "^"
14137 (if start-level
14138 ;; Get the correct level to match
14139 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14140 org-outline-regexp)
14141 " *\\(\\<\\("
14142 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14143 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14144 (props (list 'face 'default
14145 'done-face 'org-agenda-done
14146 'undone-face 'default
14147 'mouse-face 'highlight
14148 'org-not-done-regexp org-not-done-regexp
14149 'org-todo-regexp org-todo-regexp
14150 'org-complex-heading-regexp org-complex-heading-regexp
14151 'help-echo
14152 (format "mouse-2 or RET jump to org file %s"
14153 (abbreviate-file-name
14154 (or (buffer-file-name (buffer-base-buffer))
14155 (buffer-name (buffer-base-buffer)))))))
14156 (org-map-continue-from nil)
14157 lspos tags tags-list
14158 (tags-alist (list (cons 0 org-file-tags)))
14159 (llast 0) rtn rtn1 level category i txt
14160 todo marker entry priority
14161 ts-date ts-date-type ts-date-pair)
14162 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14163 (setq action (list 'lambda nil action)))
14164 (save-excursion
14165 (goto-char (point-min))
14166 (when (eq action 'sparse-tree)
14167 (org-overview)
14168 (org-remove-occur-highlights))
14169 (while (let (case-fold-search)
14170 (re-search-forward re nil t))
14171 (setq org-map-continue-from nil)
14172 (catch :skip
14173 (setq todo
14174 ;; TODO: is the 1-2 difference a bug?
14175 (when (match-end 1) (match-string-no-properties 2))
14176 tags (when (match-end 4) (match-string-no-properties 4)))
14177 (goto-char (setq lspos (match-beginning 0)))
14178 (setq level (org-reduced-level (org-outline-level))
14179 category (org-get-category))
14180 (when (eq action 'agenda)
14181 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14182 ts-date (car ts-date-pair)
14183 ts-date-type (cdr ts-date-pair)))
14184 (setq i llast llast level)
14185 ;; remove tag lists from same and sublevels
14186 (while (>= i level)
14187 (when (setq entry (assoc i tags-alist))
14188 (setq tags-alist (delete entry tags-alist)))
14189 (setq i (1- i)))
14190 ;; add the next tags
14191 (when tags
14192 (setq tags (org-split-string tags ":")
14193 tags-alist
14194 (cons (cons level tags) tags-alist)))
14195 ;; compile tags for current headline
14196 (setq tags-list
14197 (if org-use-tag-inheritance
14198 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14199 tags)
14200 org-scanner-tags tags-list)
14201 (when org-use-tag-inheritance
14202 (setcdr (car tags-alist)
14203 (mapcar (lambda (x)
14204 (setq x (copy-sequence x))
14205 (org-add-prop-inherited x))
14206 (cdar tags-alist))))
14207 (when (and tags org-use-tag-inheritance
14208 (or (not (eq t org-use-tag-inheritance))
14209 org-tags-exclude-from-inheritance))
14210 ;; Selective inheritance, remove uninherited ones.
14211 (setcdr (car tags-alist)
14212 (org-remove-uninherited-tags (cdar tags-alist))))
14213 (when (and
14215 ;; eval matcher only when the todo condition is OK
14216 (and (or (not todo-only) (member todo org-not-done-keywords))
14217 (if (functionp matcher)
14218 (let ((case-fold-search t) (org-trust-scanner-tags t))
14219 (funcall matcher todo tags-list level))
14220 matcher))
14222 ;; Call the skipper, but return t if it does not
14223 ;; skip, so that the `and' form continues evaluating.
14224 (progn
14225 (unless (eq action 'sparse-tree) (org-agenda-skip))
14228 ;; Check if timestamps are deselecting this entry
14229 (or (not todo-only)
14230 (and (member todo org-not-done-keywords)
14231 (or (not org-agenda-tags-todo-honor-ignore-options)
14232 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14234 ;; select this headline
14235 (cond
14236 ((eq action 'sparse-tree)
14237 (and org-highlight-sparse-tree-matches
14238 (org-get-heading) (match-end 0)
14239 (org-highlight-new-match
14240 (match-beginning 1) (match-end 1)))
14241 (org-show-context 'tags-tree))
14242 ((eq action 'agenda)
14243 (setq txt (org-agenda-format-item
14245 (concat
14246 (if (eq org-tags-match-list-sublevels 'indented)
14247 (make-string (1- level) ?.) "")
14248 (org-get-heading))
14249 (make-string level ?\s)
14250 category
14251 tags-list)
14252 priority (org-get-priority txt))
14253 (goto-char lspos)
14254 (setq marker (org-agenda-new-marker))
14255 (org-add-props txt props
14256 'org-marker marker 'org-hd-marker marker 'org-category category
14257 'todo-state todo
14258 'ts-date ts-date
14259 'priority priority
14260 'type (concat "tagsmatch" ts-date-type))
14261 (push txt rtn))
14262 ((functionp action)
14263 (setq org-map-continue-from nil)
14264 (save-excursion
14265 (setq rtn1 (funcall action))
14266 (push rtn1 rtn)))
14267 (t (user-error "Invalid action")))
14269 ;; if we are to skip sublevels, jump to end of subtree
14270 (unless org-tags-match-list-sublevels
14271 (org-end-of-subtree t)
14272 (backward-char 1))))
14273 ;; Get the correct position from where to continue
14274 (if org-map-continue-from
14275 (goto-char org-map-continue-from)
14276 (and (= (point) lspos) (end-of-line 1)))))
14277 (when (and (eq action 'sparse-tree)
14278 (not org-sparse-tree-open-archived-trees))
14279 (org-hide-archived-subtrees (point-min) (point-max)))
14280 (nreverse rtn)))
14282 (defun org-remove-uninherited-tags (tags)
14283 "Remove all tags that are not inherited from the list TAGS."
14284 (cond
14285 ((eq org-use-tag-inheritance t)
14286 (if org-tags-exclude-from-inheritance
14287 (org-delete-all org-tags-exclude-from-inheritance tags)
14288 tags))
14289 ((not org-use-tag-inheritance) nil)
14290 ((stringp org-use-tag-inheritance)
14291 (delq nil (mapcar
14292 (lambda (x)
14293 (if (and (string-match org-use-tag-inheritance x)
14294 (not (member x org-tags-exclude-from-inheritance)))
14295 x nil))
14296 tags)))
14297 ((listp org-use-tag-inheritance)
14298 (delq nil (mapcar
14299 (lambda (x)
14300 (if (member x org-use-tag-inheritance) x nil))
14301 tags)))))
14303 (defun org-match-sparse-tree (&optional todo-only match)
14304 "Create a sparse tree according to tags string MATCH.
14306 MATCH is a string with match syntax. It can contain a selection
14307 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14308 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14309 those. See the manual for details.
14311 If optional argument TODO-ONLY is non-nil, only select lines that
14312 are also TODO tasks."
14313 (interactive "P")
14314 (org-agenda-prepare-buffers (list (current-buffer)))
14315 (let ((org--matcher-tags-todo-only todo-only))
14316 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14317 org--matcher-tags-todo-only)))
14319 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14321 (defvar org-cached-props nil)
14322 (defun org-cached-entry-get (pom property)
14323 (if (or (eq t org-use-property-inheritance)
14324 (and (stringp org-use-property-inheritance)
14325 (let ((case-fold-search t))
14326 (string-match-p org-use-property-inheritance property)))
14327 (and (listp org-use-property-inheritance)
14328 (member-ignore-case property org-use-property-inheritance)))
14329 ;; Caching is not possible, check it directly.
14330 (org-entry-get pom property 'inherit)
14331 ;; Get all properties, so we can do complicated checks easily.
14332 (cdr (assoc-string property
14333 (or org-cached-props
14334 (setq org-cached-props (org-entry-properties pom)))
14335 t))))
14337 (defun org-global-tags-completion-table (&optional files)
14338 "Return the list of all tags in all agenda buffer/files.
14339 Optional FILES argument is a list of files which can be used
14340 instead of the agenda files."
14341 (save-excursion
14342 (org-uniquify
14343 (delq nil
14344 (apply #'append
14345 (mapcar
14346 (lambda (file)
14347 (set-buffer (find-file-noselect file))
14348 (mapcar (lambda (x)
14349 (and (stringp (car-safe x))
14350 (list (car-safe x))))
14351 (or org-current-tag-alist (org-get-buffer-tags))))
14352 (if (car-safe files) files
14353 (org-agenda-files))))))))
14355 (defun org-make-tags-matcher (match)
14356 "Create the TAGS/TODO matcher form for the selection string MATCH.
14358 Returns a cons of the selection string MATCH and a function
14359 implementing the matcher.
14361 The matcher is to be called at an Org entry, with point on the
14362 headline, and returns non-nil if the entry matches the selection
14363 string MATCH. It must be called with three arguments: the TODO
14364 keyword at the entry (or nil if none), the list of all tags at
14365 the entry including inherited ones and the reduced level of the
14366 headline. Additionally, the category of the entry, if any, must
14367 be specified as the text property `org-category' on the headline.
14369 This function sets the variable `org--matcher-tags-todo-only' to
14370 a non-nil value if the matcher restricts matching to TODO
14371 entries, otherwise it is not touched.
14373 See also `org-scan-tags'."
14374 (unless match
14375 ;; Get a new match request, with completion against the global
14376 ;; tags table and the local tags in current buffer.
14377 (let ((org-last-tags-completion-table
14378 (org-uniquify
14379 (delq nil (append (org-get-buffer-tags)
14380 (org-global-tags-completion-table))))))
14381 (setq match
14382 (completing-read
14383 "Match: "
14384 'org-tags-completion-function nil nil nil 'org-tags-history))))
14386 (let ((match0 match)
14387 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14388 (start 0)
14389 tagsmatch todomatch tagsmatcher todomatcher)
14391 ;; Expand group tags.
14392 (setq match (org-tags-expand match))
14394 ;; Check if there is a TODO part of this match, which would be the
14395 ;; part after a "/". To make sure that this slash is not part of
14396 ;; a property value to be matched against, we also check that
14397 ;; there is no / after that slash. First, find the last slash.
14398 (let ((s 0))
14399 (while (string-match "/+" match s)
14400 (setq start (match-beginning 0))
14401 (setq s (match-end 0))))
14402 (if (and (string-match "/+" match start)
14403 (not (string-match-p "\"" match start)))
14404 ;; Match contains also a TODO-matching request.
14405 (progn
14406 (setq tagsmatch (substring match 0 (match-beginning 0)))
14407 (setq todomatch (substring match (match-end 0)))
14408 (when (string-prefix-p "!" todomatch)
14409 (setq org--matcher-tags-todo-only t)
14410 (setq todomatch (substring todomatch 1)))
14411 (when (string-match "\\`\\s-*\\'" todomatch)
14412 (setq todomatch nil)))
14413 ;; Only matching tags.
14414 (setq tagsmatch match)
14415 (setq todomatch nil))
14417 ;; Make the tags matcher.
14418 (when (org-string-nw-p tagsmatch)
14419 (let ((orlist nil)
14420 (orterms (org-split-string tagsmatch "|"))
14421 term)
14422 (while (setq term (pop orterms))
14423 (while (and (equal (substring term -1) "\\") orterms)
14424 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14425 (while (string-match re term)
14426 (let* ((rest (substring term (match-end 0)))
14427 (minus (and (match-end 1)
14428 (equal (match-string 1 term) "-")))
14429 (tag (save-match-data
14430 (replace-regexp-in-string
14431 "\\\\-" "-" (match-string 2 term))))
14432 (regexp (eq (string-to-char tag) ?{))
14433 (levelp (match-end 4))
14434 (propp (match-end 5))
14436 (cond
14437 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14438 (levelp
14439 `(,(org-op-to-function (match-string 3 term))
14440 level
14441 ,(string-to-number (match-string 4 term))))
14442 (propp
14443 (let* ((gv (pcase (upcase (match-string 5 term))
14444 ("CATEGORY"
14445 '(get-text-property (point) 'org-category))
14446 ("TODO" 'todo)
14447 (p `(org-cached-entry-get nil ,p))))
14448 (pv (match-string 7 term))
14449 (regexp (eq (string-to-char pv) ?{))
14450 (strp (eq (string-to-char pv) ?\"))
14451 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14452 (po (org-op-to-function (match-string 6 term)
14453 (if timep 'time strp))))
14454 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14455 (when timep (setq pv (org-matcher-time pv)))
14456 (cond ((and regexp (eq po 'org<>))
14457 `(not (string-match ,pv (or ,gv ""))))
14458 (regexp `(string-match ,pv (or ,gv "")))
14459 (strp `(,po (or ,gv "") ,pv))
14461 `(,po
14462 (string-to-number (or ,gv ""))
14463 ,(string-to-number pv))))))
14464 (t `(member ,tag tags-list)))))
14465 (push (if minus `(not ,mm) mm) tagsmatcher)
14466 (setq term rest)))
14467 (push `(and ,@tagsmatcher) orlist)
14468 (setq tagsmatcher nil))
14469 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14471 ;; Make the TODO matcher.
14472 (when (org-string-nw-p todomatch)
14473 (let ((orlist nil))
14474 (dolist (term (org-split-string todomatch "|"))
14475 (while (string-match re term)
14476 (let* ((minus (and (match-end 1)
14477 (equal (match-string 1 term) "-")))
14478 (kwd (match-string 2 term))
14479 (regexp (eq (string-to-char kwd) ?{))
14480 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14481 `(equal todo ,kwd))))
14482 (push (if minus `(not ,mm) mm) todomatcher))
14483 (setq term (substring term (match-end 0))))
14484 (push (if (> (length todomatcher) 1)
14485 (cons 'and todomatcher)
14486 (car todomatcher))
14487 orlist)
14488 (setq todomatcher nil))
14489 (setq todomatcher (cons 'or orlist))))
14491 ;; Return the string and function of the matcher. If no
14492 ;; tags-specific or todo-specific matcher exists, match
14493 ;; everything.
14494 (let ((matcher (if (and tagsmatcher todomatcher)
14495 `(and ,tagsmatcher ,todomatcher)
14496 (or tagsmatcher todomatcher t))))
14497 (when org--matcher-tags-todo-only
14498 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14499 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14501 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14502 "Expand group tags in MATCH.
14504 This replaces every group tag in MATCH with a regexp tag search.
14505 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14506 will be replaced like this:
14508 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14509 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14510 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14512 Replacing by a regexp preserves the structure of the match.
14513 E.g., this expansion
14515 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14517 will match anything tagged with \"Lab\" and \"Home\", or tagged
14518 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14520 A group tag in MATCH can contain regular expressions of its own.
14521 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14522 will be replaced like this:
14524 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14526 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14527 assumed to be a single group tag, and the function will return
14528 the list of tags in this group.
14530 When DOWNCASE is non-nil, expand downcased TAGS."
14531 (if org-group-tags
14532 (let* ((case-fold-search t)
14533 (stable org-mode-syntax-table)
14534 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14535 (taggroups (if downcased
14536 (mapcar (lambda (tg) (mapcar #'downcase tg))
14537 taggroups)
14538 taggroups))
14539 (taggroups-keys (mapcar #'car taggroups))
14540 (return-match (if downcased (downcase match) match))
14541 (count 0)
14542 (work-already-expanded tags-already-expanded)
14543 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14544 ;; @ and _ are allowed as word-components in tags.
14545 (modify-syntax-entry ?@ "w" stable)
14546 (modify-syntax-entry ?_ "w" stable)
14547 ;; Temporarily replace regexp-expressions in the match-expression.
14548 (while (string-match "{.+?}" return-match)
14549 (cl-incf count)
14550 (push (match-string 0 return-match) regexps-in-match)
14551 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14552 (while (and taggroups-keys
14553 (with-syntax-table stable
14554 (string-match
14555 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14556 (regexp-opt taggroups-keys) "\\>\\)")
14557 return-match)))
14558 (let* ((dir (match-string 1 return-match))
14559 (tag (match-string 2 return-match))
14560 (tag (if downcased (downcase tag) tag)))
14561 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14562 (member tag work-already-expanded))
14563 (setq tags-in-group (assoc tag taggroups))
14564 (push tag work-already-expanded)
14565 ;; Recursively expand each tag in the group, if the tag hasn't
14566 ;; already been expanded. Restore the match-data after all recursive calls.
14567 (save-match-data
14568 (let (tags-expanded)
14569 (dolist (x (cdr tags-in-group))
14570 (if (and (member x taggroups-keys)
14571 (not (member x work-already-expanded)))
14572 (setq tags-expanded
14573 (delete-dups
14574 (append
14575 (org-tags-expand x t downcased
14576 work-already-expanded)
14577 tags-expanded)))
14578 (setq tags-expanded
14579 (append (list x) tags-expanded)))
14580 (setq work-already-expanded
14581 (delete-dups
14582 (append tags-expanded
14583 work-already-expanded))))
14584 (setq tags-in-group
14585 (delete-dups (cons (car tags-in-group)
14586 tags-expanded)))))
14587 ;; Filter tag-regexps from tags.
14588 (setq regexp-in-group-escaped
14589 (delq nil (mapcar (lambda (x)
14590 (if (stringp x)
14591 (and (equal "{" (substring x 0 1))
14592 (equal "}" (substring x -1))
14595 tags-in-group))
14596 regexp-in-group
14597 (mapcar (lambda (x)
14598 (substring x 1 -1))
14599 regexp-in-group-escaped)
14600 tags-in-group
14601 (delq nil (mapcar (lambda (x)
14602 (if (stringp x)
14603 (and (not (equal "{" (substring x 0 1)))
14604 (not (equal "}" (substring x -1)))
14607 tags-in-group)))
14608 ;; If single-as-list, do no more in the while-loop.
14609 (if (not single-as-list)
14610 (progn
14611 (when regexp-in-group
14612 (setq regexp-in-group
14613 (concat "\\|"
14614 (mapconcat 'identity regexp-in-group
14615 "\\|"))))
14616 (setq tags-in-group
14617 (concat dir
14618 "{\\<"
14619 (regexp-opt tags-in-group)
14620 "\\>"
14621 regexp-in-group
14622 "}"))
14623 (when (stringp tags-in-group)
14624 (org-add-props tags-in-group '(grouptag t)))
14625 (setq return-match
14626 (replace-match tags-in-group t t return-match)))
14627 (setq tags-in-group
14628 (append regexp-in-group-escaped tags-in-group))))
14629 (setq taggroups-keys (delete tag taggroups-keys))))
14630 ;; Add the regular expressions back into the match-expression again.
14631 (while regexps-in-match
14632 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14633 (pop regexps-in-match)
14634 return-match t t))
14635 (cl-decf count))
14636 (if single-as-list
14637 (if tags-in-group tags-in-group (list return-match))
14638 return-match))
14639 (if single-as-list
14640 (list (if downcased (downcase match) match))
14641 match)))
14643 (defun org-op-to-function (op &optional stringp)
14644 "Turn an operator into the appropriate function."
14645 (setq op
14646 (cond
14647 ((equal op "<" ) '(< string< org-time<))
14648 ((equal op ">" ) '(> org-string> org-time>))
14649 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14650 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14651 ((member op '("=" "==")) '(= string= org-time=))
14652 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14653 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14655 (defun org<> (a b) (not (= a b)))
14656 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14657 (defun org-string>= (a b) (not (string< a b)))
14658 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14659 (defun org-string<> (a b) (not (string= a b)))
14660 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14661 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14662 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14663 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14664 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14665 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14666 (defun org-2ft (s)
14667 "Convert S to a floating point time.
14668 If S is already a number, just return it. If it is a string, parse
14669 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14670 (cond
14671 ((numberp s) s)
14672 ((stringp s)
14673 (condition-case nil
14674 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14675 (error 0.)))
14676 (t 0.)))
14678 (defun org-time-today ()
14679 "Time in seconds today at 0:00.
14680 Returns the float number of seconds since the beginning of the
14681 epoch to the beginning of today (00:00)."
14682 (float-time (apply 'encode-time
14683 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14685 (defun org-matcher-time (s)
14686 "Interpret a time comparison value."
14687 (save-match-data
14688 (cond
14689 ((string= s "<now>") (float-time))
14690 ((string= s "<today>") (org-time-today))
14691 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14692 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14693 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14694 (+ (org-time-today)
14695 (* (string-to-number (match-string 1 s))
14696 (cdr (assoc (match-string 2 s)
14697 '(("d" . 86400.0) ("w" . 604800.0)
14698 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14699 (t (org-2ft s)))))
14701 (defun org-match-any-p (re list)
14702 "Does re match any element of list?"
14703 (setq list (mapcar (lambda (x) (string-match re x)) list))
14704 (delq nil list))
14706 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14707 (defvar org-tags-overlay (make-overlay 1 1))
14708 (delete-overlay org-tags-overlay)
14710 (defun org-get-local-tags-at (&optional pos)
14711 "Get a list of tags defined in the current headline."
14712 (org-get-tags-at pos 'local))
14714 (defun org-get-local-tags ()
14715 "Get a list of tags defined in the current headline."
14716 (org-get-tags-at nil 'local))
14718 (defun org-get-tags-at (&optional pos local)
14719 "Get a list of all headline tags applicable at POS.
14720 POS defaults to point. If tags are inherited, the list contains
14721 the targets in the same sequence as the headlines appear, i.e.
14722 the tags of the current headline come last.
14723 When LOCAL is non-nil, only return tags from the current headline,
14724 ignore inherited ones."
14725 (interactive)
14726 (if (and org-trust-scanner-tags
14727 (or (not pos) (equal pos (point)))
14728 (not local))
14729 org-scanner-tags
14730 (let (tags ltags lastpos parent)
14731 (save-excursion
14732 (save-restriction
14733 (widen)
14734 (goto-char (or pos (point)))
14735 (save-match-data
14736 (catch 'done
14737 (condition-case nil
14738 (progn
14739 (org-back-to-heading t)
14740 (while (not (equal lastpos (point)))
14741 (setq lastpos (point))
14742 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14743 (setq ltags (org-split-string
14744 (match-string-no-properties 1) ":"))
14745 (when parent
14746 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14747 (setq tags (append
14748 (if parent
14749 (org-remove-uninherited-tags ltags)
14750 ltags)
14751 tags)))
14752 (or org-use-tag-inheritance (throw 'done t))
14753 (when local (throw 'done t))
14754 (or (org-up-heading-safe) (error nil))
14755 (setq parent t)))
14756 (error nil)))))
14757 (if local
14758 tags
14759 (reverse (delete-dups
14760 (reverse (append
14761 (org-remove-uninherited-tags
14762 org-file-tags)
14763 tags)))))))))
14765 (defun org-add-prop-inherited (s)
14766 (add-text-properties 0 (length s) '(inherited t) s)
14769 (defun org-toggle-tag (tag &optional onoff)
14770 "Toggle the tag TAG for the current line.
14771 If ONOFF is `on' or `off', don't toggle but set to this state."
14772 (let (res current)
14773 (save-excursion
14774 (org-back-to-heading t)
14775 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14776 (point-at-eol) t)
14777 (progn
14778 (setq current (match-string 1))
14779 (replace-match ""))
14780 (setq current ""))
14781 (setq current (nreverse (org-split-string current ":")))
14782 (cond
14783 ((eq onoff 'on)
14784 (setq res t)
14785 (or (member tag current) (push tag current)))
14786 ((eq onoff 'off)
14787 (or (not (member tag current)) (setq current (delete tag current))))
14788 (t (if (member tag current)
14789 (setq current (delete tag current))
14790 (setq res t)
14791 (push tag current))))
14792 (end-of-line 1)
14793 (if current
14794 (progn
14795 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14796 (org-set-tags nil t))
14797 (delete-horizontal-space))
14798 (run-hooks 'org-after-tags-change-hook))
14799 res))
14801 (defun org--align-tags-here (to-col)
14802 "Align tags on the current headline to TO-COL.
14803 Assume point is on a headline."
14804 (let ((pos (point)))
14805 (beginning-of-line)
14806 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14807 (>= pos (match-beginning 2)))
14808 ;; No tags or point within tags: do not align.
14809 (goto-char pos)
14810 (goto-char (match-beginning 1))
14811 (let ((shift (max (- (if (>= to-col 0) to-col
14812 (- (abs to-col) (string-width (match-string 2))))
14813 (current-column))
14814 1)))
14815 (replace-match (make-string shift ?\s) nil nil nil 1)
14816 ;; Preserve initial position, if possible. In any case, stop
14817 ;; before tags.
14818 (when (< pos (point)) (goto-char pos))))))
14820 (defun org-set-tags-command (&optional arg just-align)
14821 "Call the set-tags command for the current entry."
14822 (interactive "P")
14823 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14824 (org-set-tags arg just-align)
14825 (save-excursion
14826 (unless (and (org-region-active-p)
14827 org-loop-over-headlines-in-active-region)
14828 (org-back-to-heading t))
14829 (org-set-tags arg just-align))))
14831 (defun org-set-tags-to (data)
14832 "Set the tags of the current entry to DATA, replacing the current tags.
14833 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14834 If DATA is nil or the empty string, any tags will be removed."
14835 (interactive "sTags: ")
14836 (setq data
14837 (cond
14838 ((eq data nil) "")
14839 ((equal data "") "")
14840 ((stringp data)
14841 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14842 ":"))
14843 ((listp data)
14844 (concat ":" (mapconcat 'identity data ":") ":"))))
14845 (when data
14846 (save-excursion
14847 (org-back-to-heading t)
14848 (when (let ((case-fold-search nil))
14849 (looking-at org-complex-heading-regexp))
14850 (if (match-end 5)
14851 (progn
14852 (goto-char (match-beginning 5))
14853 (insert data)
14854 (delete-region (point) (point-at-eol))
14855 (org-set-tags nil 'align))
14856 (goto-char (point-at-eol))
14857 (insert " " data)
14858 (org-set-tags nil 'align)))
14859 (beginning-of-line 1)
14860 (when (looking-at ".*?\\([ \t]+\\)$")
14861 (delete-region (match-beginning 1) (match-end 1))))))
14863 (defun org-align-all-tags ()
14864 "Align the tags in all headings."
14865 (interactive)
14866 (save-excursion
14867 (or (ignore-errors (org-back-to-heading t))
14868 (outline-next-heading))
14869 (if (org-at-heading-p)
14870 (org-set-tags t)
14871 (message "No headings"))))
14873 (defvar org-indent-indentation-per-level)
14874 (defun org-set-tags (&optional arg just-align)
14875 "Set the tags for the current headline.
14876 With prefix ARG, realign all tags in headings in the current buffer.
14877 When JUST-ALIGN is non-nil, only align tags."
14878 (interactive "P")
14879 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14880 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14881 'region-start-level
14882 'region))
14883 org-loop-over-headlines-in-active-region)
14884 (org-map-entries
14885 ;; We don't use ARG and JUST-ALIGN here because these args
14886 ;; are not useful when looping over headlines.
14887 #'org-set-tags
14888 org-loop-over-headlines-in-active-region
14890 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14891 (let ((org-setting-tags t))
14892 (if arg
14893 (save-excursion
14894 (goto-char (point-min))
14895 (while (re-search-forward org-outline-regexp-bol nil t)
14896 (org-set-tags nil t)
14897 (end-of-line))
14898 (message "All tags realigned to column %d" org-tags-column))
14899 (let* ((current (org-get-tags-string))
14900 (tags
14901 (if just-align current
14902 ;; Get a new set of tags from the user.
14903 (save-excursion
14904 (let* ((seen)
14905 (table
14906 (setq
14907 org-last-tags-completion-table
14908 ;; Uniquify tags in alists, yet preserve
14909 ;; structure (i.e., keywords).
14910 (delq nil
14911 (mapcar
14912 (lambda (pair)
14913 (let ((head (car pair)))
14914 (cond ((symbolp head) pair)
14915 ((member head seen) nil)
14916 (t (push head seen)
14917 pair))))
14918 (append
14919 (or org-current-tag-alist
14920 (org-get-buffer-tags))
14921 (and
14922 org-complete-tags-always-offer-all-agenda-tags
14923 (org-global-tags-completion-table
14924 (org-agenda-files))))))))
14925 (current-tags (org-split-string current ":"))
14926 (inherited-tags
14927 (nreverse (nthcdr (length current-tags)
14928 (nreverse (org-get-tags-at))))))
14929 (replace-regexp-in-string
14930 "\\([-+&]+\\|,\\)"
14932 (if (or (eq t org-use-fast-tag-selection)
14933 (and org-use-fast-tag-selection
14934 (delq nil (mapcar #'cdr table))))
14935 (org-fast-tag-selection
14936 current-tags inherited-tags table
14937 (and org-fast-tag-selection-include-todo
14938 org-todo-key-alist))
14939 (let ((org-add-colon-after-tag-completion
14940 (< 1 (length table))))
14941 (org-trim
14942 (completing-read
14943 "Tags: "
14944 #'org-tags-completion-function
14945 nil nil current 'org-tags-history))))))))))
14947 (when org-tags-sort-function
14948 (setq tags
14949 (mapconcat
14950 #'identity
14951 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14952 org-tags-sort-function)
14953 ":")))
14955 (if (or (string= ":" tags)
14956 (string= "::" tags))
14957 (setq tags ""))
14958 (if (not (org-string-nw-p tags)) (setq tags "")
14959 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14960 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14962 ;; Insert new tags at the correct column.
14963 (unless (equal current tags)
14964 (save-excursion
14965 (beginning-of-line)
14966 (let ((case-fold-search nil))
14967 (looking-at org-complex-heading-regexp))
14968 ;; Remove current tags, if any.
14969 (when (match-end 5) (replace-match "" nil nil nil 5))
14970 ;; Insert new tags, if any. Otherwise, remove trailing
14971 ;; white spaces.
14972 (end-of-line)
14973 (if (not (equal tags ""))
14974 ;; When text is being inserted on an invisible
14975 ;; region boundary, it can be inadvertently sucked
14976 ;; into invisibility.
14977 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14978 (skip-chars-backward " \t")
14979 (delete-region (point) (line-end-position)))))
14980 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14981 ;; is on.
14982 (unless (equal tags "")
14983 (let* ((level (save-excursion
14984 (beginning-of-line)
14985 (skip-chars-forward "\\*")))
14986 (offset (if (bound-and-true-p org-indent-mode)
14987 (* (1- org-indent-indentation-per-level)
14988 (1- level))
14990 (tags-column
14991 (+ org-tags-column
14992 (if (> org-tags-column 0) (- offset) offset))))
14993 (org--align-tags-here tags-column))))
14994 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14996 (defun org-change-tag-in-region (beg end tag off)
14997 "Add or remove TAG for each entry in the region.
14998 This works in the agenda, and also in an Org buffer."
14999 (interactive
15000 (list (region-beginning) (region-end)
15001 (let ((org-last-tags-completion-table
15002 (if (derived-mode-p 'org-mode)
15003 (org-uniquify
15004 (delq nil (append (org-get-buffer-tags)
15005 (org-global-tags-completion-table))))
15006 (org-global-tags-completion-table))))
15007 (completing-read
15008 "Tag: " 'org-tags-completion-function nil nil nil
15009 'org-tags-history))
15010 (progn
15011 (message "[s]et or [r]emove? ")
15012 (equal (read-char-exclusive) ?r))))
15013 (when (fboundp 'deactivate-mark) (deactivate-mark))
15014 (let ((agendap (equal major-mode 'org-agenda-mode))
15015 l1 l2 m buf pos newhead (cnt 0))
15016 (goto-char end)
15017 (setq l2 (1- (org-current-line)))
15018 (goto-char beg)
15019 (setq l1 (org-current-line))
15020 (cl-loop for l from l1 to l2 do
15021 (org-goto-line l)
15022 (setq m (get-text-property (point) 'org-hd-marker))
15023 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15024 (and agendap m))
15025 (setq buf (if agendap (marker-buffer m) (current-buffer))
15026 pos (if agendap m (point)))
15027 (with-current-buffer buf
15028 (save-excursion
15029 (save-restriction
15030 (goto-char pos)
15031 (setq cnt (1+ cnt))
15032 (org-toggle-tag tag (if off 'off 'on))
15033 (setq newhead (org-get-heading)))))
15034 (and agendap (org-agenda-change-all-lines newhead m))))
15035 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15037 (defun org-tags-completion-function (string _predicate &optional flag)
15038 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15039 (confirm (lambda (x) (stringp (car x)))))
15040 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15041 (setq s1 (match-string 1 string)
15042 s2 (match-string 2 string))
15043 (setq s1 "" s2 string))
15044 (cond
15045 ((eq flag nil)
15046 ;; try completion
15047 (setq rtn (try-completion s2 ctable confirm))
15048 (when (stringp rtn)
15049 (setq rtn
15050 (concat s1 s2 (substring rtn (length s2))
15051 (if (and org-add-colon-after-tag-completion
15052 (assoc rtn ctable))
15053 ":" ""))))
15054 rtn)
15055 ((eq flag t)
15056 ;; all-completions
15057 (all-completions s2 ctable confirm))
15058 ((eq flag 'lambda)
15059 ;; exact match?
15060 (assoc s2 ctable)))))
15062 (defun org-fast-tag-insert (kwd tags face &optional end)
15063 "Insert KDW, and the TAGS, the latter with face FACE.
15064 Also insert END."
15065 (insert (format "%-12s" (concat kwd ":"))
15066 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15067 (or end "")))
15069 (defun org-fast-tag-show-exit (flag)
15070 (save-excursion
15071 (org-goto-line 3)
15072 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15073 (replace-match ""))
15074 (when flag
15075 (end-of-line 1)
15076 (org-move-to-column (- (window-width) 19) t)
15077 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15079 (defun org-set-current-tags-overlay (current prefix)
15080 "Add an overlay to CURRENT tag with PREFIX."
15081 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15082 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15083 (org-overlay-display org-tags-overlay (concat prefix s))))
15085 (defvar org-last-tag-selection-key nil)
15086 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15087 "Fast tag selection with single keys.
15088 CURRENT is the current list of tags in the headline, INHERITED is the
15089 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15090 possibly with grouping information. TODO-TABLE is a similar table with
15091 TODO keywords, should these have keys assigned to them.
15092 If the keys are nil, a-z are automatically assigned.
15093 Returns the new tags string, or nil to not change the current settings."
15094 (let* ((fulltable (append table todo-table))
15095 (maxlen (apply 'max (mapcar
15096 (lambda (x)
15097 (if (stringp (car x)) (string-width (car x)) 0))
15098 fulltable)))
15099 (buf (current-buffer))
15100 (expert (eq org-fast-tag-selection-single-key 'expert))
15101 (buffer-tags nil)
15102 (fwidth (+ maxlen 3 1 3))
15103 (ncol (/ (- (window-width) 4) fwidth))
15104 (i-face 'org-done)
15105 (c-face 'org-todo)
15106 tg cnt e c char c1 c2 ntable tbl rtn
15107 ov-start ov-end ov-prefix
15108 (exit-after-next org-fast-tag-selection-single-key)
15109 (done-keywords org-done-keywords)
15110 groups ingroup intaggroup)
15111 (save-excursion
15112 (beginning-of-line 1)
15113 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15114 (setq ov-start (match-beginning 1)
15115 ov-end (match-end 1)
15116 ov-prefix "")
15117 (setq ov-start (1- (point-at-eol))
15118 ov-end (1+ ov-start))
15119 (skip-chars-forward "^\n\r")
15120 (setq ov-prefix
15121 (concat
15122 (buffer-substring (1- (point)) (point))
15123 (if (> (current-column) org-tags-column)
15125 (make-string (- org-tags-column (current-column)) ?\ ))))))
15126 (move-overlay org-tags-overlay ov-start ov-end)
15127 (save-window-excursion
15128 (if expert
15129 (set-buffer (get-buffer-create " *Org tags*"))
15130 (delete-other-windows)
15131 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15132 (org-switch-to-buffer-other-window " *Org tags*"))
15133 (erase-buffer)
15134 (setq-local org-done-keywords done-keywords)
15135 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15136 (org-fast-tag-insert "Current" current c-face "\n\n")
15137 (org-fast-tag-show-exit exit-after-next)
15138 (org-set-current-tags-overlay current ov-prefix)
15139 (setq tbl fulltable char ?a cnt 0)
15140 (while (setq e (pop tbl))
15141 (cond
15142 ((eq (car e) :startgroup)
15143 (push '() groups) (setq ingroup t)
15144 (unless (zerop cnt)
15145 (setq cnt 0)
15146 (insert "\n"))
15147 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15148 ((eq (car e) :endgroup)
15149 (setq ingroup nil cnt 0)
15150 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15151 ((eq (car e) :startgrouptag)
15152 (setq intaggroup t)
15153 (unless (zerop cnt)
15154 (setq cnt 0)
15155 (insert "\n"))
15156 (insert "[ "))
15157 ((eq (car e) :endgrouptag)
15158 (setq intaggroup nil cnt 0)
15159 (insert "]\n"))
15160 ((equal e '(:newline))
15161 (unless (zerop cnt)
15162 (setq cnt 0)
15163 (insert "\n")
15164 (setq e (car tbl))
15165 (while (equal (car tbl) '(:newline))
15166 (insert "\n")
15167 (setq tbl (cdr tbl)))))
15168 ((equal e '(:grouptags)) (insert " : "))
15170 (setq tg (copy-sequence (car e)) c2 nil)
15171 (if (cdr e)
15172 (setq c (cdr e))
15173 ;; automatically assign a character.
15174 (setq c1 (string-to-char
15175 (downcase (substring
15176 tg (if (= (string-to-char tg) ?@) 1 0)))))
15177 (if (or (rassoc c1 ntable) (rassoc c1 table))
15178 (while (or (rassoc char ntable) (rassoc char table))
15179 (setq char (1+ char)))
15180 (setq c2 c1))
15181 (setq c (or c2 char)))
15182 (when ingroup (push tg (car groups)))
15183 (setq tg (org-add-props tg nil 'face
15184 (cond
15185 ((not (assoc tg table))
15186 (org-get-todo-face tg))
15187 ((member tg current) c-face)
15188 ((member tg inherited) i-face))))
15189 (when (equal (caar tbl) :grouptags)
15190 (org-add-props tg nil 'face 'org-tag-group))
15191 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15192 (insert "[" c "] " tg (make-string
15193 (- fwidth 4 (length tg)) ?\ ))
15194 (push (cons tg c) ntable)
15195 (when (= (cl-incf cnt) ncol)
15196 (insert "\n")
15197 (when (or ingroup intaggroup) (insert " "))
15198 (setq cnt 0)))))
15199 (setq ntable (nreverse ntable))
15200 (insert "\n")
15201 (goto-char (point-min))
15202 (unless expert (org-fit-window-to-buffer))
15203 (setq rtn
15204 (catch 'exit
15205 (while t
15206 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15207 (if (not groups) "no " "")
15208 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15209 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15210 (setq org-last-tag-selection-key c)
15211 (cond
15212 ((= c ?\r) (throw 'exit t))
15213 ((= c ?!)
15214 (setq groups (not groups))
15215 (goto-char (point-min))
15216 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15217 ((= c ?\C-c)
15218 (if (not expert)
15219 (org-fast-tag-show-exit
15220 (setq exit-after-next (not exit-after-next)))
15221 (setq expert nil)
15222 (delete-other-windows)
15223 (set-window-buffer (split-window-vertically) " *Org tags*")
15224 (org-switch-to-buffer-other-window " *Org tags*")
15225 (org-fit-window-to-buffer)))
15226 ((or (= c ?\C-g)
15227 (and (= c ?q) (not (rassoc c ntable))))
15228 (delete-overlay org-tags-overlay)
15229 (setq quit-flag t))
15230 ((= c ?\ )
15231 (setq current nil)
15232 (when exit-after-next (setq exit-after-next 'now)))
15233 ((= c ?\t)
15234 (condition-case nil
15235 (setq tg (completing-read
15236 "Tag: "
15237 (or buffer-tags
15238 (with-current-buffer buf
15239 (setq buffer-tags
15240 (org-get-buffer-tags))))))
15241 (quit (setq tg "")))
15242 (when (string-match "\\S-" tg)
15243 (cl-pushnew (list tg) buffer-tags :test #'equal)
15244 (if (member tg current)
15245 (setq current (delete tg current))
15246 (push tg current)))
15247 (when exit-after-next (setq exit-after-next 'now)))
15248 ((setq e (rassoc c todo-table) tg (car e))
15249 (with-current-buffer buf
15250 (save-excursion (org-todo tg)))
15251 (when exit-after-next (setq exit-after-next 'now)))
15252 ((setq e (rassoc c ntable) tg (car e))
15253 (if (member tg current)
15254 (setq current (delete tg current))
15255 (cl-loop for g in groups do
15256 (when (member tg g)
15257 (dolist (x g) (setq current (delete x current)))))
15258 (push tg current))
15259 (when exit-after-next (setq exit-after-next 'now))))
15261 ;; Create a sorted list
15262 (setq current
15263 (sort current
15264 (lambda (a b)
15265 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15266 (when (eq exit-after-next 'now) (throw 'exit t))
15267 (goto-char (point-min))
15268 (beginning-of-line 2)
15269 (delete-region (point) (point-at-eol))
15270 (org-fast-tag-insert "Current" current c-face)
15271 (org-set-current-tags-overlay current ov-prefix)
15272 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15273 (setq tg (match-string 1))
15274 (add-text-properties
15275 (match-beginning 1) (match-end 1)
15276 (list 'face
15277 (cond
15278 ((member tg current) c-face)
15279 ((member tg inherited) i-face)
15280 (t (get-text-property (match-beginning 1) 'face))))))
15281 (goto-char (point-min)))))
15282 (delete-overlay org-tags-overlay)
15283 (if rtn
15284 (mapconcat 'identity current ":")
15285 nil))))
15287 (defun org-get-tags-string ()
15288 "Get the TAGS string in the current headline."
15289 (unless (org-at-heading-p t)
15290 (user-error "Not on a heading"))
15291 (save-excursion
15292 (beginning-of-line 1)
15293 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15294 (match-string-no-properties 1)
15295 "")))
15297 (defun org-get-tags ()
15298 "Get the list of tags specified in the current headline."
15299 (org-split-string (org-get-tags-string) ":"))
15301 (defun org-get-buffer-tags ()
15302 "Get a table of all tags used in the buffer, for completion."
15303 (org-with-wide-buffer
15304 (goto-char (point-min))
15305 (let ((tag-re (concat org-outline-regexp-bol
15306 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15307 tags)
15308 (while (re-search-forward tag-re nil t)
15309 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15310 (push tag tags)))
15311 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15313 ;;;; The mapping API
15315 (defvar org-agenda-skip-comment-trees)
15316 (defvar org-agenda-skip-function)
15317 (defun org-map-entries (func &optional match scope &rest skip)
15318 "Call FUNC at each headline selected by MATCH in SCOPE.
15320 FUNC is a function or a lisp form. The function will be called without
15321 arguments, with the cursor positioned at the beginning of the headline.
15322 The return values of all calls to the function will be collected and
15323 returned as a list.
15325 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15326 does not need to preserve point. After evaluation, the cursor will be
15327 moved to the end of the line (presumably of the headline of the
15328 processed entry) and search continues from there. Under some
15329 circumstances, this may not produce the wanted results. For example,
15330 if you have removed (e.g. archived) the current (sub)tree it could
15331 mean that the next entry will be skipped entirely. In such cases, you
15332 can specify the position from where search should continue by making
15333 FUNC set the variable `org-map-continue-from' to the desired buffer
15334 position.
15336 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15337 Only headlines that are matched by this query will be considered during
15338 the iteration. When MATCH is nil or t, all headlines will be
15339 visited by the iteration.
15341 SCOPE determines the scope of this command. It can be any of:
15343 nil The current buffer, respecting the restriction if any
15344 tree The subtree started with the entry at point
15345 region The entries within the active region, if any
15346 region-start-level
15347 The entries within the active region, but only those at
15348 the same level than the first one.
15349 file The current buffer, without restriction
15350 file-with-archives
15351 The current buffer, and any archives associated with it
15352 agenda All agenda files
15353 agenda-with-archives
15354 All agenda files with any archive files associated with them
15355 \(file1 file2 ...)
15356 If this is a list, all files in the list will be scanned
15358 The remaining args are treated as settings for the skipping facilities of
15359 the scanner. The following items can be given here:
15361 archive skip trees with the archive tag
15362 comment skip trees with the COMMENT keyword
15363 function or Emacs Lisp form:
15364 will be used as value for `org-agenda-skip-function', so
15365 whenever the function returns a position, FUNC will not be
15366 called for that entry and search will continue from the
15367 position returned
15369 If your function needs to retrieve the tags including inherited tags
15370 at the *current* entry, you can use the value of the variable
15371 `org-scanner-tags' which will be much faster than getting the value
15372 with `org-get-tags-at'. If your function gets properties with
15373 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15374 to t around the call to `org-entry-properties' to get the same speedup.
15375 Note that if your function moves around to retrieve tags and properties at
15376 a *different* entry, you cannot use these techniques."
15377 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15378 (not (org-region-active-p)))
15379 (let* ((org-agenda-archives-mode nil) ; just to make sure
15380 (org-agenda-skip-archived-trees (memq 'archive skip))
15381 (org-agenda-skip-comment-trees (memq 'comment skip))
15382 (org-agenda-skip-function
15383 (car (org-delete-all '(comment archive) skip)))
15384 (org-tags-match-list-sublevels t)
15385 (start-level (eq scope 'region-start-level))
15386 matcher res
15387 org-todo-keywords-for-agenda
15388 org-done-keywords-for-agenda
15389 org-todo-keyword-alist-for-agenda
15390 org-tag-alist-for-agenda
15391 org--matcher-tags-todo-only)
15393 (cond
15394 ((eq match t) (setq matcher t))
15395 ((eq match nil) (setq matcher t))
15396 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15398 (save-excursion
15399 (save-restriction
15400 (cond ((eq scope 'tree)
15401 (org-back-to-heading t)
15402 (org-narrow-to-subtree)
15403 (setq scope nil))
15404 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15405 (org-region-active-p))
15406 ;; If needed, set start-level to a string like "2"
15407 (when start-level
15408 (save-excursion
15409 (goto-char (region-beginning))
15410 (unless (org-at-heading-p) (outline-next-heading))
15411 (setq start-level (org-current-level))))
15412 (narrow-to-region (region-beginning)
15413 (save-excursion
15414 (goto-char (region-end))
15415 (unless (and (bolp) (org-at-heading-p))
15416 (outline-next-heading))
15417 (point)))
15418 (setq scope nil)))
15420 (if (not scope)
15421 (progn
15422 (org-agenda-prepare-buffers
15423 (and buffer-file-name (list buffer-file-name)))
15424 (setq res
15425 (org-scan-tags
15426 func matcher org--matcher-tags-todo-only start-level)))
15427 ;; Get the right scope
15428 (cond
15429 ((and scope (listp scope) (symbolp (car scope)))
15430 (setq scope (eval scope)))
15431 ((eq scope 'agenda)
15432 (setq scope (org-agenda-files t)))
15433 ((eq scope 'agenda-with-archives)
15434 (setq scope (org-agenda-files t))
15435 (setq scope (org-add-archive-files scope)))
15436 ((eq scope 'file)
15437 (setq scope (and buffer-file-name (list buffer-file-name))))
15438 ((eq scope 'file-with-archives)
15439 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15440 (org-agenda-prepare-buffers scope)
15441 (dolist (file scope)
15442 (with-current-buffer (org-find-base-buffer-visiting file)
15443 (org-with-wide-buffer
15444 (goto-char (point-min))
15445 (setq res
15446 (append
15448 (org-scan-tags
15449 func matcher org--matcher-tags-todo-only)))))))))
15450 res)))
15452 ;;; Properties API
15454 (defconst org-special-properties
15455 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15456 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15457 "The special properties valid in Org mode.
15458 These are properties that are not defined in the property drawer,
15459 but in some other way.")
15461 (defconst org-default-properties
15462 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15463 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15464 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15465 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15466 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15467 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15468 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15469 "Some properties that are used by Org mode for various purposes.
15470 Being in this list makes sure that they are offered for completion.")
15472 (defun org--valid-property-p (property)
15473 "Non nil when string PROPERTY is a valid property name."
15474 (not
15475 (or (equal property "")
15476 (string-match-p "\\s-" property))))
15478 (defun org--update-property-plist (key val props)
15479 "Associate KEY to VAL in alist PROPS.
15480 Modifications are made by side-effect. Return new alist."
15481 (let* ((appending (string= (substring key -1) "+"))
15482 (key (if appending (substring key 0 -1) key))
15483 (old (assoc-string key props t)))
15484 (if (not old) (cons (cons key val) props)
15485 (setcdr old (if appending (concat (cdr old) " " val) val))
15486 props)))
15488 (defun org-get-property-block (&optional beg force)
15489 "Return the (beg . end) range of the body of the property drawer.
15490 BEG is the beginning of the current subtree, or of the part
15491 before the first headline. If it is not given, it will be found.
15492 If the drawer does not exist, create it if FORCE is non-nil, or
15493 return nil."
15494 (org-with-wide-buffer
15495 (when beg (goto-char beg))
15496 (unless (org-before-first-heading-p)
15497 (let ((beg (cond (beg)
15498 ((or (not (featurep 'org-inlinetask))
15499 (org-inlinetask-in-task-p))
15500 (org-back-to-heading t))
15501 (t (org-with-limited-levels (org-back-to-heading t))))))
15502 (forward-line)
15503 (when (looking-at-p org-planning-line-re) (forward-line))
15504 (cond ((looking-at org-property-drawer-re)
15505 (forward-line)
15506 (cons (point) (progn (goto-char (match-end 0))
15507 (line-beginning-position))))
15508 (force
15509 (goto-char beg)
15510 (org-insert-property-drawer)
15511 (let ((pos (save-excursion (search-forward ":END:")
15512 (line-beginning-position))))
15513 (cons pos pos))))))))
15515 (defun org-at-property-p ()
15516 "Non-nil when point is inside a property drawer.
15517 See `org-property-re' for match data, if applicable."
15518 (save-excursion
15519 (beginning-of-line)
15520 (and (looking-at org-property-re)
15521 (let ((property-drawer (save-match-data (org-get-property-block))))
15522 (and property-drawer
15523 (>= (point) (car property-drawer))
15524 (< (point) (cdr property-drawer)))))))
15526 (defun org-property-action ()
15527 "Do an action on properties."
15528 (interactive)
15529 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15530 (let ((c (read-char-exclusive)))
15531 (cl-case c
15532 (?s (call-interactively #'org-set-property))
15533 (?d (call-interactively #'org-delete-property))
15534 (?D (call-interactively #'org-delete-property-globally))
15535 (?c (call-interactively #'org-compute-property-at-point))
15536 (otherwise (user-error "No such property action %c" c)))))
15538 (defun org-inc-effort ()
15539 "Increment the value of the effort property in the current entry."
15540 (interactive)
15541 (org-set-effort nil t))
15543 (defvar org-clock-effort) ; Defined in org-clock.el.
15544 (defvar org-clock-current-task) ; Defined in org-clock.el.
15545 (defun org-set-effort (&optional value increment)
15546 "Set the effort property of the current entry.
15547 With numerical prefix arg, use the nth allowed value, 0 stands for the
15548 10th allowed value.
15550 When INCREMENT is non-nil, set the property to the next allowed value."
15551 (interactive "P")
15552 (when (equal value 0) (setq value 10))
15553 (let* ((completion-ignore-case t)
15554 (prop org-effort-property)
15555 (cur (org-entry-get nil prop))
15556 (allowed (org-property-get-allowed-values nil prop 'table))
15557 (existing (mapcar 'list (org-property-values prop)))
15558 (heading (nth 4 (org-heading-components)))
15560 (val (cond
15561 ((stringp value) value)
15562 ((and allowed (integerp value))
15563 (or (car (nth (1- value) allowed))
15564 (car (org-last allowed))))
15565 ((and allowed increment)
15566 (or (cl-caadr (member (list cur) allowed))
15567 (user-error "Allowed effort values are not set")))
15568 (allowed
15569 (message "Select 1-9,0, [RET%s]: %s"
15570 (if cur (concat "=" cur) "")
15571 (mapconcat 'car allowed " "))
15572 (setq rpl (read-char-exclusive))
15573 (if (equal rpl ?\r)
15575 (setq rpl (- rpl ?0))
15576 (when (equal rpl 0) (setq rpl 10))
15577 (if (and (> rpl 0) (<= rpl (length allowed)))
15578 (car (nth (1- rpl) allowed))
15579 (org-completing-read "Effort: " allowed nil))))
15581 (org-completing-read
15582 (concat "Effort" (and cur (string-match "\\S-" cur)
15583 (concat " [" cur "]"))
15584 ": ")
15585 existing nil nil "" nil cur)))))
15586 (unless (equal (org-entry-get nil prop) val)
15587 (org-entry-put nil prop val))
15588 (org-refresh-property
15589 '((effort . identity)
15590 (effort-minutes . org-duration-to-minutes))
15591 val)
15592 (when (equal heading (bound-and-true-p org-clock-current-task))
15593 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15594 (org-clock-update-mode-line))
15595 (message "%s is now %s" prop val)))
15597 (defun org-entry-properties (&optional pom which)
15598 "Get all properties of the current entry.
15600 When POM is a buffer position, get all properties from the entry
15601 there instead.
15603 This includes the TODO keyword, the tags, time strings for
15604 deadline, scheduled, and clocking, and any additional properties
15605 defined in the entry.
15607 If WHICH is nil or `all', get all properties. If WHICH is
15608 `special' or `standard', only get that subclass. If WHICH is
15609 a string, only get that property.
15611 Return value is an alist. Keys are properties, as upcased
15612 strings."
15613 (org-with-point-at pom
15614 (when (and (derived-mode-p 'org-mode)
15615 (ignore-errors (org-back-to-heading t)))
15616 (catch 'exit
15617 (let* ((beg (point))
15618 (specific (and (stringp which) (upcase which)))
15619 (which (cond ((not specific) which)
15620 ((member specific org-special-properties) 'special)
15621 (t 'standard)))
15622 props)
15623 ;; Get the special properties, like TODO and TAGS.
15624 (when (memq which '(nil all special))
15625 (when (or (not specific) (string= specific "CLOCKSUM"))
15626 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15627 (when clocksum
15628 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15629 props)))
15630 (when specific (throw 'exit props)))
15631 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15632 (let ((clocksumt (get-text-property (point)
15633 :org-clock-minutes-today)))
15634 (when clocksumt
15635 (push (cons "CLOCKSUM_T"
15636 (org-duration-from-minutes clocksumt))
15637 props)))
15638 (when specific (throw 'exit props)))
15639 (when (or (not specific) (string= specific "ITEM"))
15640 (let ((case-fold-search nil))
15641 (when (looking-at org-complex-heading-regexp)
15642 (push (cons "ITEM"
15643 (let ((title (match-string-no-properties 4)))
15644 (if (org-string-nw-p title)
15645 (org-remove-tabs title)
15646 "")))
15647 props)))
15648 (when specific (throw 'exit props)))
15649 (when (or (not specific) (string= specific "TODO"))
15650 (let ((case-fold-search nil))
15651 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15652 (push (cons "TODO" (match-string-no-properties 2)) props)))
15653 (when specific (throw 'exit props)))
15654 (when (or (not specific) (string= specific "PRIORITY"))
15655 (push (cons "PRIORITY"
15656 (if (looking-at org-priority-regexp)
15657 (match-string-no-properties 2)
15658 (char-to-string org-default-priority)))
15659 props)
15660 (when specific (throw 'exit props)))
15661 (when (or (not specific) (string= specific "FILE"))
15662 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15663 props)
15664 (when specific (throw 'exit props)))
15665 (when (or (not specific) (string= specific "TAGS"))
15666 (let ((value (org-string-nw-p (org-get-tags-string))))
15667 (when value (push (cons "TAGS" value) props)))
15668 (when specific (throw 'exit props)))
15669 (when (or (not specific) (string= specific "ALLTAGS"))
15670 (let ((value (org-get-tags-at)))
15671 (when value
15672 (push (cons "ALLTAGS"
15673 (format ":%s:" (mapconcat #'identity value ":")))
15674 props)))
15675 (when specific (throw 'exit props)))
15676 (when (or (not specific) (string= specific "BLOCKED"))
15677 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15678 (when specific (throw 'exit props)))
15679 (when (or (not specific)
15680 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15681 (forward-line)
15682 (when (looking-at-p org-planning-line-re)
15683 (end-of-line)
15684 (let ((bol (line-beginning-position))
15685 ;; Backward compatibility: time keywords used to
15686 ;; be configurable (before 8.3). Make sure we
15687 ;; get the correct keyword.
15688 (key-assoc `(("CLOSED" . ,org-closed-string)
15689 ("DEADLINE" . ,org-deadline-string)
15690 ("SCHEDULED" . ,org-scheduled-string))))
15691 (dolist (pair (if specific (list (assoc specific key-assoc))
15692 key-assoc))
15693 (save-excursion
15694 (when (search-backward (cdr pair) bol t)
15695 (goto-char (match-end 0))
15696 (skip-chars-forward " \t")
15697 (and (looking-at org-ts-regexp-both)
15698 (push (cons (car pair)
15699 (match-string-no-properties 0))
15700 props)))))))
15701 (when specific (throw 'exit props)))
15702 (when (or (not specific)
15703 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15704 (let ((find-ts
15705 (lambda (end ts)
15706 ;; Fix next time-stamp before END. TS is the
15707 ;; list of time-stamps found so far.
15708 (let ((ts ts)
15709 (regexp (cond
15710 ((string= specific "TIMESTAMP")
15711 org-ts-regexp)
15712 ((string= specific "TIMESTAMP_IA")
15713 org-ts-regexp-inactive)
15714 ((assoc "TIMESTAMP_IA" ts)
15715 org-ts-regexp)
15716 ((assoc "TIMESTAMP" ts)
15717 org-ts-regexp-inactive)
15718 (t org-ts-regexp-both))))
15719 (catch 'next
15720 (while (re-search-forward regexp end t)
15721 (backward-char)
15722 (let ((object (org-element-context)))
15723 ;; Accept to match timestamps in node
15724 ;; properties, too.
15725 (when (memq (org-element-type object)
15726 '(node-property timestamp))
15727 (let ((type
15728 (org-element-property :type object)))
15729 (cond
15730 ((and (memq type '(active active-range))
15731 (not (equal specific "TIMESTAMP_IA")))
15732 (unless (assoc "TIMESTAMP" ts)
15733 (push (cons "TIMESTAMP"
15734 (org-element-property
15735 :raw-value object))
15737 (when specific (throw 'exit ts))))
15738 ((and (memq type '(inactive inactive-range))
15739 (not (string= specific "TIMESTAMP")))
15740 (unless (assoc "TIMESTAMP_IA" ts)
15741 (push (cons "TIMESTAMP_IA"
15742 (org-element-property
15743 :raw-value object))
15745 (when specific (throw 'exit ts))))))
15746 ;; Both timestamp types are found,
15747 ;; move to next part.
15748 (when (= (length ts) 2) (throw 'next ts)))))
15749 ts)))))
15750 (goto-char beg)
15751 ;; First look for timestamps within headline.
15752 (let ((ts (funcall find-ts (line-end-position) nil)))
15753 (if (= (length ts) 2) (setq props (nconc ts props))
15754 ;; Then find timestamps in the section, skipping
15755 ;; planning line.
15756 (let ((end (save-excursion (outline-next-heading))))
15757 (forward-line)
15758 (when (looking-at-p org-planning-line-re) (forward-line))
15759 (setq props (nconc (funcall find-ts end ts) props))))))))
15760 ;; Get the standard properties, like :PROP:.
15761 (when (memq which '(nil all standard))
15762 ;; If we are looking after a specific property, delegate
15763 ;; to `org-entry-get', which is faster. However, make an
15764 ;; exception for "CATEGORY", since it can be also set
15765 ;; through keywords (i.e. #+CATEGORY).
15766 (if (and specific (not (equal specific "CATEGORY")))
15767 (let ((value (org-entry-get beg specific nil t)))
15768 (throw 'exit (and value (list (cons specific value)))))
15769 (let ((range (org-get-property-block beg)))
15770 (when range
15771 (let ((end (cdr range)) seen-base)
15772 (goto-char (car range))
15773 ;; Unlike to `org--update-property-plist', we
15774 ;; handle the case where base values is found
15775 ;; after its extension. We also forbid standard
15776 ;; properties to be named as special properties.
15777 (while (re-search-forward org-property-re end t)
15778 (let* ((key (upcase (match-string-no-properties 2)))
15779 (extendp (string-match-p "\\+\\'" key))
15780 (key-base (if extendp (substring key 0 -1) key))
15781 (value (match-string-no-properties 3)))
15782 (cond
15783 ((member-ignore-case key-base org-special-properties))
15784 (extendp
15785 (setq props
15786 (org--update-property-plist key value props)))
15787 ((member key seen-base))
15788 (t (push key seen-base)
15789 (let ((p (assoc-string key props t)))
15790 (if p (setcdr p (concat value " " (cdr p)))
15791 (push (cons key value) props))))))))))))
15792 (unless (assoc "CATEGORY" props)
15793 (push (cons "CATEGORY" (org-get-category beg)) props)
15794 (when (string= specific "CATEGORY") (throw 'exit props)))
15795 ;; Return value.
15796 props)))))
15798 (defun org--property-local-values (property literal-nil)
15799 "Return value for PROPERTY in current entry.
15800 Value is a list whose car is the base value for PROPERTY and cdr
15801 a list of accumulated values. Return nil if neither is found in
15802 the entry. Also return nil when PROPERTY is set to \"nil\",
15803 unless LITERAL-NIL is non-nil."
15804 (let ((range (org-get-property-block)))
15805 (when range
15806 (goto-char (car range))
15807 (let* ((case-fold-search t)
15808 (end (cdr range))
15809 (value
15810 ;; Base value.
15811 (save-excursion
15812 (let ((v (and (re-search-forward
15813 (org-re-property property nil t) end t)
15814 (match-string-no-properties 3))))
15815 (list (if literal-nil v (org-not-nil v)))))))
15816 ;; Find additional values.
15817 (let* ((property+ (org-re-property (concat property "+") nil t)))
15818 (while (re-search-forward property+ end t)
15819 (push (match-string-no-properties 3) value)))
15820 ;; Return final values.
15821 (and (not (equal value '(nil))) (nreverse value))))))
15823 (defun org--property-global-value (property literal-nil)
15824 "Return value for PROPERTY in current buffer.
15825 Return value is a string. Return nil if property is not set
15826 globally. Also return nil when PROPERTY is set to \"nil\",
15827 unless LITERAL-NIL is non-nil."
15828 (let ((global
15829 (cdr (or (assoc-string property org-file-properties t)
15830 (assoc-string property org-global-properties t)
15831 (assoc-string property org-global-properties-fixed t)))))
15832 (if literal-nil global (org-not-nil global))))
15834 (defun org-entry-get (pom property &optional inherit literal-nil)
15835 "Get value of PROPERTY for entry or content at point-or-marker POM.
15837 If INHERIT is non-nil and the entry does not have the property,
15838 then also check higher levels of the hierarchy. If INHERIT is
15839 the symbol `selective', use inheritance only if the setting in
15840 `org-use-property-inheritance' selects PROPERTY for inheritance.
15842 If the property is present but empty, the return value is the
15843 empty string. If the property is not present at all, nil is
15844 returned. In any other case, return the value as a string.
15845 Search is case-insensitive.
15847 If LITERAL-NIL is set, return the string value \"nil\" as
15848 a string, do not interpret it as the list atom nil. This is used
15849 for inheritance when a \"nil\" value can supersede a non-nil
15850 value higher up the hierarchy."
15851 (org-with-point-at pom
15852 (cond
15853 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15854 ;; We need a special property. Use `org-entry-properties' to
15855 ;; retrieve it, but specify the wanted property.
15856 (cdr (assoc-string property (org-entry-properties nil property))))
15857 ((and inherit
15858 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15859 (org-entry-get-with-inheritance property literal-nil))
15861 (let* ((local (org--property-local-values property literal-nil))
15862 (value (and local (mapconcat #'identity (delq nil local) " "))))
15863 (if literal-nil value (org-not-nil value)))))))
15865 (defun org-property-or-variable-value (var &optional inherit)
15866 "Check if there is a property fixing the value of VAR.
15867 If yes, return this value. If not, return the current value of the variable."
15868 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15869 (if (and prop (stringp prop) (string-match "\\S-" prop))
15870 (read prop)
15871 (symbol-value var))))
15873 (defun org-entry-delete (pom property)
15874 "Delete PROPERTY from entry at point-or-marker POM.
15875 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15876 non-nil when a property was removed."
15877 (org-with-point-at pom
15878 (pcase (org-get-property-block)
15879 (`(,begin . ,origin)
15880 (let* ((end (copy-marker origin))
15881 (re (org-re-property
15882 (concat (regexp-quote property) "\\+?") t t)))
15883 (goto-char begin)
15884 (while (re-search-forward re end t)
15885 (delete-region (match-beginning 0) (line-beginning-position 2)))
15886 ;; If drawer is empty, remove it altogether.
15887 (when (= begin end)
15888 (delete-region (line-beginning-position 0)
15889 (line-beginning-position 2)))
15890 ;; Return non-nil if some property was removed.
15891 (prog1 (/= end origin) (set-marker end nil))))
15892 (_ nil))))
15894 ;; Multi-values properties are properties that contain multiple values
15895 ;; These values are assumed to be single words, separated by whitespace.
15896 (defun org-entry-add-to-multivalued-property (pom property value)
15897 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15898 (let* ((old (org-entry-get pom property))
15899 (values (and old (org-split-string old "[ \t]"))))
15900 (setq value (org-entry-protect-space value))
15901 (unless (member value values)
15902 (setq values (append values (list value)))
15903 (org-entry-put pom property
15904 (mapconcat 'identity values " ")))))
15906 (defun org-entry-remove-from-multivalued-property (pom property value)
15907 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15908 (let* ((old (org-entry-get pom property))
15909 (values (and old (org-split-string old "[ \t]"))))
15910 (setq value (org-entry-protect-space value))
15911 (when (member value values)
15912 (setq values (delete value values))
15913 (org-entry-put pom property
15914 (mapconcat 'identity values " ")))))
15916 (defun org-entry-member-in-multivalued-property (pom property value)
15917 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15918 (let* ((old (org-entry-get pom property))
15919 (values (and old (org-split-string old "[ \t]"))))
15920 (setq value (org-entry-protect-space value))
15921 (member value values)))
15923 (defun org-entry-get-multivalued-property (pom property)
15924 "Return a list of values in a multivalued property."
15925 (let* ((value (org-entry-get pom property))
15926 (values (and value (org-split-string value "[ \t]"))))
15927 (mapcar 'org-entry-restore-space values)))
15929 (defun org-entry-put-multivalued-property (pom property &rest values)
15930 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15931 VALUES should be a list of strings. Spaces will be protected."
15932 (org-entry-put pom property
15933 (mapconcat 'org-entry-protect-space values " "))
15934 (let* ((value (org-entry-get pom property))
15935 (values (and value (org-split-string value "[ \t]"))))
15936 (mapcar 'org-entry-restore-space values)))
15938 (defun org-entry-protect-space (s)
15939 "Protect spaces and newline in string S."
15940 (while (string-match " " s)
15941 (setq s (replace-match "%20" t t s)))
15942 (while (string-match "\n" s)
15943 (setq s (replace-match "%0A" t t s)))
15946 (defun org-entry-restore-space (s)
15947 "Restore spaces and newline in string S."
15948 (while (string-match "%20" s)
15949 (setq s (replace-match " " t t s)))
15950 (while (string-match "%0A" s)
15951 (setq s (replace-match "\n" t t s)))
15954 (defvar org-entry-property-inherited-from (make-marker)
15955 "Marker pointing to the entry from where a property was inherited.
15956 Each call to `org-entry-get-with-inheritance' will set this marker to the
15957 location of the entry where the inheritance search matched. If there was
15958 no match, the marker will point nowhere.
15959 Note that also `org-entry-get' calls this function, if the INHERIT flag
15960 is set.")
15962 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15963 "Get PROPERTY of entry or content at point, search higher levels if needed.
15964 The search will stop at the first ancestor which has the property defined.
15965 If the value found is \"nil\", return nil to show that the property
15966 should be considered as undefined (this is the meaning of nil here).
15967 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15968 (move-marker org-entry-property-inherited-from nil)
15969 (org-with-wide-buffer
15970 (let (value)
15971 (catch 'exit
15972 (while t
15973 (let ((v (org--property-local-values property literal-nil)))
15974 (when v
15975 (setq value
15976 (concat (mapconcat #'identity (delq nil v) " ")
15977 (and value " ")
15978 value)))
15979 (cond
15980 ((car v)
15981 (org-back-to-heading t)
15982 (move-marker org-entry-property-inherited-from (point))
15983 (throw 'exit nil))
15984 ((org-up-heading-safe))
15986 (let ((global (org--property-global-value property literal-nil)))
15987 (cond ((not global))
15988 (value (setq value (concat global " " value)))
15989 (t (setq value global))))
15990 (throw 'exit nil))))))
15991 (if literal-nil value (org-not-nil value)))))
15993 (defvar org-property-changed-functions nil
15994 "Hook called when the value of a property has changed.
15995 Each hook function should accept two arguments, the name of the property
15996 and the new value.")
15998 (defun org-entry-put (pom property value)
15999 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16001 If the value is nil, it is converted to the empty string. If it
16002 is not a string, an error is raised. Also raise an error on
16003 invalid property names.
16005 PROPERTY can be any regular property (see
16006 `org-special-properties'). It can also be \"TODO\",
16007 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16009 For the last two properties, VALUE may have any of the special
16010 values \"earlier\" and \"later\". The function then increases or
16011 decreases scheduled or deadline date by one day."
16012 (cond ((null value) (setq value ""))
16013 ((not (stringp value)) (error "Properties values should be strings"))
16014 ((not (org--valid-property-p property))
16015 (user-error "Invalid property name: \"%s\"" property)))
16016 (org-with-point-at pom
16017 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16018 (org-back-to-heading t)
16019 (org-with-limited-levels (org-back-to-heading t)))
16020 (let ((beg (point)))
16021 (cond
16022 ((equal property "TODO")
16023 (cond ((not (org-string-nw-p value)) (setq value 'none))
16024 ((not (member value org-todo-keywords-1))
16025 (user-error "\"%s\" is not a valid TODO state" value)))
16026 (org-todo value)
16027 (org-set-tags nil 'align))
16028 ((equal property "PRIORITY")
16029 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16030 (org-set-tags nil 'align))
16031 ((equal property "SCHEDULED")
16032 (forward-line)
16033 (if (and (looking-at-p org-planning-line-re)
16034 (re-search-forward
16035 org-scheduled-time-regexp (line-end-position) t))
16036 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16037 ((string= value "later") (org-timestamp-change 1 'day))
16038 ((string= value "") (org-schedule '(4)))
16039 (t (org-schedule nil value)))
16040 (if (member value '("earlier" "later" ""))
16041 (call-interactively #'org-schedule)
16042 (org-schedule nil value))))
16043 ((equal property "DEADLINE")
16044 (forward-line)
16045 (if (and (looking-at-p org-planning-line-re)
16046 (re-search-forward
16047 org-deadline-time-regexp (line-end-position) t))
16048 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16049 ((string= value "later") (org-timestamp-change 1 'day))
16050 ((string= value "") (org-deadline '(4)))
16051 (t (org-deadline nil value)))
16052 (if (member value '("earlier" "later" ""))
16053 (call-interactively #'org-deadline)
16054 (org-deadline nil value))))
16055 ((member property org-special-properties)
16056 (error "The %s property cannot be set with `org-entry-put'" property))
16058 (let* ((range (org-get-property-block beg 'force))
16059 (end (cdr range))
16060 (case-fold-search t))
16061 (goto-char (car range))
16062 (if (re-search-forward (org-re-property property nil t) end t)
16063 (progn (delete-region (match-beginning 0) (match-end 0))
16064 (goto-char (match-beginning 0)))
16065 (goto-char end)
16066 (insert "\n")
16067 (backward-char))
16068 (insert ":" property ":")
16069 (when value (insert " " value))
16070 (org-indent-line)))))
16071 (run-hook-with-args 'org-property-changed-functions property value)))
16073 (defun org-buffer-property-keys
16074 (&optional specials defaults columns ignore-malformed)
16075 "Get all property keys in the current buffer.
16077 When SPECIALS is non-nil, also list the special properties that
16078 reflect things like tags and TODO state.
16080 When DEFAULTS is non-nil, also include properties that has
16081 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16082 DESCRIPTION, LOCATION, and LOGGING and others.
16084 When COLUMNS in non-nil, also include property names given in
16085 COLUMN formats in the current buffer.
16087 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16088 automatically performed, such drawers will be silently ignored."
16089 (let ((case-fold-search t)
16090 (props (append
16091 (and specials org-special-properties)
16092 (and defaults (cons org-effort-property org-default-properties))
16093 nil)))
16094 (org-with-wide-buffer
16095 (goto-char (point-min))
16096 (while (re-search-forward org-property-start-re nil t)
16097 (let ((range (org-get-property-block)))
16098 (catch 'skip
16099 (unless range
16100 (when (and (not ignore-malformed)
16101 (not (org-before-first-heading-p))
16102 (y-or-n-p (format "Malformed drawer at %d, repair?"
16103 (line-beginning-position))))
16104 (org-get-property-block nil t))
16105 (throw 'skip nil))
16106 (goto-char (car range))
16107 (let ((begin (car range))
16108 (end (cdr range)))
16109 ;; Make sure that found property block is not located
16110 ;; before current point, as it would generate an infloop.
16111 ;; It can happen, for example, in the following
16112 ;; situation:
16114 ;; * Headline
16115 ;; :PROPERTIES:
16116 ;; ...
16117 ;; :END:
16118 ;; *************** Inlinetask
16119 ;; #+BEGIN_EXAMPLE
16120 ;; :PROPERTIES:
16121 ;; #+END_EXAMPLE
16123 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16124 (while (< (point) end)
16125 (let ((p (progn (looking-at org-property-re)
16126 (match-string-no-properties 2))))
16127 ;; Only add true property name, not extension symbol.
16128 (push (if (not (string-match-p "\\+\\'" p)) p
16129 (substring p 0 -1))
16130 props))
16131 (forward-line))))
16132 (outline-next-heading)))
16133 (when columns
16134 (goto-char (point-min))
16135 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16136 (let ((element (org-element-at-point)))
16137 (when (memq (org-element-type element) '(keyword node-property))
16138 (let ((value (org-element-property :value element))
16139 (start 0))
16140 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16141 (setq start (match-end 0))
16142 (let ((p (match-string-no-properties 1 value)))
16143 (unless (member-ignore-case p org-special-properties)
16144 (push p props))))))))))
16145 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16147 (defun org-property-values (key)
16148 "List all non-nil values of property KEY in current buffer."
16149 (org-with-wide-buffer
16150 (goto-char (point-min))
16151 (let ((case-fold-search t)
16152 (re (org-re-property key))
16153 values)
16154 (while (re-search-forward re nil t)
16155 (push (org-entry-get (point) key) values))
16156 (delete-dups values))))
16158 (defun org-insert-property-drawer ()
16159 "Insert a property drawer into the current entry."
16160 (org-with-wide-buffer
16161 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16162 (org-back-to-heading t)
16163 (org-with-limited-levels (org-back-to-heading t)))
16164 (forward-line)
16165 (when (looking-at-p org-planning-line-re) (forward-line))
16166 (unless (looking-at-p org-property-drawer-re)
16167 ;; Make sure we start editing a line from current entry, not from
16168 ;; next one. It prevents extending text properties or overlays
16169 ;; belonging to the latter.
16170 (when (bolp) (backward-char))
16171 (let ((begin (1+ (point)))
16172 (inhibit-read-only t))
16173 (insert "\n:PROPERTIES:\n:END:")
16174 (when (eobp) (insert "\n"))
16175 (org-indent-region begin (point))))))
16177 (defun org-insert-drawer (&optional arg drawer)
16178 "Insert a drawer at point.
16180 When optional argument ARG is non-nil, insert a property drawer.
16182 Optional argument DRAWER, when non-nil, is a string representing
16183 drawer's name. Otherwise, the user is prompted for a name.
16185 If a region is active, insert the drawer around that region
16186 instead.
16188 Point is left between drawer's boundaries."
16189 (interactive "P")
16190 (let* ((drawer (if arg "PROPERTIES"
16191 (or drawer (read-from-minibuffer "Drawer: ")))))
16192 (cond
16193 ;; With C-u, fall back on `org-insert-property-drawer'
16194 (arg (org-insert-property-drawer))
16195 ;; Check validity of suggested drawer's name.
16196 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16197 (user-error "Invalid drawer name"))
16198 ;; With an active region, insert a drawer at point.
16199 ((not (org-region-active-p))
16200 (progn
16201 (unless (bolp) (insert "\n"))
16202 (insert (format ":%s:\n\n:END:\n" drawer))
16203 (forward-line -2)))
16204 ;; Otherwise, insert the drawer at point
16206 (let ((rbeg (region-beginning))
16207 (rend (copy-marker (region-end))))
16208 (unwind-protect
16209 (progn
16210 (goto-char rbeg)
16211 (beginning-of-line)
16212 (when (save-excursion
16213 (re-search-forward org-outline-regexp-bol rend t))
16214 (user-error "Drawers cannot contain headlines"))
16215 ;; Position point at the beginning of the first
16216 ;; non-blank line in region. Insert drawer's opening
16217 ;; there, then indent it.
16218 (org-skip-whitespace)
16219 (beginning-of-line)
16220 (insert ":" drawer ":\n")
16221 (forward-line -1)
16222 (indent-for-tab-command)
16223 ;; Move point to the beginning of the first blank line
16224 ;; after the last non-blank line in region. Insert
16225 ;; drawer's closing, then indent it.
16226 (goto-char rend)
16227 (skip-chars-backward " \r\t\n")
16228 (insert "\n:END:")
16229 (deactivate-mark t)
16230 (indent-for-tab-command)
16231 (unless (eolp) (insert "\n")))
16232 ;; Clear marker, whatever the outcome of insertion is.
16233 (set-marker rend nil)))))))
16235 (defvar org-property-set-functions-alist nil
16236 "Property set function alist.
16237 Each entry should have the following format:
16239 (PROPERTY . READ-FUNCTION)
16241 The read function will be called with the same argument as
16242 `org-completing-read'.")
16244 (defun org-set-property-function (property)
16245 "Get the function that should be used to set PROPERTY.
16246 This is computed according to `org-property-set-functions-alist'."
16247 (or (cdr (assoc property org-property-set-functions-alist))
16248 'org-completing-read))
16250 (defun org-read-property-value (property)
16251 "Read PROPERTY value from user."
16252 (let* ((completion-ignore-case t)
16253 (allowed (org-property-get-allowed-values nil property 'table))
16254 (cur (org-entry-get nil property))
16255 (prompt (concat property " value"
16256 (if (and cur (string-match "\\S-" cur))
16257 (concat " [" cur "]") "") ": "))
16258 (set-function (org-set-property-function property))
16259 (val (if allowed
16260 (funcall set-function prompt allowed nil
16261 (not (get-text-property 0 'org-unrestricted
16262 (caar allowed))))
16263 (funcall set-function prompt
16264 (mapcar 'list (org-property-values property))
16265 nil nil "" nil cur))))
16266 (org-trim val)))
16268 (defvar org-last-set-property nil)
16269 (defvar org-last-set-property-value nil)
16270 (defun org-read-property-name ()
16271 "Read a property name."
16272 (let ((completion-ignore-case t)
16273 (default-prop (or (and (org-at-property-p)
16274 (match-string-no-properties 2))
16275 org-last-set-property)))
16276 (org-completing-read
16277 (concat "Property"
16278 (if default-prop (concat " [" default-prop "]") "")
16279 ": ")
16280 (mapcar #'list (org-buffer-property-keys nil t t))
16281 nil nil nil nil default-prop)))
16283 (defun org-set-property-and-value (use-last)
16284 "Allow to set [PROPERTY]: [value] direction from prompt.
16285 When use-default, don't even ask, just use the last
16286 \"[PROPERTY]: [value]\" string from the history."
16287 (interactive "P")
16288 (let* ((completion-ignore-case t)
16289 (pv (or (and use-last org-last-set-property-value)
16290 (org-completing-read
16291 "Enter a \"[Property]: [value]\" pair: "
16292 nil nil nil nil nil
16293 org-last-set-property-value)))
16294 prop val)
16295 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16296 (setq prop (match-string 1 pv)
16297 val (match-string 2 pv))
16298 (org-set-property prop val))))
16300 (defun org-set-property (property value)
16301 "In the current entry, set PROPERTY to VALUE.
16303 When called interactively, this will prompt for a property name, offering
16304 completion on existing and default properties. And then it will prompt
16305 for a value, offering completion either on allowed values (via an inherited
16306 xxx_ALL property) or on existing values in other instances of this property
16307 in the current file.
16309 Throw an error when trying to set a property with an invalid name."
16310 (interactive (list nil nil))
16311 (let ((property (or property (org-read-property-name))))
16312 ;; `org-entry-put' also makes the following check, but this one
16313 ;; avoids polluting `org-last-set-property' and
16314 ;; `org-last-set-property-value' needlessly.
16315 (unless (org--valid-property-p property)
16316 (user-error "Invalid property name: \"%s\"" property))
16317 (let ((value (or value (org-read-property-value property)))
16318 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16319 (setq org-last-set-property property)
16320 (setq org-last-set-property-value (concat property ": " value))
16321 ;; Possibly postprocess the inserted value:
16322 (when fn (setq value (funcall fn value)))
16323 (unless (equal (org-entry-get nil property) value)
16324 (org-entry-put nil property value)))))
16326 (defun org-find-property (property &optional value)
16327 "Find first entry in buffer that sets PROPERTY.
16329 When optional argument VALUE is non-nil, only consider an entry
16330 if it contains PROPERTY set to this value. If PROPERTY should be
16331 explicitly set to nil, use string \"nil\" for VALUE.
16333 Return position where the entry begins, or nil if there is no
16334 such entry. If narrowing is in effect, only search the visible
16335 part of the buffer."
16336 (save-excursion
16337 (goto-char (point-min))
16338 (let ((case-fold-search t)
16339 (re (org-re-property property nil (not value) value)))
16340 (catch 'exit
16341 (while (re-search-forward re nil t)
16342 (when (if value (org-at-property-p)
16343 (org-entry-get (point) property nil t))
16344 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16346 (defun org-delete-property (property)
16347 "In the current entry, delete PROPERTY."
16348 (interactive
16349 (let* ((completion-ignore-case t)
16350 (cat (org-entry-get (point) "CATEGORY"))
16351 (props0 (org-entry-properties nil 'standard))
16352 (props (if cat props0
16353 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16354 (prop (if (< 1 (length props))
16355 (completing-read "Property: " props nil t)
16356 (caar props))))
16357 (list prop)))
16358 (if (not property)
16359 (message "No property to delete in this entry")
16360 (org-entry-delete nil property)
16361 (message "Property \"%s\" deleted" property)))
16363 (defun org-delete-property-globally (property)
16364 "Remove PROPERTY globally, from all entries.
16365 This function ignores narrowing, if any."
16366 (interactive
16367 (let* ((completion-ignore-case t)
16368 (prop (completing-read
16369 "Globally remove property: "
16370 (mapcar #'list (org-buffer-property-keys)))))
16371 (list prop)))
16372 (org-with-wide-buffer
16373 (goto-char (point-min))
16374 (let ((count 0)
16375 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16376 (while (re-search-forward re nil t)
16377 (when (org-entry-delete (point) property) (cl-incf count)))
16378 (message "Property \"%s\" removed from %d entries" property count))))
16380 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16382 (defun org-compute-property-at-point ()
16383 "Compute the property at point.
16384 This looks for an enclosing column format, extracts the operator and
16385 then applies it to the property in the column format's scope."
16386 (interactive)
16387 (unless (org-at-property-p)
16388 (user-error "Not at a property"))
16389 (let ((prop (match-string-no-properties 2)))
16390 (org-columns-get-format-and-top-level)
16391 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16392 (user-error "No operator defined for property %s" prop))
16393 (org-columns-compute prop)))
16395 (defvar org-property-allowed-value-functions nil
16396 "Hook for functions supplying allowed values for a specific property.
16397 The functions must take a single argument, the name of the property, and
16398 return a flat list of allowed values. If \":ETC\" is one of
16399 the values, this means that these values are intended as defaults for
16400 completion, but that other values should be allowed too.
16401 The functions must return nil if they are not responsible for this
16402 property.")
16404 (defun org-property-get-allowed-values (pom property &optional table)
16405 "Get allowed values for the property PROPERTY.
16406 When TABLE is non-nil, return an alist that can directly be used for
16407 completion."
16408 (let (vals)
16409 (cond
16410 ((equal property "TODO")
16411 (setq vals (org-with-point-at pom
16412 (append org-todo-keywords-1 '("")))))
16413 ((equal property "PRIORITY")
16414 (let ((n org-lowest-priority))
16415 (while (>= n org-highest-priority)
16416 (push (char-to-string n) vals)
16417 (setq n (1- n)))))
16418 ((equal property "CATEGORY"))
16419 ((member property org-special-properties))
16420 ((setq vals (run-hook-with-args-until-success
16421 'org-property-allowed-value-functions property)))
16423 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16424 (when (and vals (string-match "\\S-" vals))
16425 (setq vals (car (read-from-string (concat "(" vals ")"))))
16426 (setq vals (mapcar (lambda (x)
16427 (cond ((stringp x) x)
16428 ((numberp x) (number-to-string x))
16429 ((symbolp x) (symbol-name x))
16430 (t "???")))
16431 vals)))))
16432 (when (member ":ETC" vals)
16433 (setq vals (remove ":ETC" vals))
16434 (org-add-props (car vals) '(org-unrestricted t)))
16435 (if table (mapcar 'list vals) vals)))
16437 (defun org-property-previous-allowed-value (&optional _previous)
16438 "Switch to the next allowed value for this property."
16439 (interactive)
16440 (org-property-next-allowed-value t))
16442 (defun org-property-next-allowed-value (&optional previous)
16443 "Switch to the next allowed value for this property."
16444 (interactive)
16445 (unless (org-at-property-p)
16446 (user-error "Not at a property"))
16447 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16448 (key (match-string 2))
16449 (value (match-string 3))
16450 (allowed (or (org-property-get-allowed-values (point) key)
16451 (and (member value '("[ ]" "[-]" "[X]"))
16452 '("[ ]" "[X]"))))
16453 (heading (save-match-data (nth 4 (org-heading-components))))
16454 nval)
16455 (unless allowed
16456 (user-error "Allowed values for this property have not been defined"))
16457 (when previous (setq allowed (reverse allowed)))
16458 (when (member value allowed)
16459 (setq nval (car (cdr (member value allowed)))))
16460 (setq nval (or nval (car allowed)))
16461 (when (equal nval value)
16462 (user-error "Only one allowed value for this property"))
16463 (org-at-property-p)
16464 (replace-match (concat " :" key ": " nval) t t)
16465 (org-indent-line)
16466 (beginning-of-line 1)
16467 (skip-chars-forward " \t")
16468 (when (equal prop org-effort-property)
16469 (org-refresh-property
16470 '((effort . identity)
16471 (effort-minutes . org-duration-to-minutes))
16472 nval)
16473 (when (string= org-clock-current-task heading)
16474 (setq org-clock-effort nval)
16475 (org-clock-update-mode-line)))
16476 (run-hook-with-args 'org-property-changed-functions key nval)))
16478 (defun org-find-olp (path &optional this-buffer)
16479 "Return a marker pointing to the entry at outline path OLP.
16480 If anything goes wrong, throw an error.
16481 You can wrap this call to catch the error like this:
16483 (condition-case msg
16484 (org-mobile-locate-entry (match-string 4))
16485 (error (nth 1 msg)))
16487 The return value will then be either a string with the error message,
16488 or a marker if everything is OK.
16490 If THIS-BUFFER is set, the outline path does not contain a file,
16491 only headings."
16492 (let* ((file (if this-buffer buffer-file-name (pop path)))
16493 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16494 (level 1)
16495 (lmin 1)
16496 (lmax 1)
16497 end found flevel)
16498 (unless buffer (error "File not found :%s" file))
16499 (with-current-buffer buffer
16500 (unless (derived-mode-p 'org-mode)
16501 (error "Buffer %s needs to be in Org mode" buffer))
16502 (org-with-wide-buffer
16503 (goto-char (point-min))
16504 (dolist (heading path)
16505 (let ((re (format org-complex-heading-regexp-format
16506 (regexp-quote heading)))
16507 (cnt 0))
16508 (while (re-search-forward re end t)
16509 (setq level (- (match-end 1) (match-beginning 1)))
16510 (when (and (>= level lmin) (<= level lmax))
16511 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16512 (when (= cnt 0)
16513 (error "Heading not found on level %d: %s" lmax heading))
16514 (when (> cnt 1)
16515 (error "Heading not unique on level %d: %s" lmax heading))
16516 (goto-char found)
16517 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16518 (setq end (save-excursion (org-end-of-subtree t t)))))
16519 (when (org-at-heading-p)
16520 (point-marker))))))
16522 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16523 "Find node HEADING in BUFFER.
16524 Return a marker to the heading if it was found, or nil if not.
16525 If POS-ONLY is set, return just the position instead of a marker.
16527 The heading text must match exact, but it may have a TODO keyword,
16528 a priority cookie and tags in the standard locations."
16529 (with-current-buffer (or buffer (current-buffer))
16530 (org-with-wide-buffer
16531 (goto-char (point-min))
16532 (let (case-fold-search)
16533 (when (re-search-forward
16534 (format org-complex-heading-regexp-format
16535 (regexp-quote heading)) nil t)
16536 (if pos-only
16537 (match-beginning 0)
16538 (move-marker (make-marker) (match-beginning 0))))))))
16540 (defun org-find-exact-heading-in-directory (heading &optional dir)
16541 "Find Org node headline HEADING in all .org files in directory DIR.
16542 When the target headline is found, return a marker to this location."
16543 (let ((files (directory-files (or dir default-directory)
16544 t "\\`[^.#].*\\.org\\'"))
16545 visiting m buffer)
16546 (catch 'found
16547 (dolist (file files)
16548 (message "trying %s" file)
16549 (setq visiting (org-find-base-buffer-visiting file))
16550 (setq buffer (or visiting (find-file-noselect file)))
16551 (setq m (org-find-exact-headline-in-buffer
16552 heading buffer))
16553 (when (and (not m) (not visiting)) (kill-buffer buffer))
16554 (and m (throw 'found m))))))
16556 (defun org-find-entry-with-id (ident)
16557 "Locate the entry that contains the ID property with exact value IDENT.
16558 IDENT can be a string, a symbol or a number, this function will search for
16559 the string representation of it.
16560 Return the position where this entry starts, or nil if there is no such entry."
16561 (interactive "sID: ")
16562 (let ((id (cond
16563 ((stringp ident) ident)
16564 ((symbolp ident) (symbol-name ident))
16565 ((numberp ident) (number-to-string ident))
16566 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16567 (org-with-wide-buffer (org-find-property "ID" id))))
16569 ;;;; Timestamps
16571 (defvar org-last-changed-timestamp nil)
16572 (defvar org-last-inserted-timestamp nil
16573 "The last time stamp inserted with `org-insert-time-stamp'.")
16575 (defun org-time-stamp (arg &optional inactive)
16576 "Prompt for a date/time and insert a time stamp.
16578 If the user specifies a time like HH:MM or if this command is
16579 called with at least one prefix argument, the time stamp contains
16580 the date and the time. Otherwise, only the date is included.
16582 All parts of a date not specified by the user are filled in from
16583 the timestamp at point, if any, or the current date/time
16584 otherwise.
16586 If there is already a timestamp at the cursor, it is replaced.
16588 With two universal prefix arguments, insert an active timestamp
16589 with the current time without prompting the user.
16591 When called from lisp, the timestamp is inactive if INACTIVE is
16592 non-nil."
16593 (interactive "P")
16594 (let* ((ts (cond
16595 ((org-at-date-range-p t)
16596 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16597 ((org-at-timestamp-p 'lax) (match-string 0))))
16598 ;; Default time is either the timestamp at point or today.
16599 ;; When entering a range, only the range start is considered.
16600 (default-time (if (not ts) (current-time)
16601 (apply #'encode-time (org-parse-time-string ts))))
16602 (default-input (and ts (org-get-compact-tod ts)))
16603 (repeater (and ts
16604 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16605 (match-string 0 ts)))
16606 org-time-was-given
16607 org-end-time-was-given
16608 (time
16609 (and (if (equal arg '(16)) (current-time)
16610 ;; Preserve `this-command' and `last-command'.
16611 (let ((this-command this-command)
16612 (last-command last-command))
16613 (org-read-date
16614 arg 'totime nil nil default-time default-input
16615 inactive))))))
16616 (cond
16617 ((and ts
16618 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16619 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16620 (insert "--")
16621 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16623 ;; Make sure we're on a timestamp. When in the middle of a date
16624 ;; range, move arbitrarily to range end.
16625 (unless (org-at-timestamp-p 'lax)
16626 (skip-chars-forward "-")
16627 (org-at-timestamp-p 'lax))
16628 (replace-match "")
16629 (setq org-last-changed-timestamp
16630 (org-insert-time-stamp
16631 time (or org-time-was-given arg)
16632 inactive nil nil (list org-end-time-was-given)))
16633 (when repeater
16634 (backward-char)
16635 (insert " " repeater)
16636 (setq org-last-changed-timestamp
16637 (concat (substring org-last-inserted-timestamp 0 -1)
16638 " " repeater ">")))
16639 (message "Timestamp updated"))
16640 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16641 (t (org-insert-time-stamp
16642 time (or org-time-was-given arg) inactive nil nil
16643 (list org-end-time-was-given))))))
16645 ;; FIXME: can we use this for something else, like computing time differences?
16646 (defun org-get-compact-tod (s)
16647 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16648 (let* ((t1 (match-string 1 s))
16649 (h1 (string-to-number (match-string 2 s)))
16650 (m1 (string-to-number (match-string 3 s)))
16651 (t2 (and (match-end 4) (match-string 5 s)))
16652 (h2 (and t2 (string-to-number (match-string 6 s))))
16653 (m2 (and t2 (string-to-number (match-string 7 s))))
16654 dh dm)
16655 (if (not t2)
16657 (setq dh (- h2 h1) dm (- m2 m1))
16658 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16659 (concat t1 "+" (number-to-string dh)
16660 (and (/= 0 dm) (format ":%02d" dm)))))))
16662 (defun org-time-stamp-inactive (&optional arg)
16663 "Insert an inactive time stamp.
16664 An inactive time stamp is enclosed in square brackets instead of angle
16665 brackets. It is inactive in the sense that it does not trigger agenda entries,
16666 does not link to the calendar and cannot be changed with the S-cursor keys.
16667 So these are more for recording a certain time/date."
16668 (interactive "P")
16669 (org-time-stamp arg 'inactive))
16671 (defvar org-date-ovl (make-overlay 1 1))
16672 (overlay-put org-date-ovl 'face 'org-date-selected)
16673 (delete-overlay org-date-ovl)
16675 (defvar org-ans1) ; dynamically scoped parameter
16676 (defvar org-ans2) ; dynamically scoped parameter
16678 (defvar org-plain-time-of-day-regexp) ; defined below
16680 (defvar org-overriding-default-time nil) ; dynamically scoped
16681 (defvar org-read-date-overlay nil)
16682 (defvar org-dcst nil) ; dynamically scoped
16683 (defvar org-read-date-history nil)
16684 (defvar org-read-date-final-answer nil)
16685 (defvar org-read-date-analyze-futurep nil)
16686 (defvar org-read-date-analyze-forced-year nil)
16687 (defvar org-read-date-inactive)
16689 (defvar org-read-date-minibuffer-local-map
16690 (let* ((map (make-sparse-keymap)))
16691 (set-keymap-parent map minibuffer-local-map)
16692 (org-defkey map (kbd ".")
16693 (lambda () (interactive)
16694 ;; Are we at the beginning of the prompt?
16695 (if (looking-back "^[^:]+: "
16696 (let ((inhibit-field-text-motion t))
16697 (line-beginning-position)))
16698 (org-eval-in-calendar '(calendar-goto-today))
16699 (insert "."))))
16700 (org-defkey map (kbd "C-.")
16701 (lambda () (interactive)
16702 (org-eval-in-calendar '(calendar-goto-today))))
16703 (org-defkey map [(meta shift left)]
16704 (lambda () (interactive)
16705 (org-eval-in-calendar '(calendar-backward-month 1))))
16706 (org-defkey map [(meta shift right)]
16707 (lambda () (interactive)
16708 (org-eval-in-calendar '(calendar-forward-month 1))))
16709 (org-defkey map [(meta shift up)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-backward-year 1))))
16712 (org-defkey map [(meta shift down)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-forward-year 1))))
16715 (org-defkey map [?\e (shift left)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-backward-month 1))))
16718 (org-defkey map [?\e (shift right)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-forward-month 1))))
16721 (org-defkey map [?\e (shift up)]
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-backward-year 1))))
16724 (org-defkey map [?\e (shift down)]
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-forward-year 1))))
16727 (org-defkey map [(shift up)]
16728 (lambda () (interactive)
16729 (org-eval-in-calendar '(calendar-backward-week 1))))
16730 (org-defkey map [(shift down)]
16731 (lambda () (interactive)
16732 (org-eval-in-calendar '(calendar-forward-week 1))))
16733 (org-defkey map [(shift left)]
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(calendar-backward-day 1))))
16736 (org-defkey map [(shift right)]
16737 (lambda () (interactive)
16738 (org-eval-in-calendar '(calendar-forward-day 1))))
16739 (org-defkey map "!"
16740 (lambda () (interactive)
16741 (org-eval-in-calendar '(diary-view-entries))
16742 (message "")))
16743 (org-defkey map ">"
16744 (lambda () (interactive)
16745 (org-eval-in-calendar '(calendar-scroll-left 1))))
16746 (org-defkey map "<"
16747 (lambda () (interactive)
16748 (org-eval-in-calendar '(calendar-scroll-right 1))))
16749 (org-defkey map "\C-v"
16750 (lambda () (interactive)
16751 (org-eval-in-calendar
16752 '(calendar-scroll-left-three-months 1))))
16753 (org-defkey map "\M-v"
16754 (lambda () (interactive)
16755 (org-eval-in-calendar
16756 '(calendar-scroll-right-three-months 1))))
16757 map)
16758 "Keymap for minibuffer commands when using `org-read-date'.")
16760 (defvar org-def)
16761 (defvar org-defdecode)
16762 (defvar org-with-time)
16764 (defvar calendar-setup) ; Dynamically scoped.
16765 (defun org-read-date (&optional with-time to-time from-string prompt
16766 default-time default-input inactive)
16767 "Read a date, possibly a time, and make things smooth for the user.
16768 The prompt will suggest to enter an ISO date, but you can also enter anything
16769 which will at least partially be understood by `parse-time-string'.
16770 Unrecognized parts of the date will default to the current day, month, year,
16771 hour and minute. If this command is called to replace a timestamp at point,
16772 or to enter the second timestamp of a range, the default time is taken
16773 from the existing stamp. Furthermore, the command prefers the future,
16774 so if you are giving a date where the year is not given, and the day-month
16775 combination is already past in the current year, it will assume you
16776 mean next year. For details, see the manual. A few examples:
16778 3-2-5 --> 2003-02-05
16779 feb 15 --> currentyear-02-15
16780 2/15 --> currentyear-02-15
16781 sep 12 9 --> 2009-09-12
16782 12:45 --> today 12:45
16783 22 sept 0:34 --> currentyear-09-22 0:34
16784 12 --> currentyear-currentmonth-12
16785 Fri --> nearest Friday after today
16786 -Tue --> last Tuesday
16787 etc.
16789 Furthermore you can specify a relative date by giving, as the *first* thing
16790 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16791 change in days weeks, months, years.
16792 With a single plus or minus, the date is relative to today. With a double
16793 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16794 +4d --> four days from today
16795 +4 --> same as above
16796 +2w --> two weeks from today
16797 ++5 --> five days from default date
16799 The function understands only English month and weekday abbreviations.
16801 While prompting, a calendar is popped up - you can also select the
16802 date with the mouse (button 1). The calendar shows a period of three
16803 months. To scroll it to other months, use the keys `>' and `<'.
16804 If you don't like the calendar, turn it off with
16805 (setq org-read-date-popup-calendar nil)
16807 With optional argument TO-TIME, the date will immediately be converted
16808 to an internal time.
16809 With an optional argument WITH-TIME, the prompt will suggest to
16810 also insert a time. Note that when WITH-TIME is not set, you can
16811 still enter a time, and this function will inform the calling routine
16812 about this change. The calling routine may then choose to change the
16813 format used to insert the time stamp into the buffer to include the time.
16814 With optional argument FROM-STRING, read from this string instead from
16815 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16816 the time/date that is used for everything that is not specified by the
16817 user."
16818 (require 'parse-time)
16819 (let* ((org-with-time with-time)
16820 (org-time-stamp-rounding-minutes
16821 (if (equal org-with-time '(16))
16822 '(0 0)
16823 org-time-stamp-rounding-minutes))
16824 (org-dcst org-display-custom-times)
16825 (ct (org-current-time))
16826 (org-def (or org-overriding-default-time default-time ct))
16827 (org-defdecode (decode-time org-def))
16828 (cur-frame (selected-frame))
16829 (mouse-autoselect-window nil) ; Don't let the mouse jump
16830 (calendar-setup
16831 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16832 (calendar-move-hook nil)
16833 (calendar-view-diary-initially-flag nil)
16834 (calendar-view-holidays-initially-flag nil)
16835 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16836 ;; Rationalize `org-def' and `org-defdecode', if required.
16837 (when (< (nth 2 org-defdecode) org-extend-today-until)
16838 (setf (nth 2 org-defdecode) -1)
16839 (setf (nth 1 org-defdecode) 59)
16840 (setq org-def (apply #'encode-time org-defdecode))
16841 (setq org-defdecode (decode-time org-def)))
16842 (let* ((timestr (format-time-string
16843 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16844 org-def))
16845 (prompt (concat (if prompt (concat prompt " ") "")
16846 (format "Date+time [%s]: " timestr))))
16847 (cond
16848 (from-string (setq ans from-string))
16849 (org-read-date-popup-calendar
16850 (save-excursion
16851 (save-window-excursion
16852 (calendar)
16853 (when (eq calendar-setup 'calendar-only)
16854 (setq cal-frame
16855 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16856 (select-frame cal-frame))
16857 (org-eval-in-calendar '(setq cursor-type nil) t)
16858 (unwind-protect
16859 (progn
16860 (calendar-forward-day (- (time-to-days org-def)
16861 (calendar-absolute-from-gregorian
16862 (calendar-current-date))))
16863 (org-eval-in-calendar nil t)
16864 (let* ((old-map (current-local-map))
16865 (map (copy-keymap calendar-mode-map))
16866 (minibuffer-local-map
16867 (copy-keymap org-read-date-minibuffer-local-map)))
16868 (org-defkey map (kbd "RET") 'org-calendar-select)
16869 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16870 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16871 (unwind-protect
16872 (progn
16873 (use-local-map map)
16874 (setq org-read-date-inactive inactive)
16875 (add-hook 'post-command-hook 'org-read-date-display)
16876 (setq org-ans0
16877 (read-string prompt
16878 default-input
16879 'org-read-date-history
16880 nil))
16881 ;; org-ans0: from prompt
16882 ;; org-ans1: from mouse click
16883 ;; org-ans2: from calendar motion
16884 (setq ans
16885 (concat org-ans0 " " (or org-ans1 org-ans2))))
16886 (remove-hook 'post-command-hook 'org-read-date-display)
16887 (use-local-map old-map)
16888 (when org-read-date-overlay
16889 (delete-overlay org-read-date-overlay)
16890 (setq org-read-date-overlay nil)))))
16891 (bury-buffer "*Calendar*")
16892 (when cal-frame
16893 (delete-frame cal-frame)
16894 (select-frame-set-input-focus cur-frame))))))
16896 (t ; Naked prompt only
16897 (unwind-protect
16898 (setq ans (read-string prompt default-input
16899 'org-read-date-history timestr))
16900 (when org-read-date-overlay
16901 (delete-overlay org-read-date-overlay)
16902 (setq org-read-date-overlay nil))))))
16904 (setq final (org-read-date-analyze ans org-def org-defdecode))
16906 (when org-read-date-analyze-forced-year
16907 (message "Year was forced into %s"
16908 (if org-read-date-force-compatible-dates
16909 "compatible range (1970-2037)"
16910 "range representable on this machine"))
16911 (ding))
16913 ;; One round trip to get rid of 34th of August and stuff like that....
16914 (setq final (decode-time (apply 'encode-time final)))
16916 (setq org-read-date-final-answer ans)
16918 (if to-time
16919 (apply 'encode-time final)
16920 (if (and (boundp 'org-time-was-given) org-time-was-given)
16921 (format "%04d-%02d-%02d %02d:%02d"
16922 (nth 5 final) (nth 4 final) (nth 3 final)
16923 (nth 2 final) (nth 1 final))
16924 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16926 (defun org-read-date-display ()
16927 "Display the current date prompt interpretation in the minibuffer."
16928 (when org-read-date-display-live
16929 (when org-read-date-overlay
16930 (delete-overlay org-read-date-overlay))
16931 (when (minibufferp (current-buffer))
16932 (save-excursion
16933 (end-of-line 1)
16934 (while (not (equal (buffer-substring
16935 (max (point-min) (- (point) 4)) (point))
16936 " "))
16937 (insert " ")))
16938 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16939 " " (or org-ans1 org-ans2)))
16940 (org-end-time-was-given nil)
16941 (f (org-read-date-analyze ans org-def org-defdecode))
16942 (fmts (if org-dcst
16943 org-time-stamp-custom-formats
16944 org-time-stamp-formats))
16945 (fmt (if (or org-with-time
16946 (and (boundp 'org-time-was-given) org-time-was-given))
16947 (cdr fmts)
16948 (car fmts)))
16949 (txt (format-time-string fmt (apply 'encode-time f)))
16950 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16951 (txt (concat "=> " txt)))
16952 (when (and org-end-time-was-given
16953 (string-match org-plain-time-of-day-regexp txt))
16954 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16955 org-end-time-was-given
16956 (substring txt (match-end 0)))))
16957 (when org-read-date-analyze-futurep
16958 (setq txt (concat txt " (=>F)")))
16959 (setq org-read-date-overlay
16960 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16961 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16963 (defun org-read-date-analyze (ans def defdecode)
16964 "Analyze the combined answer of the date prompt."
16965 ;; FIXME: cleanup and comment
16966 ;; Pass `current-time' result to `decode-time' (instead of calling
16967 ;; without arguments) so that only `current-time' has to be
16968 ;; overriden in tests.
16969 (let ((org-def def)
16970 (org-defdecode defdecode)
16971 (nowdecode (decode-time (current-time)))
16972 delta deltan deltaw deltadef year month day
16973 hour minute second wday pm h2 m2 tl wday1
16974 iso-year iso-weekday iso-week iso-date futurep kill-year)
16975 (setq org-read-date-analyze-futurep nil
16976 org-read-date-analyze-forced-year nil)
16977 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16978 (setq ans "+0"))
16980 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16981 (setq ans (replace-match "" t t ans)
16982 deltan (car delta)
16983 deltaw (nth 1 delta)
16984 deltadef (nth 2 delta)))
16986 ;; Check if there is an iso week date in there. If yes, store the
16987 ;; info and postpone interpreting it until the rest of the parsing
16988 ;; is done.
16989 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16990 (setq iso-year (when (match-end 1)
16991 (org-small-year-to-year
16992 (string-to-number (match-string 1 ans))))
16993 iso-weekday (when (match-end 3)
16994 (string-to-number (match-string 3 ans)))
16995 iso-week (string-to-number (match-string 2 ans)))
16996 (setq ans (replace-match "" t t ans)))
16998 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16999 (when (string-match
17000 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17001 (setq year (if (match-end 2)
17002 (string-to-number (match-string 2 ans))
17003 (progn (setq kill-year t)
17004 (string-to-number (format-time-string "%Y"))))
17005 month (string-to-number (match-string 3 ans))
17006 day (string-to-number (match-string 4 ans)))
17007 (setq year (org-small-year-to-year year))
17008 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17009 t nil ans)))
17011 ;; Help matching dotted european dates
17012 (when (string-match
17013 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17014 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17015 (setq kill-year t)
17016 (string-to-number (format-time-string "%Y")))
17017 day (string-to-number (match-string 1 ans))
17018 month (string-to-number (match-string 2 ans))
17019 ans (replace-match (format "%04d-%02d-%02d" year month day)
17020 t nil ans)))
17022 ;; Help matching american dates, like 5/30 or 5/30/7
17023 (when (string-match
17024 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17025 (setq year (if (match-end 4)
17026 (string-to-number (match-string 4 ans))
17027 (progn (setq kill-year t)
17028 (string-to-number (format-time-string "%Y"))))
17029 month (string-to-number (match-string 1 ans))
17030 day (string-to-number (match-string 2 ans)))
17031 (setq year (org-small-year-to-year year))
17032 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17033 t nil ans)))
17034 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17035 ;; If there is a time with am/pm, and *no* time without it, we convert
17036 ;; so that matching will be successful.
17037 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17038 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17039 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17040 (setq hour (string-to-number (match-string 1 ans))
17041 minute (if (match-end 3)
17042 (string-to-number (match-string 3 ans))
17044 pm (equal ?p
17045 (string-to-char (downcase (match-string 4 ans)))))
17046 (if (and (= hour 12) (not pm))
17047 (setq hour 0)
17048 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17049 (setq ans (replace-match (format "%02d:%02d" hour minute)
17050 t t ans))))
17052 ;; Check if a time range is given as a duration
17053 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17054 (setq hour (string-to-number (match-string 1 ans))
17055 h2 (+ hour (string-to-number (match-string 3 ans)))
17056 minute (string-to-number (match-string 2 ans))
17057 m2 (+ minute (if (match-end 5) (string-to-number
17058 (match-string 5 ans))0)))
17059 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17060 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17061 t t ans)))
17063 ;; Check if there is a time range
17064 (when (boundp 'org-end-time-was-given)
17065 (setq org-time-was-given nil)
17066 (when (and (string-match org-plain-time-of-day-regexp ans)
17067 (match-end 8))
17068 (setq org-end-time-was-given (match-string 8 ans))
17069 (setq ans (concat (substring ans 0 (match-beginning 7))
17070 (substring ans (match-end 7))))))
17072 (setq tl (parse-time-string ans)
17073 day (or (nth 3 tl) (nth 3 org-defdecode))
17074 month
17075 (cond ((nth 4 tl))
17076 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17077 ;; Day was specified. Make sure DAY+MONTH
17078 ;; combination happens in the future.
17079 ((nth 3 tl)
17080 (setq futurep t)
17081 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17082 (nth 4 nowdecode)))
17083 (t (nth 4 org-defdecode)))
17084 year
17085 (cond ((and (not kill-year) (nth 5 tl)))
17086 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17087 ;; Month was guessed in the future and is at least
17088 ;; equal to NOWDECODE's. Fix year accordingly.
17089 (futurep
17090 (if (or (> month (nth 4 nowdecode))
17091 (>= day (nth 3 nowdecode)))
17092 (nth 5 nowdecode)
17093 (1+ (nth 5 nowdecode))))
17094 ;; Month was specified. Make sure MONTH+YEAR
17095 ;; combination happens in the future.
17096 ((nth 4 tl)
17097 (setq futurep t)
17098 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17099 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17100 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17101 (t (nth 5 nowdecode))))
17102 (t (nth 5 org-defdecode)))
17103 hour (or (nth 2 tl) (nth 2 org-defdecode))
17104 minute (or (nth 1 tl) (nth 1 org-defdecode))
17105 second (or (nth 0 tl) 0)
17106 wday (nth 6 tl))
17108 (when (and (eq org-read-date-prefer-future 'time)
17109 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17110 (equal day (nth 3 nowdecode))
17111 (equal month (nth 4 nowdecode))
17112 (equal year (nth 5 nowdecode))
17113 (nth 2 tl)
17114 (or (< (nth 2 tl) (nth 2 nowdecode))
17115 (and (= (nth 2 tl) (nth 2 nowdecode))
17116 (nth 1 tl)
17117 (< (nth 1 tl) (nth 1 nowdecode)))))
17118 (setq day (1+ day)
17119 futurep t))
17121 ;; Special date definitions below
17122 (cond
17123 (iso-week
17124 ;; There was an iso week
17125 (require 'cal-iso)
17126 (setq futurep nil)
17127 (setq year (or iso-year year)
17128 day (or iso-weekday wday 1)
17129 wday nil ; to make sure that the trigger below does not match
17130 iso-date (calendar-gregorian-from-absolute
17131 (calendar-iso-to-absolute
17132 (list iso-week day year))))
17133 ; FIXME: Should we also push ISO weeks into the future?
17134 ; (when (and org-read-date-prefer-future
17135 ; (not iso-year)
17136 ; (< (calendar-absolute-from-gregorian iso-date)
17137 ; (time-to-days (current-time))))
17138 ; (setq year (1+ year)
17139 ; iso-date (calendar-gregorian-from-absolute
17140 ; (calendar-iso-to-absolute
17141 ; (list iso-week day year)))))
17142 (setq month (car iso-date)
17143 year (nth 2 iso-date)
17144 day (nth 1 iso-date)))
17145 (deltan
17146 (setq futurep nil)
17147 (unless deltadef
17148 ;; Pass `current-time' result to `decode-time' (instead of
17149 ;; calling without arguments) so that only `current-time' has
17150 ;; to be overriden in tests.
17151 (let ((now (decode-time (current-time))))
17152 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17153 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17154 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17155 ((equal deltaw "m") (setq month (+ month deltan)))
17156 ((equal deltaw "y") (setq year (+ year deltan)))))
17157 ((and wday (not (nth 3 tl)))
17158 ;; Weekday was given, but no day, so pick that day in the week
17159 ;; on or after the derived date.
17160 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17161 (unless (equal wday wday1)
17162 (setq day (+ day (% (- wday wday1 -7) 7))))))
17163 (when (and (boundp 'org-time-was-given)
17164 (nth 2 tl))
17165 (setq org-time-was-given t))
17166 (when (< year 100) (setq year (+ 2000 year)))
17167 ;; Check of the date is representable
17168 (if org-read-date-force-compatible-dates
17169 (progn
17170 (when (< year 1970)
17171 (setq year 1970 org-read-date-analyze-forced-year t))
17172 (when (> year 2037)
17173 (setq year 2037 org-read-date-analyze-forced-year t)))
17174 (condition-case nil
17175 (ignore (encode-time second minute hour day month year))
17176 (error
17177 (setq year (nth 5 org-defdecode))
17178 (setq org-read-date-analyze-forced-year t))))
17179 (setq org-read-date-analyze-futurep futurep)
17180 (list second minute hour day month year)))
17182 (defvar parse-time-weekdays)
17183 (defun org-read-date-get-relative (s today default)
17184 "Check string S for special relative date string.
17185 TODAY and DEFAULT are internal times, for today and for a default.
17186 Return shift list (N what def-flag)
17187 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17188 N is the number of WHATs to shift.
17189 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17190 the DEFAULT date rather than TODAY."
17191 (require 'parse-time)
17192 (when (and
17193 (string-match
17194 (concat
17195 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17196 "\\([0-9]+\\)?"
17197 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17198 "\\([ \t]\\|$\\)") s)
17199 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17200 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17201 (string-to-char (substring (match-string 1 s) -1))
17202 ?+))
17203 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17204 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17205 (what (if (match-end 3) (match-string 3 s) "d"))
17206 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17207 (date (if rel default today))
17208 (wday (nth 6 (decode-time date)))
17209 delta)
17210 (if wday1
17211 (progn
17212 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17213 (when (= delta 0) (setq delta 7))
17214 (when (= dir ?-)
17215 (setq delta (- delta 7))
17216 (when (= delta 0) (setq delta -7)))
17217 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17218 (list delta "d" rel))
17219 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17221 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17222 "Turn a user-specified date into the internal representation.
17223 The internal representation needed by the calendar is (month day year).
17224 This is a wrapper to handle the brain-dead convention in calendar that
17225 user function argument order change dependent on argument order."
17226 (pcase calendar-date-style
17227 (`american (list arg1 arg2 arg3))
17228 (`european (list arg2 arg1 arg3))
17229 (`iso (list arg2 arg3 arg1))))
17231 (defun org-eval-in-calendar (form &optional keepdate)
17232 "Eval FORM in the calendar window and return to current window.
17233 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17234 (let ((sf (selected-frame))
17235 (sw (selected-window)))
17236 (select-window (get-buffer-window "*Calendar*" t))
17237 (eval form)
17238 (when (and (not keepdate) (calendar-cursor-to-date))
17239 (let* ((date (calendar-cursor-to-date))
17240 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17241 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17242 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17243 (select-window sw)
17244 (select-frame-set-input-focus sf)))
17246 (defun org-calendar-select ()
17247 "Return to `org-read-date' with the date currently selected.
17248 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17249 (interactive)
17250 (when (calendar-cursor-to-date)
17251 (let* ((date (calendar-cursor-to-date))
17252 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17253 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17254 (when (active-minibuffer-window) (exit-minibuffer))))
17256 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17257 "Insert a date stamp for the date given by the internal TIME.
17258 See `format-time-string' for the format of TIME.
17259 WITH-HM means use the stamp format that includes the time of the day.
17260 INACTIVE means use square brackets instead of angular ones, so that the
17261 stamp will not contribute to the agenda.
17262 PRE and POST are optional strings to be inserted before and after the
17263 stamp.
17264 The command returns the inserted time stamp."
17265 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17266 stamp)
17267 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17268 (insert-before-markers (or pre ""))
17269 (when (listp extra)
17270 (setq extra (car extra))
17271 (if (and (stringp extra)
17272 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17273 (setq extra (format "-%02d:%02d"
17274 (string-to-number (match-string 1 extra))
17275 (string-to-number (match-string 2 extra))))
17276 (setq extra nil)))
17277 (when extra
17278 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17279 (insert-before-markers (setq stamp (format-time-string fmt time)))
17280 (insert-before-markers (or post ""))
17281 (setq org-last-inserted-timestamp stamp)))
17283 (defun org-toggle-time-stamp-overlays ()
17284 "Toggle the use of custom time stamp formats."
17285 (interactive)
17286 (setq org-display-custom-times (not org-display-custom-times))
17287 (unless org-display-custom-times
17288 (let ((p (point-min)) (bmp (buffer-modified-p)))
17289 (while (setq p (next-single-property-change p 'display))
17290 (when (and (get-text-property p 'display)
17291 (eq (get-text-property p 'face) 'org-date))
17292 (remove-text-properties
17293 p (setq p (next-single-property-change p 'display))
17294 '(display t))))
17295 (set-buffer-modified-p bmp)))
17296 (org-restart-font-lock)
17297 (setq org-table-may-need-update t)
17298 (if org-display-custom-times
17299 (message "Time stamps are overlaid with custom format")
17300 (message "Time stamp overlays removed")))
17302 (defun org-display-custom-time (beg end)
17303 "Overlay modified time stamp format over timestamp between BEG and END."
17304 (let* ((ts (buffer-substring beg end))
17305 t1 w1 with-hm tf time str w2 (off 0))
17306 (save-match-data
17307 (setq t1 (org-parse-time-string ts t))
17308 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17309 (setq off (- (match-end 0) (match-beginning 0)))))
17310 (setq end (- end off))
17311 (setq w1 (- end beg)
17312 with-hm (and (nth 1 t1) (nth 2 t1))
17313 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17314 time (org-fix-decoded-time t1)
17315 str (org-add-props
17316 (format-time-string
17317 (substring tf 1 -1) (apply 'encode-time time))
17318 nil 'mouse-face 'highlight)
17319 w2 (length str))
17320 (unless (= w2 w1)
17321 (add-text-properties (1+ beg) (+ 2 beg)
17322 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17323 (put-text-property beg end 'display str)))
17325 (defun org-fix-decoded-time (time)
17326 "Set 0 instead of nil for the first 6 elements of time.
17327 Don't touch the rest."
17328 (let ((n 0))
17329 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17331 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17332 "Difference between TIMESTAMP-STRING and now in days.
17333 If SECONDS is non-nil, return the difference in seconds."
17334 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17335 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17336 (funcall fdiff (current-time)))))
17338 (defun org-deadline-close-p (timestamp-string &optional ndays)
17339 "Is the time in TIMESTAMP-STRING close to the current date?"
17340 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17341 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17342 (not (org-entry-is-done-p))))
17344 (defun org-get-wdays (ts &optional delay zero-delay)
17345 "Get the deadline lead time appropriate for timestring TS.
17346 When DELAY is non-nil, get the delay time for scheduled items
17347 instead of the deadline lead time. When ZERO-DELAY is non-nil
17348 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17349 don't try to find the delay cookie in the scheduled timestamp."
17350 (let ((tv (if delay org-scheduled-delay-days
17351 org-deadline-warning-days)))
17352 (cond
17353 ((or (and delay (< tv 0))
17354 (and delay zero-delay (<= tv 0))
17355 (and (not delay) (<= tv 0)))
17356 ;; Enforce this value no matter what
17357 (- tv))
17358 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17359 ;; lead time is specified.
17360 (floor (* (string-to-number (match-string 1 ts))
17361 (cdr (assoc (match-string 2 ts)
17362 '(("d" . 1) ("w" . 7)
17363 ("m" . 30.4) ("y" . 365.25)
17364 ("h" . 0.041667)))))))
17365 ;; go for the default.
17366 (t tv))))
17368 (defun org-calendar-select-mouse (ev)
17369 "Return to `org-read-date' with the date currently selected.
17370 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17371 (interactive "e")
17372 (mouse-set-point ev)
17373 (when (calendar-cursor-to-date)
17374 (let* ((date (calendar-cursor-to-date))
17375 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17376 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17377 (when (active-minibuffer-window) (exit-minibuffer))))
17379 (defun org-check-deadlines (ndays)
17380 "Check if there are any deadlines due or past due.
17381 A deadline is considered due if it happens within `org-deadline-warning-days'
17382 days from today's date. If the deadline appears in an entry marked DONE,
17383 it is not shown. A numeric prefix argument NDAYS can be used to test that
17384 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17385 are shown."
17386 (interactive "P")
17387 (let* ((org-warn-days
17388 (cond
17389 ((equal ndays '(4)) 100000)
17390 (ndays (prefix-numeric-value ndays))
17391 (t (abs org-deadline-warning-days))))
17392 (case-fold-search nil)
17393 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17394 (callback
17395 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17396 (message "%d deadlines past-due or due within %d days"
17397 (org-occur regexp nil callback)
17398 org-warn-days)))
17400 (defsubst org-re-timestamp (type)
17401 "Return a regexp for timestamp TYPE.
17402 Allowed values for TYPE are:
17404 all: all timestamps
17405 active: only active timestamps (<...>)
17406 inactive: only inactive timestamps ([...])
17407 scheduled: only scheduled timestamps
17408 deadline: only deadline timestamps
17409 closed: only closed time-stamps
17411 When TYPE is nil, fall back on returning a regexp that matches
17412 both scheduled and deadline timestamps."
17413 (cl-case type
17414 (all org-ts-regexp-both)
17415 (active org-ts-regexp)
17416 (inactive org-ts-regexp-inactive)
17417 (scheduled org-scheduled-time-regexp)
17418 (deadline org-deadline-time-regexp)
17419 (closed org-closed-time-regexp)
17420 (otherwise
17421 (concat "\\<"
17422 (regexp-opt (list org-deadline-string org-scheduled-string))
17423 " *<\\([^>]+\\)>"))))
17425 (defun org-check-before-date (d)
17426 "Check if there are deadlines or scheduled entries before date D."
17427 (interactive (list (org-read-date)))
17428 (let* ((case-fold-search nil)
17429 (regexp (org-re-timestamp org-ts-type))
17430 (ts-type org-ts-type)
17431 (callback
17432 (lambda ()
17433 (let ((match (match-string 1)))
17434 (and (if (memq ts-type '(active inactive all))
17435 (eq (org-element-type (save-excursion
17436 (backward-char)
17437 (org-element-context)))
17438 'timestamp)
17439 (org-at-planning-p))
17440 (time-less-p
17441 (org-time-string-to-time match)
17442 (org-time-string-to-time d)))))))
17443 (message "%d entries before %s"
17444 (org-occur regexp nil callback)
17445 d)))
17447 (defun org-check-after-date (d)
17448 "Check if there are deadlines or scheduled entries after date D."
17449 (interactive (list (org-read-date)))
17450 (let* ((case-fold-search nil)
17451 (regexp (org-re-timestamp org-ts-type))
17452 (ts-type org-ts-type)
17453 (callback
17454 (lambda ()
17455 (let ((match (match-string 1)))
17456 (and (if (memq ts-type '(active inactive all))
17457 (eq (org-element-type (save-excursion
17458 (backward-char)
17459 (org-element-context)))
17460 'timestamp)
17461 (org-at-planning-p))
17462 (not (time-less-p
17463 (org-time-string-to-time match)
17464 (org-time-string-to-time d))))))))
17465 (message "%d entries after %s"
17466 (org-occur regexp nil callback)
17467 d)))
17469 (defun org-check-dates-range (start-date end-date)
17470 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17471 (interactive (list (org-read-date nil nil nil "Range starts")
17472 (org-read-date nil nil nil "Range end")))
17473 (let ((case-fold-search nil)
17474 (regexp (org-re-timestamp org-ts-type))
17475 (callback
17476 (let ((type org-ts-type))
17477 (lambda ()
17478 (let ((match (match-string 1)))
17479 (and
17480 (if (memq type '(active inactive all))
17481 (eq (org-element-type (save-excursion
17482 (backward-char)
17483 (org-element-context)))
17484 'timestamp)
17485 (org-at-planning-p))
17486 (not (time-less-p
17487 (org-time-string-to-time match)
17488 (org-time-string-to-time start-date)))
17489 (time-less-p
17490 (org-time-string-to-time match)
17491 (org-time-string-to-time end-date))))))))
17492 (message "%d entries between %s and %s"
17493 (org-occur regexp nil callback) start-date end-date)))
17495 (defun org-evaluate-time-range (&optional to-buffer)
17496 "Evaluate a time range by computing the difference between start and end.
17497 Normally the result is just printed in the echo area, but with prefix arg
17498 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17499 If the time range is actually in a table, the result is inserted into the
17500 next column.
17501 For time difference computation, a year is assumed to be exactly 365
17502 days in order to avoid rounding problems."
17503 (interactive "P")
17505 (org-clock-update-time-maybe)
17506 (save-excursion
17507 (unless (org-at-date-range-p t)
17508 (goto-char (point-at-bol))
17509 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17510 (unless (org-at-date-range-p t)
17511 (user-error "Not at a time-stamp range, and none found in current line")))
17512 (let* ((ts1 (match-string 1))
17513 (ts2 (match-string 2))
17514 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17515 (match-end (match-end 0))
17516 (time1 (org-time-string-to-time ts1))
17517 (time2 (org-time-string-to-time ts2))
17518 (t1 (float-time time1))
17519 (t2 (float-time time2))
17520 (diff (abs (- t2 t1)))
17521 (negative (< (- t2 t1) 0))
17522 ;; (ys (floor (* 365 24 60 60)))
17523 (ds (* 24 60 60))
17524 (hs (* 60 60))
17525 (fy "%dy %dd %02d:%02d")
17526 (fy1 "%dy %dd")
17527 (fd "%dd %02d:%02d")
17528 (fd1 "%dd")
17529 (fh "%02d:%02d")
17530 y d h m align)
17531 (if havetime
17532 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17534 d (floor (/ diff ds)) diff (mod diff ds)
17535 h (floor (/ diff hs)) diff (mod diff hs)
17536 m (floor (/ diff 60)))
17537 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17539 d (floor (+ (/ diff ds) 0.5))
17540 h 0 m 0))
17541 (if (not to-buffer)
17542 (message "%s" (org-make-tdiff-string y d h m))
17543 (if (org-at-table-p)
17544 (progn
17545 (goto-char match-end)
17546 (setq align t)
17547 (and (looking-at " *|") (goto-char (match-end 0))))
17548 (goto-char match-end))
17549 (when (looking-at
17550 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17551 (replace-match ""))
17552 (when negative (insert " -"))
17553 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17554 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17555 (insert " " (format fh h m))))
17556 (when align (org-table-align))
17557 (message "Time difference inserted")))))
17559 (defun org-make-tdiff-string (y d h m)
17560 (let ((fmt "")
17561 (l nil))
17562 (when (> y 0)
17563 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17564 (push y l))
17565 (when (> d 0)
17566 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17567 (push d l))
17568 (when (> h 0)
17569 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17570 (push h l))
17571 (when (> m 0)
17572 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17573 (push m l))
17574 (apply 'format fmt (nreverse l))))
17576 (defun org-time-string-to-time (s &optional buffer pos)
17577 "Convert a timestamp string into internal time."
17578 (condition-case errdata
17579 (apply 'encode-time (org-parse-time-string s))
17580 (error (error "Bad timestamp `%s'%s\nError was: %s"
17581 s (if (not (and buffer pos))
17583 (format-message " at %d in buffer `%s'" pos buffer))
17584 (cdr errdata)))))
17586 (defun org-time-string-to-seconds (s)
17587 "Convert a timestamp string to a number of seconds."
17588 (float-time (org-time-string-to-time s)))
17590 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17592 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17593 "Convert time stamp S to an absolute day number.
17595 If DAYNR in non-nil, and there is a specifier for a cyclic time
17596 stamp, get the closest date to DAYNR. If PREFER is
17597 `past' (respectively `future') return a date past (respectively
17598 after) or equal to DAYNR.
17600 POS is the location of time stamp S, as a buffer position in
17601 BUFFER.
17603 Diary sexp timestamps are matched against DAYNR, when non-nil.
17604 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17605 signalled."
17606 (cond
17607 ((string-match "\\`%%\\((.*)\\)" s)
17608 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17609 ;; only able to match individual dates. If it fails, raise an
17610 ;; error.
17611 (if (and daynr
17612 (org-diary-sexp-entry
17613 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17614 daynr
17615 (signal 'org-diary-sexp-no-match (list s))))
17616 (daynr (org-closest-date s daynr prefer))
17617 (t (time-to-days
17618 (condition-case errdata
17619 (apply #'encode-time (org-parse-time-string s))
17620 (error (error "Bad timestamp `%s'%s\nError was: %s"
17622 (if (not (and buffer pos)) ""
17623 (format-message " at %d in buffer `%s'" pos buffer))
17624 (cdr errdata))))))))
17626 (defun org-days-to-iso-week (days)
17627 "Return the iso week number."
17628 (require 'cal-iso)
17629 (car (calendar-iso-from-absolute days)))
17631 (defun org-small-year-to-year (year)
17632 "Convert 2-digit years into 4-digit years.
17633 YEAR is expanded into one of the 30 next years, if possible, or
17634 into a past one. Any year larger than 99 is returned unchanged."
17635 (if (>= year 100) year
17636 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17637 (century (/ current 100))
17638 (offset (- year (% current 100))))
17639 (cond ((> offset 30) (+ (* (1- century) 100) year))
17640 ((> offset -70) (+ (* century 100) year))
17641 (t (+ (* (1+ century) 100) year))))))
17643 (defun org-time-from-absolute (d)
17644 "Return the time corresponding to date D.
17645 D may be an absolute day number, or a calendar-type list (month day year)."
17646 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17647 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17649 (defvar org-agenda-current-date)
17650 (defun org-calendar-holiday ()
17651 "List of holidays, for Diary display in Org mode."
17652 (require 'holidays)
17653 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17654 (and hl (mapconcat #'identity hl "; "))))
17656 (defun org-diary-sexp-entry (sexp entry d)
17657 "Process a SEXP diary ENTRY for date D."
17658 (require 'diary-lib)
17659 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17660 ;; dynamically.
17661 (let* ((sexp `(let ((entry ,entry)
17662 (date ',d))
17663 ,(car (read-from-string sexp))))
17664 (result (if calendar-debug-sexp (eval sexp)
17665 (condition-case nil
17666 (eval sexp)
17667 (error
17668 (beep)
17669 (message "Bad sexp at line %d in %s: %s"
17670 (org-current-line)
17671 (buffer-file-name) sexp)
17672 (sleep-for 2))))))
17673 (cond ((stringp result) (split-string result "; "))
17674 ((and (consp result)
17675 (not (consp (cdr result)))
17676 (stringp (cdr result))) (cdr result))
17677 ((and (consp result)
17678 (stringp (car result))) result)
17679 (result entry))))
17681 (defun org-diary-to-ical-string (frombuf)
17682 "Get iCalendar entries from diary entries in buffer FROMBUF.
17683 This uses the icalendar.el library."
17684 (let* ((tmpdir temporary-file-directory)
17685 (tmpfile (make-temp-name
17686 (expand-file-name "orgics" tmpdir)))
17687 buf rtn b e)
17688 (with-current-buffer frombuf
17689 (icalendar-export-region (point-min) (point-max) tmpfile)
17690 (setq buf (find-buffer-visiting tmpfile))
17691 (set-buffer buf)
17692 (goto-char (point-min))
17693 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17694 (setq b (match-beginning 0)))
17695 (goto-char (point-max))
17696 (when (re-search-backward "^END:VEVENT" nil t)
17697 (setq e (match-end 0)))
17698 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17699 (kill-buffer buf)
17700 (delete-file tmpfile)
17701 rtn))
17703 (defun org-closest-date (start current prefer)
17704 "Return closest date to CURRENT starting from START.
17706 CURRENT and START are both time stamps.
17708 When PREFER is `past', return a date that is either CURRENT or
17709 past. When PREFER is `future', return a date that is either
17710 CURRENT or future.
17712 Only time stamps with a repeater are modified. Any other time
17713 stamp stay unchanged. In any case, return value is an absolute
17714 day number."
17715 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17716 ;; No repeater. Do not shift time stamp.
17717 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17718 (let ((value (string-to-number (match-string 1 start)))
17719 (type (match-string 2 start)))
17720 (if (= 0 value)
17721 ;; Repeater with a 0-value is considered as void.
17722 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17723 (let* ((base (org-date-to-gregorian start))
17724 (target (org-date-to-gregorian current))
17725 (sday (calendar-absolute-from-gregorian base))
17726 (cday (calendar-absolute-from-gregorian target))
17727 n1 n2)
17728 ;; If START is already past CURRENT, just return START.
17729 (if (<= cday sday) sday
17730 ;; Compute closest date before (N1) and closest date past
17731 ;; (N2) CURRENT.
17732 (pcase type
17733 ("h"
17734 (let ((missing-hours
17735 (mod (+ (- (* 24 (- cday sday))
17736 (nth 2 (org-parse-time-string start)))
17737 org-extend-today-until)
17738 value)))
17739 (setf n1 (if (= missing-hours 0) cday
17740 (- cday (1+ (/ missing-hours 24)))))
17741 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17742 ((or "d" "w")
17743 (let ((value (if (equal type "w") (* 7 value) value)))
17744 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17745 (setf n2 (+ n1 value))))
17746 ("m"
17747 (let* ((add-months
17748 (lambda (d n)
17749 ;; Add N months to gregorian date D, i.e.,
17750 ;; a list (MONTH DAY YEAR). Return a valid
17751 ;; gregorian date.
17752 (let ((m (+ (nth 0 d) n)))
17753 (list (mod m 12)
17754 (nth 1 d)
17755 (+ (/ m 12) (nth 2 d))))))
17756 (months ; Complete months to TARGET.
17757 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17758 (- (nth 0 target) (nth 0 base))
17759 ;; If START's day is greater than
17760 ;; TARGET's, remove incomplete month.
17761 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17762 value)
17763 value))
17764 (before (funcall add-months base months)))
17765 (setf n1 (calendar-absolute-from-gregorian before))
17766 (setf n2
17767 (calendar-absolute-from-gregorian
17768 (funcall add-months before value)))))
17770 (let* ((d (nth 1 base))
17771 (m (nth 0 base))
17772 (y (nth 2 base))
17773 (years ; Complete years to TARGET.
17774 (* (/ (- (nth 2 target)
17776 ;; If START's month and day are
17777 ;; greater than TARGET's, remove
17778 ;; incomplete year.
17779 (if (or (> (nth 0 target) m)
17780 (and (= (nth 0 target) m)
17781 (> (nth 1 target) d)))
17784 value)
17785 value))
17786 (before (list m d (+ y years))))
17787 (setf n1 (calendar-absolute-from-gregorian before))
17788 (setf n2 (calendar-absolute-from-gregorian
17789 (list m d (+ (nth 2 before) value)))))))
17790 ;; Handle PREFER parameter, if any.
17791 (cond
17792 ((eq prefer 'past) (if (= cday n2) n2 n1))
17793 ((eq prefer 'future) (if (= cday n1) n1 n2))
17794 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17796 (defun org-date-to-gregorian (d)
17797 "Turn any specification of date D into a Gregorian date for the calendar."
17798 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17799 ((and (listp d) (= (length d) 3)) d)
17800 ((stringp d)
17801 (let ((d (org-parse-time-string d)))
17802 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17803 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17805 (defun org-parse-time-string (s &optional nodefault zone)
17806 "Parse the standard Org time string.
17808 This should be a lot faster than the normal `parse-time-string'.
17810 If time is not given, defaults to 0:00. However, with optional
17811 NODEFAULT, hour and minute fields will be nil if not given.
17813 The optional ZONE is omitted or nil for Emacs local time, t for
17814 Universal Time, ‘wall’ for system wall clock time, or a string as
17815 in the TZ environment variable."
17816 (cond ((string-match org-ts-regexp0 s)
17817 (list 0
17818 (when (or (match-beginning 8) (not nodefault))
17819 (string-to-number (or (match-string 8 s) "0")))
17820 (when (or (match-beginning 7) (not nodefault))
17821 (string-to-number (or (match-string 7 s) "0")))
17822 (string-to-number (match-string 4 s))
17823 (string-to-number (match-string 3 s))
17824 (string-to-number (match-string 2 s))
17825 nil nil zone))
17826 ((string-match "^<[^>]+>$" s)
17827 ;; FIXME: `decode-time' needs to be called with ZONE as its
17828 ;; second argument. However, this requires at least Emacs
17829 ;; 25.1. We can do it when we switch to this version as our
17830 ;; minimal requirement.
17831 (decode-time (seconds-to-time (org-matcher-time s))))
17832 (t (error "Not a standard Org time string: %s" s))))
17834 (defun org-timestamp-up (&optional arg)
17835 "Increase the date item at the cursor by one.
17836 If the cursor is on the year, change the year. If it is on the month,
17837 the day or the time, change that.
17838 With prefix ARG, change by that many units."
17839 (interactive "p")
17840 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17842 (defun org-timestamp-down (&optional arg)
17843 "Decrease the date item at the cursor by one.
17844 If the cursor is on the year, change the year. If it is on the month,
17845 the day or the time, change that.
17846 With prefix ARG, change by that many units."
17847 (interactive "p")
17848 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17850 (defun org-timestamp-up-day (&optional arg)
17851 "Increase the date in the time stamp by one day.
17852 With prefix ARG, change that many days."
17853 (interactive "p")
17854 (if (and (not (org-at-timestamp-p 'lax))
17855 (org-at-heading-p))
17856 (org-todo 'up)
17857 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17859 (defun org-timestamp-down-day (&optional arg)
17860 "Decrease the date in the time stamp by one day.
17861 With prefix ARG, change that many days."
17862 (interactive "p")
17863 (if (and (not (org-at-timestamp-p 'lax))
17864 (org-at-heading-p))
17865 (org-todo 'down)
17866 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17868 (defun org-at-timestamp-p (&optional extended)
17869 "Non-nil if point is inside a timestamp.
17871 By default, the function only consider syntactically valid active
17872 timestamps. However, the caller may have a broader definition
17873 for timestamps. As a consequence, optional argument EXTENDED can
17874 be set to the following values
17876 `inactive'
17878 Include also syntactically valid inactive timestamps.
17880 `agenda'
17882 Include timestamps allowed in Agenda, i.e., those in
17883 properties drawers, planning lines and clock lines.
17885 `lax'
17887 Ignore context. The function matches any part of the
17888 document looking like a timestamp. This includes comments,
17889 example blocks...
17891 For backward-compatibility with Org 9.0, every other non-nil
17892 value is equivalent to `inactive'.
17894 When at a timestamp, return the position of the point as a symbol
17895 among `bracket', `after', `year', `month', `hour', `minute',
17896 `day' or a number of character from the last know part of the
17897 time stamp.
17899 When matching, the match groups are the following:
17900 group 1: year
17901 group 2: month
17902 group 3: day number
17903 group 4: day name
17904 group 5: hours, if any
17905 group 6: minutes, if any"
17906 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17907 (pos (point))
17908 (match?
17909 (let ((boundaries (org-in-regexp regexp)))
17910 (save-match-data
17911 (cond ((null boundaries) nil)
17912 ((eq extended 'lax) t)
17914 (or (and (eq extended 'agenda)
17915 (or (org-at-planning-p)
17916 (org-at-property-p)
17917 (and (bound-and-true-p
17918 org-agenda-include-inactive-timestamps)
17919 (org-at-clock-log-p))))
17920 (eq 'timestamp
17921 (save-excursion
17922 (when (= pos (cdr boundaries)) (forward-char -1))
17923 (org-element-type (org-element-context)))))))))))
17924 (cond
17925 ((not match?) nil)
17926 ((= pos (match-beginning 0)) 'bracket)
17927 ;; Distinguish location right before the closing bracket from
17928 ;; right after it.
17929 ((= pos (1- (match-end 0))) 'bracket)
17930 ((= pos (match-end 0)) 'after)
17931 ((org-pos-in-match-range pos 2) 'year)
17932 ((org-pos-in-match-range pos 3) 'month)
17933 ((org-pos-in-match-range pos 7) 'hour)
17934 ((org-pos-in-match-range pos 8) 'minute)
17935 ((or (org-pos-in-match-range pos 4)
17936 (org-pos-in-match-range pos 5)) 'day)
17937 ((and (> pos (or (match-end 8) (match-end 5)))
17938 (< pos (match-end 0)))
17939 (- pos (or (match-end 8) (match-end 5))))
17940 (t 'day))))
17942 (defun org-toggle-timestamp-type ()
17943 "Toggle the type (<active> or [inactive]) of a time stamp."
17944 (interactive)
17945 (when (org-at-timestamp-p 'lax)
17946 (let ((beg (match-beginning 0)) (end (match-end 0))
17947 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17948 (save-excursion
17949 (goto-char beg)
17950 (while (re-search-forward "[][<>]" end t)
17951 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17952 t t)))
17953 (message "Timestamp is now %sactive"
17954 (if (equal (char-after beg) ?<) "" "in")))))
17956 (defun org-at-clock-log-p ()
17957 "Non-nil if point is on a clock log line."
17958 (and (org-match-line org-clock-line-re)
17959 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17961 (defvar org-clock-history) ; defined in org-clock.el
17962 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17963 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17964 "Change the date in the time stamp at point.
17965 The date will be changed by N times WHAT. WHAT can be `day', `month',
17966 `year', `minute', `second'. If WHAT is not given, the cursor position
17967 in the timestamp determines what will be changed.
17968 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17969 (let ((origin (point))
17970 (timestamp? (org-at-timestamp-p 'lax))
17971 origin-cat
17972 with-hm inactive
17973 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17974 extra rem
17975 ts time time0 fixnext clrgx)
17976 (unless timestamp? (user-error "Not at a timestamp"))
17977 (if (and (not what) (eq timestamp? 'bracket))
17978 (org-toggle-timestamp-type)
17979 ;; Point isn't on brackets. Remember the part of the time-stamp
17980 ;; the point was in. Indeed, size of time-stamps may change,
17981 ;; but point must be kept in the same category nonetheless.
17982 (setq origin-cat timestamp?)
17983 (when (and (not what) (not (eq timestamp? 'day))
17984 org-display-custom-times
17985 (get-text-property (point) 'display)
17986 (not (get-text-property (1- (point)) 'display)))
17987 (setq timestamp? 'day))
17988 (setq timestamp? (or what timestamp?)
17989 inactive (= (char-after (match-beginning 0)) ?\[)
17990 ts (match-string 0))
17991 (replace-match "")
17992 (when (string-match
17993 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17995 (setq extra (match-string 1 ts))
17996 (when suppress-tmp-delay
17997 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17998 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17999 (setq with-hm t))
18000 (setq time0 (org-parse-time-string ts))
18001 (when (and updown
18002 (eq timestamp? 'minute)
18003 (not current-prefix-arg))
18004 ;; This looks like s-up and s-down. Change by one rounding step.
18005 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18006 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18007 (setcar (cdr time0) (+ (nth 1 time0)
18008 (if (> n 0) (- rem) (- dm rem))))))
18009 (setq time
18010 (apply #'encode-time
18011 (or (car time0) 0)
18012 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
18013 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
18014 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18015 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18016 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18017 (nthcdr 6 time0)))
18018 (when (and (memq timestamp? '(hour minute))
18019 extra
18020 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18021 (setq extra (org-modify-ts-extra
18022 extra
18023 (if (eq timestamp? 'hour) 2 5)
18024 n dm)))
18025 (when (integerp timestamp?)
18026 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18027 (when (eq what 'calendar)
18028 (let ((cal-date (org-get-date-from-calendar)))
18029 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18030 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18031 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18032 (setcar time0 (or (car time0) 0))
18033 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18034 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18035 (setq time (apply 'encode-time time0))))
18036 ;; Insert the new time-stamp, and ensure point stays in the same
18037 ;; category as before (i.e. not after the last position in that
18038 ;; category).
18039 (let ((pos (point)))
18040 ;; Stay before inserted string. `save-excursion' is of no use.
18041 (setq org-last-changed-timestamp
18042 (org-insert-time-stamp time with-hm inactive nil nil extra))
18043 (goto-char pos))
18044 (save-match-data
18045 (looking-at org-ts-regexp3)
18046 (goto-char
18047 (pcase origin-cat
18048 ;; `day' category ends before `hour' if any, or at the end
18049 ;; of the day name.
18050 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18051 (`hour (min (match-end 7) origin))
18052 (`minute (min (1- (match-end 8)) origin))
18053 ((pred integerp) (min (1- (match-end 0)) origin))
18054 ;; Point was right after the time-stamp. However, the
18055 ;; time-stamp length might have changed, so refer to
18056 ;; (match-end 0) instead.
18057 (`after (match-end 0))
18058 ;; `year' and `month' have both fixed size: point couldn't
18059 ;; have moved into another part.
18060 (_ origin))))
18061 ;; Update clock if on a CLOCK line.
18062 (org-clock-update-time-maybe)
18063 ;; Maybe adjust the closest clock in `org-clock-history'
18064 (when org-clock-adjust-closest
18065 (if (not (and (org-at-clock-log-p)
18066 (< 1 (length (delq nil (mapcar 'marker-position
18067 org-clock-history))))))
18068 (message "No clock to adjust")
18069 (cond ((save-excursion ; fix previous clock?
18070 (re-search-backward org-ts-regexp0 nil t)
18071 (looking-back (concat org-clock-string " \\[")
18072 (line-beginning-position)))
18073 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18074 ((save-excursion ; fix next clock?
18075 (re-search-backward org-ts-regexp0 nil t)
18076 (looking-at (concat org-ts-regexp0 "\\] =>")))
18077 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18078 (save-window-excursion
18079 ;; Find closest clock to point, adjust the previous/next one in history
18080 (let* ((p (save-excursion (org-back-to-heading t)))
18081 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18082 (clfixnth
18083 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18084 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18085 (if (not clfixpos)
18086 (message "No clock to adjust")
18087 (save-excursion
18088 (org-goto-marker-or-bmk clfixpos)
18089 (org-show-subtree)
18090 (when (re-search-forward clrgx nil t)
18091 (goto-char (match-beginning 1))
18092 (let (org-clock-adjust-closest)
18093 (org-timestamp-change n timestamp? updown))
18094 (message "Clock adjusted in %s for heading: %s"
18095 (file-name-nondirectory (buffer-file-name))
18096 (org-get-heading t t)))))))))
18097 ;; Try to recenter the calendar window, if any.
18098 (when (and org-calendar-follow-timestamp-change
18099 (get-buffer-window "*Calendar*" t)
18100 (memq timestamp? '(day month year)))
18101 (org-recenter-calendar (time-to-days time))))))
18103 (defun org-modify-ts-extra (s pos n dm)
18104 "Change the different parts of the lead-time and repeat fields in timestamp."
18105 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18106 ng h m new rem)
18107 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18108 (cond
18109 ((or (org-pos-in-match-range pos 2)
18110 (org-pos-in-match-range pos 3))
18111 (setq m (string-to-number (match-string 3 s))
18112 h (string-to-number (match-string 2 s)))
18113 (if (org-pos-in-match-range pos 2)
18114 (setq h (+ h n))
18115 (setq n (* dm (with-no-warnings (signum n))))
18116 (unless (= 0 (setq rem (% m dm)))
18117 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18118 (setq m (+ m n)))
18119 (when (< m 0) (setq m (+ m 60) h (1- h)))
18120 (when (> m 59) (setq m (- m 60) h (1+ h)))
18121 (setq h (mod h 24))
18122 (setq ng 1 new (format "-%02d:%02d" h m)))
18123 ((org-pos-in-match-range pos 6)
18124 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18125 ((org-pos-in-match-range pos 5)
18126 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18128 ((org-pos-in-match-range pos 9)
18129 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18130 ((org-pos-in-match-range pos 8)
18131 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18133 (when ng
18134 (setq s (concat
18135 (substring s 0 (match-beginning ng))
18137 (substring s (match-end ng))))))
18140 (defun org-recenter-calendar (d)
18141 "If the calendar is visible, recenter it to date D."
18142 (let ((cwin (get-buffer-window "*Calendar*" t)))
18143 (when cwin
18144 (let ((calendar-move-hook nil))
18145 (with-selected-window cwin
18146 (calendar-goto-date
18147 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18149 (defun org-goto-calendar (&optional arg)
18150 "Go to the Emacs calendar at the current date.
18151 If there is a time stamp in the current line, go to that date.
18152 A prefix ARG can be used to force the current date."
18153 (interactive "P")
18154 (let ((calendar-move-hook nil)
18155 (calendar-view-holidays-initially-flag nil)
18156 (calendar-view-diary-initially-flag nil)
18157 diff)
18158 (when (or (org-at-timestamp-p 'lax)
18159 (org-match-line (concat ".*" org-ts-regexp)))
18160 (let ((d1 (time-to-days (current-time)))
18161 (d2 (time-to-days
18162 (org-time-string-to-time (match-string 1)))))
18163 (setq diff (- d2 d1))))
18164 (calendar)
18165 (calendar-goto-today)
18166 (when (and diff (not arg)) (calendar-forward-day diff))))
18168 (defun org-get-date-from-calendar ()
18169 "Return a list (month day year) of date at point in calendar."
18170 (with-current-buffer "*Calendar*"
18171 (save-match-data
18172 (calendar-cursor-to-date))))
18174 (defun org-date-from-calendar ()
18175 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18176 If there is already a time stamp at the cursor position, update it."
18177 (interactive)
18178 (if (org-at-timestamp-p 'lax)
18179 (org-timestamp-change 0 'calendar)
18180 (let ((cal-date (org-get-date-from-calendar)))
18181 (org-insert-time-stamp
18182 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18184 (defcustom org-effort-durations
18185 `(("min" . 1)
18186 ("h" . 60)
18187 ("d" . ,(* 60 8))
18188 ("w" . ,(* 60 8 5))
18189 ("m" . ,(* 60 8 5 4))
18190 ("y" . ,(* 60 8 5 40)))
18191 "Conversion factor to minutes for an effort modifier.
18193 Each entry has the form (MODIFIER . MINUTES).
18195 In an effort string, a number followed by MODIFIER is multiplied
18196 by the specified number of MINUTES to obtain an effort in
18197 minutes.
18199 For example, if the value of this variable is ((\"hours\" . 60)), then an
18200 effort string \"2hours\" is equivalent to 120 minutes."
18201 :group 'org-agenda
18202 :version "26.1"
18203 :package-version '(Org . "8.3")
18204 :type '(alist :key-type (string :tag "Modifier")
18205 :value-type (number :tag "Minutes")))
18207 (defcustom org-image-actual-width t
18208 "Should we use the actual width of images when inlining them?
18210 When set to t, always use the image width.
18212 When set to a number, use imagemagick (when available) to set
18213 the image's width to this value.
18215 When set to a number in a list, try to get the width from any
18216 #+ATTR.* keyword if it matches a width specification like
18218 #+ATTR_HTML: :width 300px
18220 and fall back on that number if none is found.
18222 When set to nil, try to get the width from an #+ATTR.* keyword
18223 and fall back on the original width if none is found.
18225 This requires Emacs >= 24.1, build with imagemagick support."
18226 :group 'org-appearance
18227 :version "24.4"
18228 :package-version '(Org . "8.0")
18229 :type '(choice
18230 (const :tag "Use the image width" t)
18231 (integer :tag "Use a number of pixels")
18232 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18233 (const :tag "Use #+ATTR* or don't resize" nil)))
18235 (defcustom org-agenda-inhibit-startup nil
18236 "Inhibit startup when preparing agenda buffers.
18237 When this variable is t, the initialization of the Org agenda
18238 buffers is inhibited: e.g. the visibility state is not set, the
18239 tables are not re-aligned, etc."
18240 :type 'boolean
18241 :version "24.3"
18242 :group 'org-agenda)
18244 (defcustom org-agenda-ignore-properties nil
18245 "Avoid updating text properties when building the agenda.
18246 Properties are used to prepare buffers for effort estimates,
18247 appointments, statistics and subtree-local categories.
18248 If you don't use these in the agenda, you can add them to this
18249 list and agenda building will be a bit faster.
18250 The value is a list, with zero or more of the symbols `effort', `appt',
18251 `stats' or `category'."
18252 :type '(set :greedy t
18253 (const effort)
18254 (const appt)
18255 (const stats)
18256 (const category))
18257 :version "26.1"
18258 :package-version '(Org . "8.3")
18259 :group 'org-agenda)
18261 ;;;; Files
18263 (defun org-save-all-org-buffers ()
18264 "Save all Org buffers without user confirmation."
18265 (interactive)
18266 (message "Saving all Org buffers...")
18267 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18268 (when (featurep 'org-id) (org-id-locations-save))
18269 (message "Saving all Org buffers... done"))
18271 (defun org-revert-all-org-buffers ()
18272 "Revert all Org buffers.
18273 Prompt for confirmation when there are unsaved changes.
18274 Be sure you know what you are doing before letting this function
18275 overwrite your changes.
18277 This function is useful in a setup where one tracks org files
18278 with a version control system, to revert on one machine after pulling
18279 changes from another. I believe the procedure must be like this:
18281 1. M-x org-save-all-org-buffers
18282 2. Pull changes from the other machine, resolve conflicts
18283 3. M-x org-revert-all-org-buffers"
18284 (interactive)
18285 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18286 (user-error "Abort"))
18287 (save-excursion
18288 (save-window-excursion
18289 (dolist (b (buffer-list))
18290 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18291 (with-current-buffer b buffer-file-name))
18292 (pop-to-buffer-same-window b)
18293 (revert-buffer t 'no-confirm)))
18294 (when (and (featurep 'org-id) org-id-track-globally)
18295 (org-id-locations-load)))))
18297 ;;;; Agenda files
18299 ;;;###autoload
18300 (defun org-switchb (&optional arg)
18301 "Switch between Org buffers.
18303 With `\\[universal-argument]' prefix, restrict available buffers to files.
18305 With `\\[universal-argument] \\[universal-argument]' \
18306 prefix, restrict available buffers to agenda files."
18307 (interactive "P")
18308 (let ((blist (org-buffer-list
18309 (cond ((equal arg '(4)) 'files)
18310 ((equal arg '(16)) 'agenda)))))
18311 (pop-to-buffer-same-window
18312 (completing-read "Org buffer: "
18313 (mapcar #'list (mapcar #'buffer-name blist))
18314 nil t))))
18316 (defun org-buffer-list (&optional predicate exclude-tmp)
18317 "Return a list of Org buffers.
18318 PREDICATE can be `export', `files' or `agenda'.
18320 export restrict the list to Export buffers.
18321 files restrict the list to buffers visiting Org files.
18322 agenda restrict the list to buffers visiting agenda files.
18324 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18325 (let* ((bfn nil)
18326 (agenda-files (and (eq predicate 'agenda)
18327 (mapcar 'file-truename (org-agenda-files t))))
18328 (filter
18329 (cond
18330 ((eq predicate 'files)
18331 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18332 ((eq predicate 'export)
18333 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18334 ((eq predicate 'agenda)
18335 (lambda (b)
18336 (with-current-buffer b
18337 (and (derived-mode-p 'org-mode)
18338 (setq bfn (buffer-file-name b))
18339 (member (file-truename bfn) agenda-files)))))
18340 (t (lambda (b) (with-current-buffer b
18341 (or (derived-mode-p 'org-mode)
18342 (string-match "\\*Org .*Export"
18343 (buffer-name b)))))))))
18344 (delq nil
18345 (mapcar
18346 (lambda(b)
18347 (if (and (funcall filter b)
18348 (or (not exclude-tmp)
18349 (not (string-match "tmp" (buffer-name b)))))
18351 nil))
18352 (buffer-list)))))
18354 (defun org-agenda-files (&optional unrestricted archives)
18355 "Get the list of agenda files.
18356 Optional UNRESTRICTED means return the full list even if a restriction
18357 is currently in place.
18358 When ARCHIVES is t, include all archive files that are really being
18359 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18360 `org-agenda-archives-mode' is t."
18361 (let ((files
18362 (cond
18363 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18364 ((stringp org-agenda-files) (org-read-agenda-file-list))
18365 ((listp org-agenda-files) org-agenda-files)
18366 (t (error "Invalid value of `org-agenda-files'")))))
18367 (setq files (apply 'append
18368 (mapcar (lambda (f)
18369 (if (file-directory-p f)
18370 (directory-files
18371 f t org-agenda-file-regexp)
18372 (list f)))
18373 files)))
18374 (when org-agenda-skip-unavailable-files
18375 (setq files (delq nil
18376 (mapcar (function
18377 (lambda (file)
18378 (and (file-readable-p file) file)))
18379 files))))
18380 (when (or (eq archives t)
18381 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18382 (setq files (org-add-archive-files files)))
18383 files))
18385 (defun org-agenda-file-p (&optional file)
18386 "Return non-nil, if FILE is an agenda file.
18387 If FILE is omitted, use the file associated with the current
18388 buffer."
18389 (let ((fname (or file (buffer-file-name))))
18390 (and fname
18391 (member (file-truename fname)
18392 (mapcar #'file-truename (org-agenda-files t))))))
18394 (defun org-edit-agenda-file-list ()
18395 "Edit the list of agenda files.
18396 Depending on setup, this either uses customize to edit the variable
18397 `org-agenda-files', or it visits the file that is holding the list. In the
18398 latter case, the buffer is set up in a way that saving it automatically kills
18399 the buffer and restores the previous window configuration."
18400 (interactive)
18401 (if (stringp org-agenda-files)
18402 (let ((cw (current-window-configuration)))
18403 (find-file org-agenda-files)
18404 (setq-local org-window-configuration cw)
18405 (add-hook 'after-save-hook
18406 (lambda ()
18407 (set-window-configuration
18408 (prog1 org-window-configuration
18409 (kill-buffer (current-buffer))))
18410 (org-install-agenda-files-menu)
18411 (message "New agenda file list installed"))
18412 nil 'local)
18413 (message "%s" (substitute-command-keys
18414 "Edit list and finish with \\[save-buffer]")))
18415 (customize-variable 'org-agenda-files)))
18417 (defun org-store-new-agenda-file-list (list)
18418 "Set new value for the agenda file list and save it correctly."
18419 (if (stringp org-agenda-files)
18420 (let ((fe (org-read-agenda-file-list t)) b u)
18421 (while (setq b (find-buffer-visiting org-agenda-files))
18422 (kill-buffer b))
18423 (with-temp-file org-agenda-files
18424 (insert
18425 (mapconcat
18426 (lambda (f) ;; Keep un-expanded entries.
18427 (if (setq u (assoc f fe))
18428 (cdr u)
18430 list "\n")
18431 "\n")))
18432 (let ((org-mode-hook nil) (org-inhibit-startup t)
18433 (org-insert-mode-line-in-empty-file nil))
18434 (setq org-agenda-files list)
18435 (customize-save-variable 'org-agenda-files org-agenda-files))))
18437 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18438 "Read the list of agenda files from a file.
18439 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18440 filenames, used by `org-store-new-agenda-file-list' to write back
18441 un-expanded file names."
18442 (when (file-directory-p org-agenda-files)
18443 (error "`org-agenda-files' cannot be a single directory"))
18444 (when (stringp org-agenda-files)
18445 (with-temp-buffer
18446 (insert-file-contents org-agenda-files)
18447 (mapcar
18448 (lambda (f)
18449 (let ((e (expand-file-name (substitute-in-file-name f)
18450 org-directory)))
18451 (if pair-with-expansion
18452 (cons e f)
18453 e)))
18454 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18456 ;;;###autoload
18457 (defun org-cycle-agenda-files ()
18458 "Cycle through the files in `org-agenda-files'.
18459 If the current buffer visits an agenda file, find the next one in the list.
18460 If the current buffer does not, find the first agenda file."
18461 (interactive)
18462 (let* ((fs (or (org-agenda-files t)
18463 (user-error "No agenda files")))
18464 (files (copy-sequence fs))
18465 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18466 file)
18467 (when tcf
18468 (while (and (setq file (pop files))
18469 (not (equal (file-truename file) tcf)))))
18470 (find-file (car (or files fs)))
18471 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18473 (defun org-agenda-file-to-front (&optional to-end)
18474 "Move/add the current file to the top of the agenda file list.
18475 If the file is not present in the list, it is added to the front. If it is
18476 present, it is moved there. With optional argument TO-END, add/move to the
18477 end of the list."
18478 (interactive "P")
18479 (let ((org-agenda-skip-unavailable-files nil)
18480 (file-alist (mapcar (lambda (x)
18481 (cons (file-truename x) x))
18482 (org-agenda-files t)))
18483 (ctf (file-truename
18484 (or buffer-file-name
18485 (user-error "Please save the current buffer to a file"))))
18486 x had)
18487 (setq x (assoc ctf file-alist) had x)
18489 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18490 (if to-end
18491 (setq file-alist (append (delq x file-alist) (list x)))
18492 (setq file-alist (cons x (delq x file-alist))))
18493 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18494 (org-install-agenda-files-menu)
18495 (message "File %s to %s of agenda file list"
18496 (if had "moved" "added") (if to-end "end" "front"))))
18498 (defun org-remove-file (&optional file)
18499 "Remove current file from the list of files in variable `org-agenda-files'.
18500 These are the files which are being checked for agenda entries.
18501 Optional argument FILE means use this file instead of the current."
18502 (interactive)
18503 (let* ((org-agenda-skip-unavailable-files nil)
18504 (file (or file buffer-file-name
18505 (user-error "Current buffer does not visit a file")))
18506 (true-file (file-truename file))
18507 (afile (abbreviate-file-name file))
18508 (files (delq nil (mapcar
18509 (lambda (x)
18510 (unless (equal true-file
18511 (file-truename x))
18513 (org-agenda-files t)))))
18514 (if (not (= (length files) (length (org-agenda-files t))))
18515 (progn
18516 (org-store-new-agenda-file-list files)
18517 (org-install-agenda-files-menu)
18518 (message "Removed from Org Agenda list: %s" afile))
18519 (message "File was not in list: %s (not removed)" afile))))
18521 (defun org-file-menu-entry (file)
18522 (vector file (list 'find-file file) t))
18524 (defun org-check-agenda-file (file)
18525 "Make sure FILE exists. If not, ask user what to do."
18526 (unless (file-exists-p file)
18527 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18528 (abbreviate-file-name file))
18529 (let ((r (downcase (read-char-exclusive))))
18530 (cond
18531 ((equal r ?r)
18532 (org-remove-file file)
18533 (throw 'nextfile t))
18534 (t (user-error "Abort"))))))
18536 (defun org-get-agenda-file-buffer (file)
18537 "Get an agenda buffer visiting FILE.
18538 If the buffer needs to be created, add it to the list of buffers
18539 which might be released later."
18540 (let ((buf (org-find-base-buffer-visiting file)))
18541 (if buf
18542 buf ; just return it
18543 ;; Make a new buffer and remember it
18544 (setq buf (find-file-noselect file))
18545 (when buf (push buf org-agenda-new-buffers))
18546 buf)))
18548 (defun org-release-buffers (blist)
18549 "Release all buffers in list, asking the user for confirmation when needed.
18550 When a buffer is unmodified, it is just killed. When modified, it is saved
18551 \(if the user agrees) and then killed."
18552 (let (file)
18553 (dolist (buf blist)
18554 (setq file (buffer-file-name buf))
18555 (when (and (buffer-modified-p buf)
18556 file
18557 (y-or-n-p (format "Save file %s? " file)))
18558 (with-current-buffer buf (save-buffer)))
18559 (kill-buffer buf))))
18561 (defun org-agenda-prepare-buffers (files)
18562 "Create buffers for all agenda files, protect archived trees and comments."
18563 (interactive)
18564 (let ((pa '(:org-archived t))
18565 (pc '(:org-comment t))
18566 (pall '(:org-archived t :org-comment t))
18567 (inhibit-read-only t)
18568 (org-inhibit-startup org-agenda-inhibit-startup)
18569 (rea (concat ":" org-archive-tag ":"))
18570 re pos)
18571 (setq org-tag-alist-for-agenda nil
18572 org-tag-groups-alist-for-agenda nil)
18573 (save-excursion
18574 (save-restriction
18575 (dolist (file files)
18576 (catch 'nextfile
18577 (if (bufferp file)
18578 (set-buffer file)
18579 (org-check-agenda-file file)
18580 (set-buffer (org-get-agenda-file-buffer file)))
18581 (widen)
18582 (org-set-regexps-and-options 'tags-only)
18583 (setq pos (point))
18584 (or (memq 'category org-agenda-ignore-properties)
18585 (org-refresh-category-properties))
18586 (or (memq 'stats org-agenda-ignore-properties)
18587 (org-refresh-stats-properties))
18588 (or (memq 'effort org-agenda-ignore-properties)
18589 (org-refresh-effort-properties))
18590 (or (memq 'appt org-agenda-ignore-properties)
18591 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18592 (setq org-todo-keywords-for-agenda
18593 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18594 (setq org-done-keywords-for-agenda
18595 (append org-done-keywords-for-agenda org-done-keywords))
18596 (setq org-todo-keyword-alist-for-agenda
18597 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18598 (setq org-tag-alist-for-agenda
18599 (org-uniquify
18600 (append org-tag-alist-for-agenda
18601 org-current-tag-alist)))
18602 ;; Merge current file's tag groups into global
18603 ;; `org-tag-groups-alist-for-agenda'.
18604 (when org-group-tags
18605 (dolist (alist org-tag-groups-alist)
18606 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18607 (if old
18608 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18609 (push alist org-tag-groups-alist-for-agenda)))))
18610 (org-with-silent-modifications
18611 (save-excursion
18612 (remove-text-properties (point-min) (point-max) pall)
18613 (when org-agenda-skip-archived-trees
18614 (goto-char (point-min))
18615 (while (re-search-forward rea nil t)
18616 (when (org-at-heading-p t)
18617 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18618 (goto-char (point-min))
18619 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18620 (while (re-search-forward re nil t)
18621 (when (save-match-data (org-in-commented-heading-p t))
18622 (add-text-properties
18623 (match-beginning 0) (org-end-of-subtree t) pc)))))
18624 (goto-char pos)))))
18625 (setq org-todo-keywords-for-agenda
18626 (org-uniquify org-todo-keywords-for-agenda))
18627 (setq org-todo-keyword-alist-for-agenda
18628 (org-uniquify org-todo-keyword-alist-for-agenda))))
18631 ;;;; CDLaTeX minor mode
18633 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18634 "Keymap for the minor `org-cdlatex-mode'.")
18636 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18637 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18638 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18639 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18640 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18642 (defvar org-cdlatex-texmathp-advice-is-done nil
18643 "Flag remembering if we have applied the advice to texmathp already.")
18645 (define-minor-mode org-cdlatex-mode
18646 "Toggle the minor `org-cdlatex-mode'.
18647 This mode supports entering LaTeX environment and math in LaTeX fragments
18648 in Org mode.
18649 \\{org-cdlatex-mode-map}"
18650 nil " OCDL" nil
18651 (when org-cdlatex-mode
18652 (require 'cdlatex)
18653 (run-hooks 'cdlatex-mode-hook)
18654 (cdlatex-compute-tables))
18655 (unless org-cdlatex-texmathp-advice-is-done
18656 (setq org-cdlatex-texmathp-advice-is-done t)
18657 (defadvice texmathp (around org-math-always-on activate)
18658 "Always return t in Org buffers.
18659 This is because we want to insert math symbols without dollars even outside
18660 the LaTeX math segments. If Org mode thinks that point is actually inside
18661 an embedded LaTeX fragment, let `texmathp' do its job.
18662 `\\[org-cdlatex-mode-map]'"
18663 (interactive)
18664 (let (p)
18665 (cond
18666 ((not (derived-mode-p 'org-mode)) ad-do-it)
18667 ((eq this-command 'cdlatex-math-symbol)
18668 (setq ad-return-value t
18669 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18671 (let ((p (org-inside-LaTeX-fragment-p)))
18672 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18673 (setq ad-return-value t
18674 texmathp-why '("Org mode embedded math" . 0))
18675 (when p ad-do-it)))))))))
18677 (defun turn-on-org-cdlatex ()
18678 "Unconditionally turn on `org-cdlatex-mode'."
18679 (org-cdlatex-mode 1))
18681 (defun org-try-cdlatex-tab ()
18682 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18683 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18684 - inside a LaTeX fragment, or
18685 - after the first word in a line, where an abbreviation expansion could
18686 insert a LaTeX environment."
18687 (when org-cdlatex-mode
18688 (cond
18689 ;; Before any word on the line: No expansion possible.
18690 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18691 ;; Just after first word on the line: Expand it. Make sure it
18692 ;; cannot happen on headlines, though.
18693 ((save-excursion
18694 (skip-chars-backward "a-zA-Z0-9*")
18695 (skip-chars-backward " \t")
18696 (and (bolp) (not (org-at-heading-p))))
18697 (cdlatex-tab) t)
18698 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18700 (defun org-cdlatex-underscore-caret (&optional _arg)
18701 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18702 Revert to the normal definition outside of these fragments."
18703 (interactive "P")
18704 (if (org-inside-LaTeX-fragment-p)
18705 (call-interactively 'cdlatex-sub-superscript)
18706 (let (org-cdlatex-mode)
18707 (call-interactively (key-binding (vector last-input-event))))))
18709 (defun org-cdlatex-math-modify (&optional _arg)
18710 "Execute `cdlatex-math-modify' in LaTeX fragments.
18711 Revert to the normal definition outside of these fragments."
18712 (interactive "P")
18713 (if (org-inside-LaTeX-fragment-p)
18714 (call-interactively 'cdlatex-math-modify)
18715 (let (org-cdlatex-mode)
18716 (call-interactively (key-binding (vector last-input-event))))))
18718 (defun org-cdlatex-environment-indent (&optional environment item)
18719 "Execute `cdlatex-environment' and indent the inserted environment.
18721 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18723 The inserted environment is indented to current indentation
18724 unless point is at the beginning of the line, in which the
18725 environment remains unintended."
18726 (interactive)
18727 ;; cdlatex-environment always return nil. Therefore, capture output
18728 ;; first and determine if an environment was selected.
18729 (let* ((beg (point-marker))
18730 (end (copy-marker (point) t))
18731 (inserted (progn
18732 (ignore-errors (cdlatex-environment environment item))
18733 (< beg end)))
18734 ;; Figure out how many lines to move forward after the
18735 ;; environment has been inserted.
18736 (lines (when inserted
18737 (save-excursion
18738 (- (cl-loop while (< beg (point))
18739 with x = 0
18740 do (forward-line -1)
18741 (cl-incf x)
18742 finally return x)
18743 (if (progn (goto-char beg)
18744 (and (progn (skip-chars-forward " \t") (eolp))
18745 (progn (skip-chars-backward " \t") (bolp))))
18746 1 0)))))
18747 (env (org-trim (delete-and-extract-region beg end))))
18748 (when inserted
18749 ;; Get indentation of next line unless at column 0.
18750 (let ((ind (if (bolp) 0
18751 (save-excursion
18752 (org-return-indent)
18753 (prog1 (org-get-indentation)
18754 (when (progn (skip-chars-forward " \t") (eolp))
18755 (delete-region beg (point)))))))
18756 (bol (progn (skip-chars-backward " \t") (bolp))))
18757 ;; Insert a newline before environment unless at column zero
18758 ;; to "escape" the current line. Insert a newline if
18759 ;; something is one the same line as \end{ENVIRONMENT}.
18760 (insert
18761 (concat (unless bol "\n") env
18762 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18763 (unless (zerop ind)
18764 (save-excursion
18765 (goto-char beg)
18766 (while (< (point) end)
18767 (unless (eolp) (indent-line-to ind))
18768 (forward-line))))
18769 (goto-char beg)
18770 (forward-line lines)
18771 (indent-line-to ind)))
18772 (set-marker beg nil)
18773 (set-marker end nil)))
18776 ;;;; LaTeX fragments
18778 (defun org-inside-LaTeX-fragment-p ()
18779 "Test if point is inside a LaTeX fragment.
18780 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18781 sequence appearing also before point.
18782 Even though the matchers for math are configurable, this function assumes
18783 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18784 delimiters are skipped when they have been removed by customization.
18785 The return value is nil, or a cons cell with the delimiter and the
18786 position of this delimiter.
18788 This function does a reasonably good job, but can locally be fooled by
18789 for example currency specifications. For example it will assume being in
18790 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18791 fragments that are properly closed, but during editing, we have to live
18792 with the uncertainty caused by missing closing delimiters. This function
18793 looks only before point, not after."
18794 (catch 'exit
18795 (let ((pos (point))
18796 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18797 (lim (save-excursion (org-backward-paragraph) (point)))
18798 dd-on str (start 0) m re)
18799 (goto-char pos)
18800 (when dodollar
18801 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18802 re (nth 1 (assoc "$" org-latex-regexps)))
18803 (while (string-match re str start)
18804 (cond
18805 ((= (match-end 0) (length str))
18806 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18807 ((= (match-end 0) (- (length str) 5))
18808 (throw 'exit nil))
18809 (t (setq start (match-end 0))))))
18810 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18811 (goto-char pos)
18812 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18813 (and (match-beginning 2) (throw 'exit nil))
18814 ;; count $$
18815 (while (re-search-backward "\\$\\$" lim t)
18816 (setq dd-on (not dd-on)))
18817 (goto-char pos)
18818 (when dd-on (cons "$$" m))))))
18820 (defun org-inside-latex-macro-p ()
18821 "Is point inside a LaTeX macro or its arguments?"
18822 (save-match-data
18823 (org-in-regexp
18824 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18826 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18827 "Build an overlay between BEG and END using IMAGE file.
18828 Argument IMAGETYPE is the extension of the displayed image,
18829 as a string. It defaults to \"png\"."
18830 (let ((ov (make-overlay beg end))
18831 (imagetype (or (intern imagetype) 'png)))
18832 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18833 (overlay-put ov 'evaporate t)
18834 (overlay-put ov
18835 'modification-hooks
18836 (list (lambda (o _flag _beg _end &optional _l)
18837 (delete-overlay o))))
18838 (overlay-put ov
18839 'display
18840 (list 'image :type imagetype :file image :ascent 'center))))
18842 (defun org--list-latex-overlays (&optional beg end)
18843 "List all Org LaTeX overlays in current buffer.
18844 Limit to overlays between BEG and END when those are provided."
18845 (cl-remove-if-not
18846 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18847 (overlays-in (or beg (point-min)) (or end (point-max)))))
18849 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18850 "Remove all overlays with LaTeX fragment images in current buffer.
18851 When optional arguments BEG and END are non-nil, remove all
18852 overlays between them instead. Return a non-nil value when some
18853 overlays were removed, nil otherwise."
18854 (let ((overlays (org--list-latex-overlays beg end)))
18855 (mapc #'delete-overlay overlays)
18856 overlays))
18858 (defun org-toggle-latex-fragment (&optional arg)
18859 "Preview the LaTeX fragment at point, or all locally or globally.
18861 If the cursor is on a LaTeX fragment, create the image and overlay
18862 it over the source code, if there is none. Remove it otherwise.
18863 If there is no fragment at point, display all fragments in the
18864 current section.
18866 With prefix ARG, preview or clear image for all fragments in the
18867 current subtree or in the whole buffer when used before the first
18868 headline. With a prefix ARG `\\[universal-argument] \
18869 \\[universal-argument]' preview or clear images
18870 for all fragments in the buffer."
18871 (interactive "P")
18872 (when (display-graphic-p)
18873 (catch 'exit
18874 (save-excursion
18875 (let (beg end msg)
18876 (cond
18877 ((or (equal arg '(16))
18878 (and (equal arg '(4))
18879 (org-with-limited-levels (org-before-first-heading-p))))
18880 (if (org-remove-latex-fragment-image-overlays)
18881 (progn (message "LaTeX fragments images removed from buffer")
18882 (throw 'exit nil))
18883 (setq msg "Creating images for buffer...")))
18884 ((equal arg '(4))
18885 (org-with-limited-levels (org-back-to-heading t))
18886 (setq beg (point))
18887 (setq end (progn (org-end-of-subtree t) (point)))
18888 (if (org-remove-latex-fragment-image-overlays beg end)
18889 (progn
18890 (message "LaTeX fragment images removed from subtree")
18891 (throw 'exit nil))
18892 (setq msg "Creating images for subtree...")))
18893 ((let ((datum (org-element-context)))
18894 (when (memq (org-element-type datum)
18895 '(latex-environment latex-fragment))
18896 (setq beg (org-element-property :begin datum))
18897 (setq end (org-element-property :end datum))
18898 (if (org-remove-latex-fragment-image-overlays beg end)
18899 (progn (message "LaTeX fragment image removed")
18900 (throw 'exit nil))
18901 (setq msg "Creating image...")))))
18903 (org-with-limited-levels
18904 (setq beg (if (org-at-heading-p) (line-beginning-position)
18905 (outline-previous-heading)
18906 (point)))
18907 (setq end (progn (outline-next-heading) (point)))
18908 (if (org-remove-latex-fragment-image-overlays beg end)
18909 (progn
18910 (message "LaTeX fragment images removed from section")
18911 (throw 'exit nil))
18912 (setq msg "Creating images for section...")))))
18913 (let ((file (buffer-file-name (buffer-base-buffer))))
18914 (org-format-latex
18915 (concat org-preview-latex-image-directory "org-ltximg")
18916 beg end
18917 ;; Emacs cannot overlay images from remote hosts. Create
18918 ;; it in `temporary-file-directory' instead.
18919 (if (or (not file) (file-remote-p file))
18920 temporary-file-directory
18921 default-directory)
18922 'overlays msg 'forbuffer org-preview-latex-default-process))
18923 (message (concat msg "done")))))))
18925 (defun org-format-latex
18926 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18927 "Replace LaTeX fragments with links to an image.
18929 The function takes care of creating the replacement image.
18931 Only consider fragments between BEG and END when those are
18932 provided.
18934 When optional argument OVERLAYS is non-nil, display the image on
18935 top of the fragment instead of replacing it.
18937 PROCESSING-TYPE is the conversion method to use, as a symbol.
18939 Some of the options can be changed using the variable
18940 `org-format-latex-options', which see."
18941 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18942 (unless (eq processing-type 'verbatim)
18943 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18944 (cnt 0)
18945 checkdir-flag)
18946 (goto-char (or beg (point-min)))
18947 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18948 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18949 (overlay-recenter (or end (point-max))))
18950 (while (re-search-forward math-regexp end t)
18951 (unless (and overlays
18952 (eq (get-char-property (point) 'org-overlay-type)
18953 'org-latex-overlay))
18954 (let* ((context (org-element-context))
18955 (type (org-element-type context)))
18956 (when (memq type '(latex-environment latex-fragment))
18957 (let ((block-type (eq type 'latex-environment))
18958 (value (org-element-property :value context))
18959 (beg (org-element-property :begin context))
18960 (end (save-excursion
18961 (goto-char (org-element-property :end context))
18962 (skip-chars-backward " \r\t\n")
18963 (point))))
18964 (cond
18965 ((eq processing-type 'mathjax)
18966 ;; Prepare for MathJax processing.
18967 (if (not (string-match "\\`\\$\\$?" value))
18968 (goto-char end)
18969 (delete-region beg end)
18970 (if (string= (match-string 0 value) "$$")
18971 (insert "\\[" (substring value 2 -2) "\\]")
18972 (insert "\\(" (substring value 1 -1) "\\)"))))
18973 ((assq processing-type org-preview-latex-process-alist)
18974 ;; Process to an image.
18975 (cl-incf cnt)
18976 (goto-char beg)
18977 (let* ((processing-info
18978 (cdr (assq processing-type org-preview-latex-process-alist)))
18979 (face (face-at-point))
18980 ;; Get the colors from the face at point.
18982 (let ((color (plist-get org-format-latex-options
18983 :foreground)))
18984 (if (and forbuffer (eq color 'auto))
18985 (face-attribute face :foreground nil 'default)
18986 color)))
18988 (let ((color (plist-get org-format-latex-options
18989 :background)))
18990 (if (and forbuffer (eq color 'auto))
18991 (face-attribute face :background nil 'default)
18992 color)))
18993 (hash (sha1 (prin1-to-string
18994 (list org-format-latex-header
18995 org-latex-default-packages-alist
18996 org-latex-packages-alist
18997 org-format-latex-options
18998 forbuffer value fg bg))))
18999 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19000 (absprefix (expand-file-name prefix dir))
19001 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19002 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19003 (sep (and block-type "\n\n"))
19004 (link (concat sep "[[file:" linkfile "]]" sep))
19005 (options
19006 (org-combine-plists
19007 org-format-latex-options
19008 `(:foreground ,fg :background ,bg))))
19009 (when msg (message msg cnt))
19010 (unless checkdir-flag ; Ensure the directory exists.
19011 (setq checkdir-flag t)
19012 (let ((todir (file-name-directory absprefix)))
19013 (unless (file-directory-p todir)
19014 (make-directory todir t))))
19015 (unless (file-exists-p movefile)
19016 (org-create-formula-image
19017 value movefile options forbuffer processing-type))
19018 (if overlays
19019 (progn
19020 (dolist (o (overlays-in beg end))
19021 (when (eq (overlay-get o 'org-overlay-type)
19022 'org-latex-overlay)
19023 (delete-overlay o)))
19024 (org--format-latex-make-overlay beg end movefile imagetype)
19025 (goto-char end))
19026 (delete-region beg end)
19027 (insert
19028 (org-add-props link
19029 (list 'org-latex-src
19030 (replace-regexp-in-string "\"" "" value)
19031 'org-latex-src-embed-type
19032 (if block-type 'paragraph 'character)))))))
19033 ((eq processing-type 'mathml)
19034 ;; Process to MathML.
19035 (unless (org-format-latex-mathml-available-p)
19036 (user-error "LaTeX to MathML converter not configured"))
19037 (cl-incf cnt)
19038 (when msg (message msg cnt))
19039 (goto-char beg)
19040 (delete-region beg end)
19041 (insert (org-format-latex-as-mathml
19042 value block-type prefix dir)))
19044 (error "Unknown conversion process %s for LaTeX fragments"
19045 processing-type)))))))))))
19047 (defun org-create-math-formula (latex-frag &optional mathml-file)
19048 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19049 Use `org-latex-to-mathml-convert-command'. If the conversion is
19050 sucessful, return the portion between \"<math...> </math>\"
19051 elements otherwise return nil. When MATHML-FILE is specified,
19052 write the results in to that file. When invoked as an
19053 interactive command, prompt for LATEX-FRAG, with initial value
19054 set to the current active region and echo the results for user
19055 inspection."
19056 (interactive (list (let ((frag (when (org-region-active-p)
19057 (buffer-substring-no-properties
19058 (region-beginning) (region-end)))))
19059 (read-string "LaTeX Fragment: " frag nil frag))))
19060 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19061 (let* ((tmp-in-file
19062 (let ((file (file-relative-name
19063 (make-temp-name (expand-file-name "ltxmathml-in")))))
19064 (write-region latex-frag nil file)
19065 file))
19066 (tmp-out-file (file-relative-name
19067 (make-temp-name (expand-file-name "ltxmathml-out"))))
19068 (cmd (format-spec
19069 org-latex-to-mathml-convert-command
19070 `((?j . ,(and org-latex-to-mathml-jar-file
19071 (shell-quote-argument
19072 (expand-file-name
19073 org-latex-to-mathml-jar-file))))
19074 (?I . ,(shell-quote-argument tmp-in-file))
19075 (?i . ,latex-frag)
19076 (?o . ,(shell-quote-argument tmp-out-file)))))
19077 mathml shell-command-output)
19078 (when (called-interactively-p 'any)
19079 (unless (org-format-latex-mathml-available-p)
19080 (user-error "LaTeX to MathML converter not configured")))
19081 (message "Running %s" cmd)
19082 (setq shell-command-output (shell-command-to-string cmd))
19083 (setq mathml
19084 (when (file-readable-p tmp-out-file)
19085 (with-current-buffer (find-file-noselect tmp-out-file t)
19086 (goto-char (point-min))
19087 (when (re-search-forward
19088 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19089 (regexp-quote
19090 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19091 nil t)
19092 (prog1 (match-string 0) (kill-buffer))))))
19093 (cond
19094 (mathml
19095 (setq mathml
19096 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19097 (when mathml-file
19098 (write-region mathml nil mathml-file))
19099 (when (called-interactively-p 'any)
19100 (message mathml)))
19101 ((message "LaTeX to MathML conversion failed")
19102 (message shell-command-output)))
19103 (delete-file tmp-in-file)
19104 (when (file-exists-p tmp-out-file)
19105 (delete-file tmp-out-file))
19106 mathml))
19108 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19109 prefix &optional dir)
19110 "Use `org-create-math-formula' but check local cache first."
19111 (let* ((absprefix (expand-file-name prefix dir))
19112 (print-length nil) (print-level nil)
19113 (formula-id (concat
19114 "formula-"
19115 (sha1
19116 (prin1-to-string
19117 (list latex-frag
19118 org-latex-to-mathml-convert-command)))))
19119 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19120 (formula-cache-dir (file-name-directory formula-cache)))
19122 (unless (file-directory-p formula-cache-dir)
19123 (make-directory formula-cache-dir t))
19125 (unless (file-exists-p formula-cache)
19126 (org-create-math-formula latex-frag formula-cache))
19128 (if (file-exists-p formula-cache)
19129 ;; Successful conversion. Return the link to MathML file.
19130 (org-add-props
19131 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19132 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19133 'org-latex-src-embed-type (if latex-frag-type
19134 'paragraph 'character)))
19135 ;; Failed conversion. Return the LaTeX fragment verbatim
19136 latex-frag)))
19138 (defun org--get-display-dpi ()
19139 "Get the DPI of the display.
19140 The function assumes that the display has the same pixel width in
19141 the horizontal and vertical directions."
19142 (if (display-graphic-p)
19143 (round (/ (display-pixel-height)
19144 (/ (display-mm-height) 25.4)))
19145 (error "Attempt to calculate the dpi of a non-graphic display")))
19147 (defun org-create-formula-image
19148 (string tofile options buffer &optional processing-type)
19149 "Create an image from LaTeX source using external processes.
19151 The LaTeX STRING is saved to a temporary LaTeX file, then
19152 converted to an image file by process PROCESSING-TYPE defined in
19153 `org-preview-latex-process-alist'. A nil value defaults to
19154 `org-preview-latex-default-process'.
19156 The generated image file is eventually moved to TOFILE.
19158 The OPTIONS argument controls the size, foreground color and
19159 background color of the generated image.
19161 When BUFFER non-nil, this function is used for LaTeX previewing.
19162 Otherwise, it is used to deal with LaTeX snippets showed in
19163 a HTML file."
19164 (let* ((processing-type (or processing-type
19165 org-preview-latex-default-process))
19166 (processing-info
19167 (cdr (assq processing-type org-preview-latex-process-alist)))
19168 (programs (plist-get processing-info :programs))
19169 (error-message (or (plist-get processing-info :message) ""))
19170 (use-xcolor (plist-get processing-info :use-xcolor))
19171 (image-input-type (plist-get processing-info :image-input-type))
19172 (image-output-type (plist-get processing-info :image-output-type))
19173 (post-clean (or (plist-get processing-info :post-clean)
19174 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19175 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19176 (latex-header
19177 (or (plist-get processing-info :latex-header)
19178 (org-latex-make-preamble
19179 (org-export-get-environment (org-export-get-backend 'latex))
19180 org-format-latex-header
19181 'snippet)))
19182 (latex-compiler (plist-get processing-info :latex-compiler))
19183 (image-converter (plist-get processing-info :image-converter))
19184 (tmpdir temporary-file-directory)
19185 (texfilebase (make-temp-name
19186 (expand-file-name "orgtex" tmpdir)))
19187 (texfile (concat texfilebase ".tex"))
19188 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19189 '(1.0 . 1.0)))
19190 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19191 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19192 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19193 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19194 "Black"))
19195 (bg (or (plist-get options (if buffer :background :html-background))
19196 "Transparent"))
19197 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19198 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19199 (dolist (program programs)
19200 (org-check-external-command program error-message))
19201 (if use-xcolor
19202 (progn (if (eq fg 'default)
19203 (setq fg (org-latex-color :foreground))
19204 (setq fg (org-latex-color-format fg)))
19205 (if (eq bg 'default)
19206 (setq bg (org-latex-color :background))
19207 (setq bg (org-latex-color-format
19208 (if (string= bg "Transparent") "white" bg))))
19209 (with-temp-file texfile
19210 (insert latex-header)
19211 (insert "\n\\begin{document}\n"
19212 "\\definecolor{fg}{rgb}{" fg "}\n"
19213 "\\definecolor{bg}{rgb}{" bg "}\n"
19214 "\n\\pagecolor{bg}\n"
19215 "\n{\\color{fg}\n"
19216 string
19217 "\n}\n"
19218 "\n\\end{document}\n")))
19219 (if (eq fg 'default)
19220 (setq fg (org-dvipng-color :foreground))
19221 (unless (string= fg "Transparent")
19222 (setq fg (org-dvipng-color-format fg))))
19223 (if (eq bg 'default)
19224 (setq bg (org-dvipng-color :background))
19225 (unless (string= bg "Transparent")
19226 (setq bg (org-dvipng-color-format bg))))
19227 (with-temp-file texfile
19228 (insert latex-header)
19229 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19231 (let* ((err-msg (format "Please adjust '%s' part of \
19232 `org-preview-latex-process-alist'."
19233 processing-type))
19234 (image-input-file
19235 (org-compile-file
19236 texfile latex-compiler image-input-type err-msg log-buf))
19237 (image-output-file
19238 (org-compile-file
19239 image-input-file image-converter image-output-type err-msg log-buf
19240 `((?F . ,(shell-quote-argument fg))
19241 (?B . ,(shell-quote-argument bg))
19242 (?D . ,(shell-quote-argument (format "%s" dpi)))
19243 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19244 (copy-file image-output-file tofile 'replace)
19245 (dolist (e post-clean)
19246 (when (file-exists-p (concat texfilebase e))
19247 (delete-file (concat texfilebase e))))
19248 image-output-file)))
19250 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19251 "Fill a LaTeX header template TPL.
19252 In the template, the following place holders will be recognized:
19254 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19255 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19256 [PACKAGES] \\usepackage statements for PKG
19257 [NO-PACKAGES] do not include PKG
19258 [EXTRA] the string EXTRA
19259 [NO-EXTRA] do not include EXTRA
19261 For backward compatibility, if both the positive and the negative place
19262 holder is missing, the positive one (without the \"NO-\") will be
19263 assumed to be present at the end of the template.
19264 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19265 EXTRA is a string.
19266 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19267 (let (rpl (end ""))
19268 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19269 (setq rpl (if (or (match-end 1) (not def-pkg))
19270 "" (org-latex-packages-to-string def-pkg snippets-p t))
19271 tpl (replace-match rpl t t tpl))
19272 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19274 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19275 (setq rpl (if (or (match-end 1) (not pkg))
19276 "" (org-latex-packages-to-string pkg snippets-p t))
19277 tpl (replace-match rpl t t tpl))
19278 (when pkg (setq end
19279 (concat end "\n"
19280 (org-latex-packages-to-string pkg snippets-p)))))
19282 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19283 (setq rpl (if (or (match-end 1) (not extra))
19284 "" (concat extra "\n"))
19285 tpl (replace-match rpl t t tpl))
19286 (when (and extra (string-match "\\S-" extra))
19287 (setq end (concat end "\n" extra))))
19289 (if (string-match "\\S-" end)
19290 (concat tpl "\n" end)
19291 tpl)))
19293 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19294 "Turn an alist of packages into a string with the \\usepackage macros."
19295 (setq pkg (mapconcat (lambda(p)
19296 (cond
19297 ((stringp p) p)
19298 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19299 (format "%% Package %s omitted" (cadr p)))
19300 ((equal "" (car p))
19301 (format "\\usepackage{%s}" (cadr p)))
19303 (format "\\usepackage[%s]{%s}"
19304 (car p) (cadr p)))))
19306 "\n"))
19307 (if newline (concat pkg "\n") pkg))
19309 (defun org-dvipng-color (attr)
19310 "Return a RGB color specification for dvipng."
19311 (org-dvipng-color-format (face-attribute 'default attr nil)))
19313 (defun org-dvipng-color-format (color-name)
19314 "Convert COLOR-NAME to a RGB color value for dvipng."
19315 (apply #'format "rgb %s %s %s"
19316 (mapcar 'org-normalize-color
19317 (color-values color-name))))
19319 (defun org-latex-color (attr)
19320 "Return a RGB color for the LaTeX color package."
19321 (org-latex-color-format (face-attribute 'default attr nil)))
19323 (defun org-latex-color-format (color-name)
19324 "Convert COLOR-NAME to a RGB color value."
19325 (apply #'format "%s,%s,%s"
19326 (mapcar 'org-normalize-color
19327 (color-values color-name))))
19329 (defun org-normalize-color (value)
19330 "Return string to be used as color value for an RGB component."
19331 (format "%g" (/ value 65535.0)))
19335 ;; Image display
19337 (defvar-local org-inline-image-overlays nil)
19339 (defun org-toggle-inline-images (&optional include-linked)
19340 "Toggle the display of inline images.
19341 INCLUDE-LINKED is passed to `org-display-inline-images'."
19342 (interactive "P")
19343 (if org-inline-image-overlays
19344 (progn
19345 (org-remove-inline-images)
19346 (when (called-interactively-p 'interactive)
19347 (message "Inline image display turned off")))
19348 (org-display-inline-images include-linked)
19349 (when (called-interactively-p 'interactive)
19350 (message (if org-inline-image-overlays
19351 (format "%d images displayed inline"
19352 (length org-inline-image-overlays))
19353 "No images to display inline")))))
19355 (defun org-redisplay-inline-images ()
19356 "Refresh the display of inline images."
19357 (interactive)
19358 (if (not org-inline-image-overlays)
19359 (org-toggle-inline-images)
19360 (org-toggle-inline-images)
19361 (org-toggle-inline-images)))
19363 (defun org-display-inline-images (&optional include-linked refresh beg end)
19364 "Display inline images.
19366 An inline image is a link which follows either of these
19367 conventions:
19369 1. Its path is a file with an extension matching return value
19370 from `image-file-name-regexp' and it has no contents.
19372 2. Its description consists in a single link of the previous
19373 type.
19375 When optional argument INCLUDE-LINKED is non-nil, also links with
19376 a text description part will be inlined. This can be nice for
19377 a quick look at those images, but it does not reflect what
19378 exported files will look like.
19380 When optional argument REFRESH is non-nil, refresh existing
19381 images between BEG and END. This will create new image displays
19382 only if necessary. BEG and END default to the buffer
19383 boundaries."
19384 (interactive "P")
19385 (when (display-graphic-p)
19386 (unless refresh
19387 (org-remove-inline-images)
19388 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19389 (org-with-wide-buffer
19390 (goto-char (or beg (point-min)))
19391 (let ((case-fold-search t)
19392 (file-extension-re (image-file-name-regexp)))
19393 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19394 (let ((link (save-match-data (org-element-context))))
19395 ;; Check if we're at an inline image.
19396 (when (and (equal (org-element-property :type link) "file")
19397 (or include-linked
19398 (not (org-element-property :contents-begin link)))
19399 (let ((parent (org-element-property :parent link)))
19400 (or (not (eq (org-element-type parent) 'link))
19401 (not (cdr (org-element-contents parent)))))
19402 (string-match-p file-extension-re
19403 (org-element-property :path link)))
19404 (let ((file (expand-file-name
19405 (org-link-unescape
19406 (org-element-property :path link)))))
19407 (when (file-exists-p file)
19408 (let ((width
19409 ;; Apply `org-image-actual-width' specifications.
19410 (cond
19411 ((not (image-type-available-p 'imagemagick)) nil)
19412 ((eq org-image-actual-width t) nil)
19413 ((listp org-image-actual-width)
19415 ;; First try to find a width among
19416 ;; attributes associated to the paragraph
19417 ;; containing link.
19418 (let ((paragraph
19419 (let ((e link))
19420 (while (and (setq e (org-element-property
19421 :parent e))
19422 (not (eq (org-element-type e)
19423 'paragraph))))
19424 e)))
19425 (when paragraph
19426 (save-excursion
19427 (goto-char (org-element-property :begin paragraph))
19428 (when
19429 (re-search-forward
19430 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19431 (org-element-property
19432 :post-affiliated paragraph)
19434 (string-to-number (match-string 1))))))
19435 ;; Otherwise, fall-back to provided number.
19436 (car org-image-actual-width)))
19437 ((numberp org-image-actual-width)
19438 org-image-actual-width)))
19439 (old (get-char-property-and-overlay
19440 (org-element-property :begin link)
19441 'org-image-overlay)))
19442 (if (and (car-safe old) refresh)
19443 (image-refresh (overlay-get (cdr old) 'display))
19444 (let ((image (create-image file
19445 (and width 'imagemagick)
19447 :width width)))
19448 (when image
19449 (let* ((link
19450 ;; If inline image is the description
19451 ;; of another link, be sure to
19452 ;; consider the latter as the one to
19453 ;; apply the overlay on.
19454 (let ((parent
19455 (org-element-property :parent link)))
19456 (if (eq (org-element-type parent) 'link)
19457 parent
19458 link)))
19459 (ov (make-overlay
19460 (org-element-property :begin link)
19461 (progn
19462 (goto-char
19463 (org-element-property :end link))
19464 (skip-chars-backward " \t")
19465 (point)))))
19466 (overlay-put ov 'display image)
19467 (overlay-put ov 'face 'default)
19468 (overlay-put ov 'org-image-overlay t)
19469 (overlay-put
19470 ov 'modification-hooks
19471 (list 'org-display-inline-remove-overlay))
19472 (push ov org-inline-image-overlays)))))))))))))))
19474 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19475 "Remove inline-display overlay if a corresponding region is modified."
19476 (let ((inhibit-modification-hooks t))
19477 (when (and ov after)
19478 (delete ov org-inline-image-overlays)
19479 (delete-overlay ov))))
19481 (defun org-remove-inline-images ()
19482 "Remove inline display of images."
19483 (interactive)
19484 (mapc #'delete-overlay org-inline-image-overlays)
19485 (setq org-inline-image-overlays nil))
19487 ;;;; Key bindings
19489 ;; Outline functions from `outline-mode-prefix-map'
19490 ;; that can be remapped in Org:
19491 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19492 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19493 (define-key org-mode-map [remap outline-forward-same-level]
19494 'org-forward-heading-same-level)
19495 (define-key org-mode-map [remap outline-backward-same-level]
19496 'org-backward-heading-same-level)
19497 (define-key org-mode-map [remap outline-show-branches]
19498 'org-kill-note-or-show-branches)
19499 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19500 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19501 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19502 (define-key org-mode-map [remap outline-next-visible-heading]
19503 'org-next-visible-heading)
19504 (define-key org-mode-map [remap outline-previous-visible-heading]
19505 'org-previous-visible-heading)
19506 (define-key org-mode-map [remap show-children] 'org-show-children)
19508 ;; Outline functions from `outline-mode-prefix-map' that can not
19509 ;; be remapped in Org:
19511 ;; - the column "key binding" shows whether the Outline function is still
19512 ;; available in Org mode on the same key that it has been bound to in
19513 ;; Outline mode:
19514 ;; - "overridden": key used for a different functionality in Org mode
19515 ;; - else: key still bound to the same Outline function in Org mode
19517 ;; | Outline function | key binding | Org replacement |
19518 ;; |------------------------------------+-------------+--------------------------|
19519 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19520 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19521 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19522 ;; | `show-entry' | overridden | no replacement |
19523 ;; | `show-branches' | `C-c C-k' | still same function |
19524 ;; | `show-subtree' | overridden | visibility cycling |
19525 ;; | `show-all' | overridden | no replacement |
19526 ;; | `hide-subtree' | overridden | visibility cycling |
19527 ;; | `hide-body' | overridden | no replacement |
19528 ;; | `hide-entry' | overridden | visibility cycling |
19529 ;; | `hide-leaves' | overridden | no replacement |
19530 ;; | `hide-sublevels' | overridden | no replacement |
19531 ;; | `hide-other' | overridden | no replacement |
19533 ;; Make `C-c C-x' a prefix key
19534 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19536 ;; TAB key with modifiers
19537 (org-defkey org-mode-map "\C-i" 'org-cycle)
19538 (org-defkey org-mode-map [(tab)] 'org-cycle)
19539 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19540 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19541 ;; The following line is necessary under Suse GNU/Linux
19542 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19543 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19544 (define-key org-mode-map [backtab] 'org-shifttab)
19546 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19547 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19548 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19550 ;; Cursor keys with modifiers
19551 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19552 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19553 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19554 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19556 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19557 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19558 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19559 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19560 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19561 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19563 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19564 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19565 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19566 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19568 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19569 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19570 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19571 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19573 ;; Babel keys
19574 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19575 (dolist (pair org-babel-key-bindings)
19576 (define-key org-babel-map (car pair) (cdr pair)))
19578 ;;; Extra keys for tty access.
19579 ;; We only set them when really needed because otherwise the
19580 ;; menus don't show the simple keys
19582 (when (or org-use-extra-keys (not window-system))
19583 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19584 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19585 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19586 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19587 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19588 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19589 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19590 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19591 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19592 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19593 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19594 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19595 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19596 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19597 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19598 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19599 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19600 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19601 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19602 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19603 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19604 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19605 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19606 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19607 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19608 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19609 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19610 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19612 ;; All the other keys
19614 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19615 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19616 (if (boundp 'narrow-map)
19617 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19618 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19619 (if (boundp 'narrow-map)
19620 (org-defkey narrow-map "b" 'org-narrow-to-block)
19621 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19622 (if (boundp 'narrow-map)
19623 (org-defkey narrow-map "e" 'org-narrow-to-element)
19624 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19625 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19626 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19627 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19628 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19629 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19630 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19631 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19632 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19633 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19634 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19635 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19636 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19637 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19638 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19639 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19640 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19641 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19642 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19643 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19644 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19645 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19646 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19647 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19648 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19649 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19650 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19651 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19652 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19653 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19654 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19655 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19656 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19657 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19658 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19659 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19660 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19661 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19662 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19663 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19664 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19665 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19666 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19667 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19668 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19669 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19670 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19671 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19672 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19673 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19674 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19675 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19676 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19677 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19678 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19679 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19680 (org-defkey org-mode-map "\C-c^" 'org-sort)
19681 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19682 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19683 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19684 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19685 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19686 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19687 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19688 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19689 (org-defkey org-mode-map "\C-m" 'org-return)
19690 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19691 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19692 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19693 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19694 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19695 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19696 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19697 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19698 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19699 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19700 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19701 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19702 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19703 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19704 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19705 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19706 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19707 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19708 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19709 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19710 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19711 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19712 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19713 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19714 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19716 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19717 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19718 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19720 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19721 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19722 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19723 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19724 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19725 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19726 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19727 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19728 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19729 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19730 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19731 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19732 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19733 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19734 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19735 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19736 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19737 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19738 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19739 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19740 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19741 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19743 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19744 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19745 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19746 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19747 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19749 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19751 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19753 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19754 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19756 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19759 (defconst org-speed-commands-default
19761 ("Outline Navigation")
19762 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19763 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19764 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19765 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19766 ("F" . org-next-block)
19767 ("B" . org-previous-block)
19768 ("u" . (org-speed-move-safe 'outline-up-heading))
19769 ("j" . org-goto)
19770 ("g" . (org-refile t))
19771 ("Outline Visibility")
19772 ("c" . org-cycle)
19773 ("C" . org-shifttab)
19774 (" " . org-display-outline-path)
19775 ("s" . org-narrow-to-subtree)
19776 ("=" . org-columns)
19777 ("Outline Structure Editing")
19778 ("U" . org-metaup)
19779 ("D" . org-metadown)
19780 ("r" . org-metaright)
19781 ("l" . org-metaleft)
19782 ("R" . org-shiftmetaright)
19783 ("L" . org-shiftmetaleft)
19784 ("i" . (progn (forward-char 1) (call-interactively
19785 'org-insert-heading-respect-content)))
19786 ("^" . org-sort)
19787 ("w" . org-refile)
19788 ("a" . org-archive-subtree-default-with-confirmation)
19789 ("@" . org-mark-subtree)
19790 ("#" . org-toggle-comment)
19791 ("Clock Commands")
19792 ("I" . org-clock-in)
19793 ("O" . org-clock-out)
19794 ("Meta Data Editing")
19795 ("t" . org-todo)
19796 ("," . (org-priority))
19797 ("0" . (org-priority ?\ ))
19798 ("1" . (org-priority ?A))
19799 ("2" . (org-priority ?B))
19800 ("3" . (org-priority ?C))
19801 (":" . org-set-tags-command)
19802 ("e" . org-set-effort)
19803 ("E" . org-inc-effort)
19804 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19805 (org-entry-put (point) "APPT_WARNTIME" m)))
19806 ("Agenda Views etc")
19807 ("v" . org-agenda)
19808 ("/" . org-sparse-tree)
19809 ("Misc")
19810 ("o" . org-open-at-point)
19811 ("?" . org-speed-command-help)
19812 ("<" . (org-agenda-set-restriction-lock 'subtree))
19813 (">" . (org-agenda-remove-restriction-lock))
19815 "The default speed commands.")
19817 (defun org-print-speed-command (e)
19818 (if (> (length (car e)) 1)
19819 (progn
19820 (princ "\n")
19821 (princ (car e))
19822 (princ "\n")
19823 (princ (make-string (length (car e)) ?-))
19824 (princ "\n"))
19825 (princ (car e))
19826 (princ " ")
19827 (if (symbolp (cdr e))
19828 (princ (symbol-name (cdr e)))
19829 (prin1 (cdr e)))
19830 (princ "\n")))
19832 (defun org-speed-command-help ()
19833 "Show the available speed commands."
19834 (interactive)
19835 (if (not org-use-speed-commands)
19836 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19837 (with-output-to-temp-buffer "*Help*"
19838 (princ "User-defined Speed commands\n===========================\n")
19839 (mapc #'org-print-speed-command org-speed-commands-user)
19840 (princ "\n")
19841 (princ "Built-in Speed commands\n=======================\n")
19842 (mapc #'org-print-speed-command org-speed-commands-default))
19843 (with-current-buffer "*Help*"
19844 (setq truncate-lines t))))
19846 (defun org-speed-move-safe (cmd)
19847 "Execute CMD, but make sure that the cursor always ends up in a headline.
19848 If not, return to the original position and throw an error."
19849 (interactive)
19850 (let ((pos (point)))
19851 (call-interactively cmd)
19852 (unless (and (bolp) (org-at-heading-p))
19853 (goto-char pos)
19854 (error "Boundary reached while executing %s" cmd))))
19856 (defvar org-self-insert-command-undo-counter 0)
19858 (defvar org-table-auto-blank-field) ; defined in org-table.el
19859 (defvar org-speed-command nil)
19861 (defun org-speed-command-activate (keys)
19862 "Hook for activating single-letter speed commands.
19863 `org-speed-commands-default' specifies a minimal command set.
19864 Use `org-speed-commands-user' for further customization."
19865 (when (or (and (bolp) (looking-at org-outline-regexp))
19866 (and (functionp org-use-speed-commands)
19867 (funcall org-use-speed-commands)))
19868 (cdr (assoc keys (append org-speed-commands-user
19869 org-speed-commands-default)))))
19871 (defun org-babel-speed-command-activate (keys)
19872 "Hook for activating single-letter code block commands."
19873 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19874 (cdr (assoc keys org-babel-key-bindings))))
19876 (defcustom org-speed-command-hook
19877 '(org-speed-command-activate org-babel-speed-command-activate)
19878 "Hook for activating speed commands at strategic locations.
19879 Hook functions are called in sequence until a valid handler is
19880 found.
19882 Each hook takes a single argument, a user-pressed command key
19883 which is also a `self-insert-command' from the global map.
19885 Within the hook, examine the cursor position and the command key
19886 and return nil or a valid handler as appropriate. Handler could
19887 be one of an interactive command, a function, or a form.
19889 Set `org-use-speed-commands' to non-nil value to enable this
19890 hook. The default setting is `org-speed-command-activate'."
19891 :group 'org-structure
19892 :version "24.1"
19893 :type 'hook)
19895 (defun org-self-insert-command (N)
19896 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19897 If the cursor is in a table looking at whitespace, the whitespace is
19898 overwritten, and the table is not marked as requiring realignment."
19899 (interactive "p")
19900 (org-check-before-invisible-edit 'insert)
19901 (cond
19902 ((and org-use-speed-commands
19903 (let ((kv (this-command-keys-vector)))
19904 (setq org-speed-command
19905 (run-hook-with-args-until-success
19906 'org-speed-command-hook
19907 (make-string 1 (aref kv (1- (length kv))))))))
19908 (cond
19909 ((commandp org-speed-command)
19910 (setq this-command org-speed-command)
19911 (call-interactively org-speed-command))
19912 ((functionp org-speed-command)
19913 (funcall org-speed-command))
19914 ((and org-speed-command (listp org-speed-command))
19915 (eval org-speed-command))
19916 (t (let (org-use-speed-commands)
19917 (call-interactively 'org-self-insert-command)))))
19918 ((and
19919 (org-at-table-p)
19920 (progn
19921 ;; Check if we blank the field, and if that triggers align.
19922 (and (featurep 'org-table) org-table-auto-blank-field
19923 (memq last-command
19924 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19925 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19926 ;; Got extra space, this field does not determine
19927 ;; column width.
19928 (let (org-table-may-need-update) (org-table-blank-field))
19929 ;; No extra space, this field may determine column
19930 ;; width.
19931 (org-table-blank-field)))
19933 (eq N 1)
19934 (looking-at "[^|\n]* \\( \\)|"))
19935 ;; There is room for insertion without re-aligning the table.
19936 (delete-region (match-beginning 1) (match-end 1))
19937 (self-insert-command N))
19939 (setq org-table-may-need-update t)
19940 (self-insert-command N)
19941 (org-fix-tags-on-the-fly)
19942 (when org-self-insert-cluster-for-undo
19943 (if (not (eq last-command 'org-self-insert-command))
19944 (setq org-self-insert-command-undo-counter 1)
19945 (if (>= org-self-insert-command-undo-counter 20)
19946 (setq org-self-insert-command-undo-counter 1)
19947 (and (> org-self-insert-command-undo-counter 0)
19948 buffer-undo-list (listp buffer-undo-list)
19949 (not (cadr buffer-undo-list)) ; remove nil entry
19950 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19951 (setq org-self-insert-command-undo-counter
19952 (1+ org-self-insert-command-undo-counter))))))))
19954 (defun org-check-before-invisible-edit (kind)
19955 "Check is editing if kind KIND would be dangerous with invisible text around.
19956 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19957 ;; First, try to get out of here as quickly as possible, to reduce overhead
19958 (when (and org-catch-invisible-edits
19959 (or (not (boundp 'visible-mode)) (not visible-mode))
19960 (or (get-char-property (point) 'invisible)
19961 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19962 ;; OK, we need to take a closer look. Do not consider
19963 ;; invisibility obtained through text properties (e.g., link
19964 ;; fontification), as it cannot be toggled.
19965 (let* ((invisible-at-point
19966 (pcase (get-char-property-and-overlay (point) 'invisible)
19967 (`(,_ . ,(and (pred overlayp) o)) o)))
19968 ;; Assume that point cannot land in the middle of an
19969 ;; overlay, or between two overlays.
19970 (invisible-before-point
19971 (and (not invisible-at-point)
19972 (not (bobp))
19973 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19974 (`(,_ . ,(and (pred overlayp) o)) o))))
19975 (border-and-ok-direction
19977 ;; Check if we are acting predictably before invisible
19978 ;; text.
19979 (and invisible-at-point
19980 (memq kind '(insert delete-backward)))
19981 ;; Check if we are acting predictably after invisible text
19982 ;; This works not well, and I have turned it off. It seems
19983 ;; better to always show and stop after invisible text.
19984 ;; (and (not invisible-at-point) invisible-before-point
19985 ;; (memq kind '(insert delete)))
19987 (when (or invisible-at-point invisible-before-point)
19988 (when (eq org-catch-invisible-edits 'error)
19989 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19990 (if (and org-custom-properties-overlays
19991 (y-or-n-p "Display invisible properties in this buffer? "))
19992 (org-toggle-custom-properties-visibility)
19993 ;; Make the area visible
19994 (save-excursion
19995 (when invisible-before-point
19996 (goto-char
19997 (previous-single-char-property-change (point) 'invisible)))
19998 ;; Remove whatever overlay is currently making yet-to-be
19999 ;; edited text invisible. Also remove nested invisibility
20000 ;; related overlays.
20001 (delete-overlay (or invisible-at-point invisible-before-point))
20002 (let ((origin (if invisible-at-point (point) (1- (point)))))
20003 (while (pcase (get-char-property-and-overlay origin 'invisible)
20004 (`(,_ . ,(and (pred overlayp) o))
20005 (delete-overlay o)
20006 t)))))
20007 (cond
20008 ((eq org-catch-invisible-edits 'show)
20009 ;; That's it, we do the edit after showing
20010 (message
20011 "Unfolding invisible region around point before editing")
20012 (sit-for 1))
20013 ((and (eq org-catch-invisible-edits 'smart)
20014 border-and-ok-direction)
20015 (message "Unfolding invisible region around point before editing"))
20017 ;; Don't do the edit, make the user repeat it in full visibility
20018 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20020 (defun org-fix-tags-on-the-fly ()
20021 "Align tags in headline at point.
20022 Unlike to `org-set-tags', it ignores region and sorting."
20023 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20024 (org-at-heading-p))
20025 (let ((org-ignore-region t)
20026 (org-tags-sort-function nil))
20027 (org-set-tags nil t))))
20029 (defun org-delete-backward-char (N)
20030 "Like `delete-backward-char', insert whitespace at field end in tables.
20031 When deleting backwards, in tables this function will insert whitespace in
20032 front of the next \"|\" separator, to keep the table aligned. The table will
20033 still be marked for re-alignment if the field did fill the entire column,
20034 because, in this case the deletion might narrow the column."
20035 (interactive "p")
20036 (save-match-data
20037 (org-check-before-invisible-edit 'delete-backward)
20038 (if (and (org-at-table-p)
20039 (eq N 1)
20040 (string-match "|" (buffer-substring (point-at-bol) (point)))
20041 (looking-at ".*?|"))
20042 (let ((pos (point))
20043 (noalign (looking-at "[^|\n\r]* |"))
20044 (c org-table-may-need-update))
20045 (backward-delete-char N)
20046 (unless overwrite-mode
20047 (skip-chars-forward "^|")
20048 (insert " ")
20049 (goto-char (1- pos)))
20050 ;; noalign: if there were two spaces at the end, this field
20051 ;; does not determine the width of the column.
20052 (when noalign (setq org-table-may-need-update c)))
20053 (backward-delete-char N)
20054 (org-fix-tags-on-the-fly))))
20056 (defun org-delete-char (N)
20057 "Like `delete-char', but insert whitespace at field end in tables.
20058 When deleting characters, in tables this function will insert whitespace in
20059 front of the next \"|\" separator, to keep the table aligned. The table will
20060 still be marked for re-alignment if the field did fill the entire column,
20061 because, in this case the deletion might narrow the column."
20062 (interactive "p")
20063 (save-match-data
20064 (org-check-before-invisible-edit 'delete)
20065 (if (and (org-at-table-p)
20066 (not (bolp))
20067 (not (= (char-after) ?|))
20068 (eq N 1))
20069 (if (looking-at ".*?|")
20070 (let ((pos (point))
20071 (noalign (looking-at "[^|\n\r]* |"))
20072 (c org-table-may-need-update))
20073 (replace-match
20074 (concat (substring (match-string 0) 1 -1) " |") nil t)
20075 (goto-char pos)
20076 ;; noalign: if there were two spaces at the end, this field
20077 ;; does not determine the width of the column.
20078 (when noalign (setq org-table-may-need-update c)))
20079 (delete-char N))
20080 (delete-char N)
20081 (org-fix-tags-on-the-fly))))
20083 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20084 (put 'org-self-insert-command 'delete-selection
20085 (lambda ()
20086 (not (run-hook-with-args-until-success
20087 'self-insert-uses-region-functions))))
20088 (put 'orgtbl-self-insert-command 'delete-selection
20089 (lambda ()
20090 (not (run-hook-with-args-until-success
20091 'self-insert-uses-region-functions))))
20092 (put 'org-delete-char 'delete-selection 'supersede)
20093 (put 'org-delete-backward-char 'delete-selection 'supersede)
20094 (put 'org-yank 'delete-selection 'yank)
20096 ;; Make `flyspell-mode' delay after some commands
20097 (put 'org-self-insert-command 'flyspell-delayed t)
20098 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20099 (put 'org-delete-char 'flyspell-delayed t)
20100 (put 'org-delete-backward-char 'flyspell-delayed t)
20102 ;; Make pabbrev-mode expand after Org mode commands
20103 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20104 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20106 (defun org-remap (map &rest commands)
20107 "In MAP, remap the functions given in COMMANDS.
20108 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20109 (let (new old)
20110 (while commands
20111 (setq old (pop commands) new (pop commands))
20112 (org-defkey map (vector 'remap old) new))))
20114 (defun org-transpose-words ()
20115 "Transpose words for Org.
20116 This uses the `org-mode-transpose-word-syntax-table' syntax
20117 table, which interprets characters in `org-emphasis-alist' as
20118 word constituents."
20119 (interactive)
20120 (with-syntax-table org-mode-transpose-word-syntax-table
20121 (call-interactively 'transpose-words)))
20122 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20124 (when (eq org-enable-table-editor 'optimized)
20125 ;; If the user wants maximum table support, we need to hijack
20126 ;; some standard editing functions
20127 (org-remap org-mode-map
20128 'self-insert-command 'org-self-insert-command
20129 'delete-char 'org-delete-char
20130 'delete-backward-char 'org-delete-backward-char)
20131 (org-defkey org-mode-map "|" 'org-force-self-insert))
20133 (defvar org-ctrl-c-ctrl-c-hook nil
20134 "Hook for functions attaching themselves to `C-c C-c'.
20136 This can be used to add additional functionality to the C-c C-c
20137 key which executes context-dependent commands. This hook is run
20138 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20139 run after the last test.
20141 Each function will be called with no arguments. The function
20142 must check if the context is appropriate for it to act. If yes,
20143 it should do its thing and then return a non-nil value. If the
20144 context is wrong, just do nothing and return nil.")
20146 (defvar org-ctrl-c-ctrl-c-final-hook nil
20147 "Hook for functions attaching themselves to `C-c C-c'.
20149 This can be used to add additional functionality to the C-c C-c
20150 key which executes context-dependent commands. This hook is run
20151 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20152 before the first test.
20154 Each function will be called with no arguments. The function
20155 must check if the context is appropriate for it to act. If yes,
20156 it should do its thing and then return a non-nil value. If the
20157 context is wrong, just do nothing and return nil.")
20159 (defvar org-tab-first-hook nil
20160 "Hook for functions to attach themselves to TAB.
20161 See `org-ctrl-c-ctrl-c-hook' for more information.
20162 This hook runs as the first action when TAB is pressed, even before
20163 `org-cycle' messes around with the `outline-regexp' to cater for
20164 inline tasks and plain list item folding.
20165 If any function in this hook returns t, any other actions that
20166 would have been caused by TAB (such as table field motion or visibility
20167 cycling) will not occur.")
20169 (defvar org-tab-after-check-for-table-hook nil
20170 "Hook for functions to attach themselves to TAB.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.
20172 This hook runs after it has been established that the cursor is not in a
20173 table, but before checking if the cursor is in a headline or if global cycling
20174 should be done.
20175 If any function in this hook returns t, not other actions like visibility
20176 cycling will be done.")
20178 (defvar org-tab-after-check-for-cycling-hook nil
20179 "Hook for functions to attach themselves to TAB.
20180 See `org-ctrl-c-ctrl-c-hook' for more information.
20181 This hook runs after it has been established that not table field motion and
20182 not visibility should be done because of current context. This is probably
20183 the place where a package like yasnippets can hook in.")
20185 (defvar org-tab-before-tab-emulation-hook nil
20186 "Hook for functions to attach themselves to TAB.
20187 See `org-ctrl-c-ctrl-c-hook' for more information.
20188 This hook runs after every other options for TAB have been exhausted, but
20189 before indentation and \t insertion takes place.")
20191 (defvar org-metaleft-hook nil
20192 "Hook for functions attaching themselves to `M-left'.
20193 See `org-ctrl-c-ctrl-c-hook' for more information.")
20194 (defvar org-metaright-hook nil
20195 "Hook for functions attaching themselves to `M-right'.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20197 (defvar org-metaup-hook nil
20198 "Hook for functions attaching themselves to `M-up'.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-metadown-hook nil
20201 "Hook for functions attaching themselves to `M-down'.
20202 See `org-ctrl-c-ctrl-c-hook' for more information.")
20203 (defvar org-shiftmetaleft-hook nil
20204 "Hook for functions attaching themselves to `M-S-left'.
20205 See `org-ctrl-c-ctrl-c-hook' for more information.")
20206 (defvar org-shiftmetaright-hook nil
20207 "Hook for functions attaching themselves to `M-S-right'.
20208 See `org-ctrl-c-ctrl-c-hook' for more information.")
20209 (defvar org-shiftmetaup-hook nil
20210 "Hook for functions attaching themselves to `M-S-up'.
20211 See `org-ctrl-c-ctrl-c-hook' for more information.")
20212 (defvar org-shiftmetadown-hook nil
20213 "Hook for functions attaching themselves to `M-S-down'.
20214 See `org-ctrl-c-ctrl-c-hook' for more information.")
20215 (defvar org-metareturn-hook nil
20216 "Hook for functions attaching themselves to `M-RET'.
20217 See `org-ctrl-c-ctrl-c-hook' for more information.")
20218 (defvar org-shiftup-hook nil
20219 "Hook for functions attaching themselves to `S-up'.
20220 See `org-ctrl-c-ctrl-c-hook' for more information.")
20221 (defvar org-shiftup-final-hook nil
20222 "Hook for functions attaching themselves to `S-up'.
20223 This one runs after all other options except shift-select have been excluded.
20224 See `org-ctrl-c-ctrl-c-hook' for more information.")
20225 (defvar org-shiftdown-hook nil
20226 "Hook for functions attaching themselves to `S-down'.
20227 See `org-ctrl-c-ctrl-c-hook' for more information.")
20228 (defvar org-shiftdown-final-hook nil
20229 "Hook for functions attaching themselves to `S-down'.
20230 This one runs after all other options except shift-select have been excluded.
20231 See `org-ctrl-c-ctrl-c-hook' for more information.")
20232 (defvar org-shiftleft-hook nil
20233 "Hook for functions attaching themselves to `S-left'.
20234 See `org-ctrl-c-ctrl-c-hook' for more information.")
20235 (defvar org-shiftleft-final-hook nil
20236 "Hook for functions attaching themselves to `S-left'.
20237 This one runs after all other options except shift-select have been excluded.
20238 See `org-ctrl-c-ctrl-c-hook' for more information.")
20239 (defvar org-shiftright-hook nil
20240 "Hook for functions attaching themselves to `S-right'.
20241 See `org-ctrl-c-ctrl-c-hook' for more information.")
20242 (defvar org-shiftright-final-hook nil
20243 "Hook for functions attaching themselves to `S-right'.
20244 This one runs after all other options except shift-select have been excluded.
20245 See `org-ctrl-c-ctrl-c-hook' for more information.")
20247 (defun org-modifier-cursor-error ()
20248 "Throw an error, a modified cursor command was applied in wrong context."
20249 (user-error "This command is active in special context like tables, headlines or items"))
20251 (defun org-shiftselect-error ()
20252 "Throw an error because Shift-Cursor command was applied in wrong context."
20253 (if (and (boundp 'shift-select-mode) shift-select-mode)
20254 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20255 (user-error "This command works only in special context like headlines or timestamps")))
20257 (defun org-call-for-shift-select (cmd)
20258 (let ((this-command-keys-shift-translated t))
20259 (call-interactively cmd)))
20261 (defun org-shifttab (&optional arg)
20262 "Global visibility cycling or move to previous table field.
20263 Call `org-table-previous-field' within a table.
20264 When ARG is nil, cycle globally through visibility states.
20265 When ARG is a numeric prefix, show contents of this level."
20266 (interactive "P")
20267 (cond
20268 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20269 ((integerp arg)
20270 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20271 (message "Content view to level: %d" arg)
20272 (org-content (prefix-numeric-value arg2))
20273 (org-cycle-show-empty-lines t)
20274 (setq org-cycle-global-status 'overview)))
20275 (t (call-interactively 'org-global-cycle))))
20277 (defun org-shiftmetaleft ()
20278 "Promote subtree or delete table column.
20279 Calls `org-promote-subtree', `org-outdent-item-tree', or
20280 `org-table-delete-column', depending on context. See the
20281 individual commands for more information."
20282 (interactive)
20283 (cond
20284 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20285 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20286 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20287 ((if (not (org-region-active-p)) (org-at-item-p)
20288 (save-excursion (goto-char (region-beginning))
20289 (org-at-item-p)))
20290 (call-interactively 'org-outdent-item-tree))
20291 (t (org-modifier-cursor-error))))
20293 (defun org-shiftmetaright ()
20294 "Demote subtree or insert table column.
20295 Calls `org-demote-subtree', `org-indent-item-tree', or
20296 `org-table-insert-column', depending on context. See the
20297 individual commands for more information."
20298 (interactive)
20299 (cond
20300 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20301 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20302 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20303 ((if (not (org-region-active-p)) (org-at-item-p)
20304 (save-excursion (goto-char (region-beginning))
20305 (org-at-item-p)))
20306 (call-interactively 'org-indent-item-tree))
20307 (t (org-modifier-cursor-error))))
20309 (defun org-shiftmetaup (&optional _arg)
20310 "Drag the line at point up.
20311 In a table, kill the current row.
20312 On a clock timestamp, update the value of the timestamp like `S-<up>'
20313 but also adjust the previous clocked item in the clock history.
20314 Everywhere else, drag the line at point up."
20315 (interactive "P")
20316 (cond
20317 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20318 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20319 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20320 (call-interactively 'org-timestamp-up)))
20321 (t (call-interactively 'org-drag-line-backward))))
20323 (defun org-shiftmetadown (&optional _arg)
20324 "Drag the line at point down.
20325 In a table, insert an empty row at the current line.
20326 On a clock timestamp, update the value of the timestamp like `S-<down>'
20327 but also adjust the previous clocked item in the clock history.
20328 Everywhere else, drag the line at point down."
20329 (interactive "P")
20330 (cond
20331 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20332 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20333 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20334 (call-interactively 'org-timestamp-down)))
20335 (t (call-interactively 'org-drag-line-forward))))
20337 (defsubst org-hidden-tree-error ()
20338 (user-error
20339 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20341 (defun org-metaleft (&optional _arg)
20342 "Promote heading, list item at point or move table column left.
20344 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20345 depending on context. With no specific context, calls the Emacs
20346 default `backward-word'. See the individual commands for more
20347 information.
20349 This function runs the hook `org-metaleft-hook' as a first step,
20350 and returns at first non-nil value."
20351 (interactive "P")
20352 (cond
20353 ((run-hook-with-args-until-success 'org-metaleft-hook))
20354 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20355 ((org-with-limited-levels
20356 (or (org-at-heading-p)
20357 (and (org-region-active-p)
20358 (save-excursion
20359 (goto-char (region-beginning))
20360 (org-at-heading-p)))))
20361 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20362 (call-interactively 'org-do-promote))
20363 ;; At an inline task.
20364 ((org-at-heading-p)
20365 (call-interactively 'org-inlinetask-promote))
20366 ((or (org-at-item-p)
20367 (and (org-region-active-p)
20368 (save-excursion
20369 (goto-char (region-beginning))
20370 (org-at-item-p))))
20371 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20372 (call-interactively 'org-outdent-item))
20373 (t (call-interactively 'backward-word))))
20375 (defun org-metaright (&optional _arg)
20376 "Demote heading, list item at point or move table column right.
20378 In front of a drawer or a block keyword, indent it correctly.
20380 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20381 `org-indent-drawer' or `org-indent-block' depending on context.
20382 With no specific context, calls the Emacs default `forward-word'.
20383 See the individual commands for more information.
20385 This function runs the hook `org-metaright-hook' as a first step,
20386 and returns at first non-nil value."
20387 (interactive "P")
20388 (cond
20389 ((run-hook-with-args-until-success 'org-metaright-hook))
20390 ((org-at-table-p) (call-interactively 'org-table-move-column))
20391 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20392 ((org-at-block-p) (call-interactively 'org-indent-block))
20393 ((org-with-limited-levels
20394 (or (org-at-heading-p)
20395 (and (org-region-active-p)
20396 (save-excursion
20397 (goto-char (region-beginning))
20398 (org-at-heading-p)))))
20399 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20400 (call-interactively 'org-do-demote))
20401 ;; At an inline task.
20402 ((org-at-heading-p)
20403 (call-interactively 'org-inlinetask-demote))
20404 ((or (org-at-item-p)
20405 (and (org-region-active-p)
20406 (save-excursion
20407 (goto-char (region-beginning))
20408 (org-at-item-p))))
20409 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20410 (call-interactively 'org-indent-item))
20411 (t (call-interactively 'forward-word))))
20413 (defun org-check-for-hidden (what)
20414 "Check if there are hidden headlines/items in the current visual line.
20415 WHAT can be either `headlines' or `items'. If the current line is
20416 an outline or item heading and it has a folded subtree below it,
20417 this function returns t, nil otherwise."
20418 (let ((re (cond
20419 ((eq what 'headlines) org-outline-regexp-bol)
20420 ((eq what 'items) (org-item-beginning-re))
20421 (t (error "This should not happen"))))
20422 beg end)
20423 (save-excursion
20424 (catch 'exit
20425 (unless (org-region-active-p)
20426 (setq beg (point-at-bol))
20427 (beginning-of-line 2)
20428 (while (and (not (eobp)) ;; this is like `next-line'
20429 (get-char-property (1- (point)) 'invisible))
20430 (beginning-of-line 2))
20431 (setq end (point))
20432 (goto-char beg)
20433 (goto-char (point-at-eol))
20434 (setq end (max end (point)))
20435 (while (re-search-forward re end t)
20436 (when (get-char-property (match-beginning 0) 'invisible)
20437 (throw 'exit t))))
20438 nil))))
20440 (defun org-metaup (&optional _arg)
20441 "Move subtree up or move table row up.
20442 Calls `org-move-subtree-up' or `org-table-move-row' or
20443 `org-move-item-up', depending on context. See the individual commands
20444 for more information."
20445 (interactive "P")
20446 (cond
20447 ((run-hook-with-args-until-success 'org-metaup-hook))
20448 ((org-region-active-p)
20449 (let* ((a (min (region-beginning) (region-end)))
20450 (b (1- (max (region-beginning) (region-end))))
20451 (c (save-excursion (goto-char a)
20452 (move-beginning-of-line 0)))
20453 (d (save-excursion (goto-char a)
20454 (move-end-of-line 0) (point))))
20455 (transpose-regions a b c d)
20456 (goto-char c)))
20457 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20458 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20459 ((org-at-item-p) (call-interactively 'org-move-item-up))
20460 (t (org-drag-element-backward))))
20462 (defun org-metadown (&optional _arg)
20463 "Move subtree down or move table row down.
20464 Calls `org-move-subtree-down' or `org-table-move-row' or
20465 `org-move-item-down', depending on context. See the individual
20466 commands for more information."
20467 (interactive "P")
20468 (cond
20469 ((run-hook-with-args-until-success 'org-metadown-hook))
20470 ((org-region-active-p)
20471 (let* ((a (min (region-beginning) (region-end)))
20472 (b (max (region-beginning) (region-end)))
20473 (c (save-excursion (goto-char b)
20474 (move-beginning-of-line 1)))
20475 (d (save-excursion (goto-char b)
20476 (move-end-of-line 1) (1+ (point)))))
20477 (transpose-regions a b c d)
20478 (goto-char d)))
20479 ((org-at-table-p) (call-interactively 'org-table-move-row))
20480 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20481 ((org-at-item-p) (call-interactively 'org-move-item-down))
20482 (t (org-drag-element-forward))))
20484 (defun org-shiftup (&optional arg)
20485 "Increase item in timestamp or increase priority of current headline.
20486 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20487 depending on context. See the individual commands for more information."
20488 (interactive "P")
20489 (cond
20490 ((run-hook-with-args-until-success 'org-shiftup-hook))
20491 ((and org-support-shift-select (org-region-active-p))
20492 (org-call-for-shift-select 'previous-line))
20493 ((org-at-timestamp-p 'lax)
20494 (call-interactively (if org-edit-timestamp-down-means-later
20495 'org-timestamp-down 'org-timestamp-up)))
20496 ((and (not (eq org-support-shift-select 'always))
20497 org-enable-priority-commands
20498 (org-at-heading-p))
20499 (call-interactively 'org-priority-up))
20500 ((and (not org-support-shift-select) (org-at-item-p))
20501 (call-interactively 'org-previous-item))
20502 ((org-clocktable-try-shift 'up arg))
20503 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20504 (org-support-shift-select
20505 (org-call-for-shift-select 'previous-line))
20506 (t (org-shiftselect-error))))
20508 (defun org-shiftdown (&optional arg)
20509 "Decrease item in timestamp or decrease priority of current headline.
20510 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20511 depending on context. See the individual commands for more information."
20512 (interactive "P")
20513 (cond
20514 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20515 ((and org-support-shift-select (org-region-active-p))
20516 (org-call-for-shift-select 'next-line))
20517 ((org-at-timestamp-p 'lax)
20518 (call-interactively (if org-edit-timestamp-down-means-later
20519 'org-timestamp-up 'org-timestamp-down)))
20520 ((and (not (eq org-support-shift-select 'always))
20521 org-enable-priority-commands
20522 (org-at-heading-p))
20523 (call-interactively 'org-priority-down))
20524 ((and (not org-support-shift-select) (org-at-item-p))
20525 (call-interactively 'org-next-item))
20526 ((org-clocktable-try-shift 'down arg))
20527 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20528 (org-support-shift-select
20529 (org-call-for-shift-select 'next-line))
20530 (t (org-shiftselect-error))))
20532 (defun org-shiftright (&optional arg)
20533 "Cycle the thing at point or in the current line, depending on context.
20534 Depending on context, this does one of the following:
20536 - switch a timestamp at point one day into the future
20537 - on a headline, switch to the next TODO keyword.
20538 - on an item, switch entire list to the next bullet type
20539 - on a property line, switch to the next allowed value
20540 - on a clocktable definition line, move time block into the future"
20541 (interactive "P")
20542 (cond
20543 ((run-hook-with-args-until-success 'org-shiftright-hook))
20544 ((and org-support-shift-select (org-region-active-p))
20545 (org-call-for-shift-select 'forward-char))
20546 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20547 ((and (not (eq org-support-shift-select 'always))
20548 (org-at-heading-p))
20549 (let ((org-inhibit-logging
20550 (not org-treat-S-cursor-todo-selection-as-state-change))
20551 (org-inhibit-blocking
20552 (not org-treat-S-cursor-todo-selection-as-state-change)))
20553 (org-call-with-arg 'org-todo 'right)))
20554 ((or (and org-support-shift-select
20555 (not (eq org-support-shift-select 'always))
20556 (org-at-item-bullet-p))
20557 (and (not org-support-shift-select) (org-at-item-p)))
20558 (org-call-with-arg 'org-cycle-list-bullet nil))
20559 ((and (not (eq org-support-shift-select 'always))
20560 (org-at-property-p))
20561 (call-interactively 'org-property-next-allowed-value))
20562 ((org-clocktable-try-shift 'right arg))
20563 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20564 (org-support-shift-select
20565 (org-call-for-shift-select 'forward-char))
20566 (t (org-shiftselect-error))))
20568 (defun org-shiftleft (&optional arg)
20569 "Cycle the thing at point or in the current line, depending on context.
20570 Depending on context, this does one of the following:
20572 - switch a timestamp at point one day into the past
20573 - on a headline, switch to the previous TODO keyword.
20574 - on an item, switch entire list to the previous bullet type
20575 - on a property line, switch to the previous allowed value
20576 - on a clocktable definition line, move time block into the past"
20577 (interactive "P")
20578 (cond
20579 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20580 ((and org-support-shift-select (org-region-active-p))
20581 (org-call-for-shift-select 'backward-char))
20582 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20583 ((and (not (eq org-support-shift-select 'always))
20584 (org-at-heading-p))
20585 (let ((org-inhibit-logging
20586 (not org-treat-S-cursor-todo-selection-as-state-change))
20587 (org-inhibit-blocking
20588 (not org-treat-S-cursor-todo-selection-as-state-change)))
20589 (org-call-with-arg 'org-todo 'left)))
20590 ((or (and org-support-shift-select
20591 (not (eq org-support-shift-select 'always))
20592 (org-at-item-bullet-p))
20593 (and (not org-support-shift-select) (org-at-item-p)))
20594 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20595 ((and (not (eq org-support-shift-select 'always))
20596 (org-at-property-p))
20597 (call-interactively 'org-property-previous-allowed-value))
20598 ((org-clocktable-try-shift 'left arg))
20599 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20600 (org-support-shift-select
20601 (org-call-for-shift-select 'backward-char))
20602 (t (org-shiftselect-error))))
20604 (defun org-shiftcontrolright ()
20605 "Switch to next TODO set."
20606 (interactive)
20607 (cond
20608 ((and org-support-shift-select (org-region-active-p))
20609 (org-call-for-shift-select 'forward-word))
20610 ((and (not (eq org-support-shift-select 'always))
20611 (org-at-heading-p))
20612 (org-call-with-arg 'org-todo 'nextset))
20613 (org-support-shift-select
20614 (org-call-for-shift-select 'forward-word))
20615 (t (org-shiftselect-error))))
20617 (defun org-shiftcontrolleft ()
20618 "Switch to previous TODO set."
20619 (interactive)
20620 (cond
20621 ((and org-support-shift-select (org-region-active-p))
20622 (org-call-for-shift-select 'backward-word))
20623 ((and (not (eq org-support-shift-select 'always))
20624 (org-at-heading-p))
20625 (org-call-with-arg 'org-todo 'previousset))
20626 (org-support-shift-select
20627 (org-call-for-shift-select 'backward-word))
20628 (t (org-shiftselect-error))))
20630 (defun org-shiftcontrolup (&optional n)
20631 "Change timestamps synchronously up in CLOCK log lines.
20632 Optional argument N tells to change by that many units."
20633 (interactive "P")
20634 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20635 (let (org-support-shift-select)
20636 (org-clock-timestamps-up n))
20637 (user-error "Not at a clock log")))
20639 (defun org-shiftcontroldown (&optional n)
20640 "Change timestamps synchronously down in CLOCK log lines.
20641 Optional argument N tells to change by that many units."
20642 (interactive "P")
20643 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20644 (let (org-support-shift-select)
20645 (org-clock-timestamps-down n))
20646 (user-error "Not at a clock log")))
20648 (defun org-increase-number-at-point (&optional inc)
20649 "Increment the number at point.
20650 With an optional prefix numeric argument INC, increment using
20651 this numeric value."
20652 (interactive "p")
20653 (if (not (number-at-point))
20654 (user-error "Not on a number")
20655 (unless inc (setq inc 1))
20656 (let ((pos (point))
20657 (beg (skip-chars-backward "-+^/*0-9eE."))
20658 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20659 (setq nap (buffer-substring-no-properties
20660 (+ pos beg) (+ pos beg end)))
20661 (delete-region (+ pos beg) (+ pos beg end))
20662 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20663 (when (org-at-table-p)
20664 (org-table-align)
20665 (org-table-end-of-field 1))))
20667 (defun org-decrease-number-at-point (&optional inc)
20668 "Decrement the number at point.
20669 With an optional prefix numeric argument INC, decrement using
20670 this numeric value."
20671 (interactive "p")
20672 (org-increase-number-at-point (- (or inc 1))))
20674 (defun org-ctrl-c-ret ()
20675 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20676 (interactive)
20677 (cond
20678 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20679 (t (call-interactively 'org-insert-heading))))
20681 (defun org-find-visible ()
20682 (let ((s (point)))
20683 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20684 (get-char-property s 'invisible)))
20686 (defun org-find-invisible ()
20687 (let ((s (point)))
20688 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20689 (not (get-char-property s 'invisible))))
20692 (defun org-copy-visible (beg end)
20693 "Copy the visible parts of the region."
20694 (interactive "r")
20695 (let (snippets s)
20696 (save-excursion
20697 (save-restriction
20698 (narrow-to-region beg end)
20699 (setq s (goto-char (point-min)))
20700 (while (not (= (point) (point-max)))
20701 (goto-char (org-find-invisible))
20702 (push (buffer-substring s (point)) snippets)
20703 (setq s (goto-char (org-find-visible))))))
20704 (kill-new (apply 'concat (nreverse snippets)))))
20706 (defun org-copy-special ()
20707 "Copy region in table or copy current subtree.
20708 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20709 context. See the individual commands for more information."
20710 (interactive)
20711 (call-interactively
20712 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20714 (defun org-cut-special ()
20715 "Cut region in table or cut current subtree.
20716 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20717 context. See the individual commands for more information."
20718 (interactive)
20719 (call-interactively
20720 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20722 (defun org-paste-special (arg)
20723 "Paste rectangular region into table, or past subtree relative to level.
20724 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20725 See the individual commands for more information."
20726 (interactive "P")
20727 (if (org-at-table-p)
20728 (org-table-paste-rectangle)
20729 (org-paste-subtree arg)))
20731 (defun org-edit-special (&optional arg)
20732 "Call a special editor for the element at point.
20733 When at a table, call the formula editor with `org-table-edit-formulas'.
20734 When in a source code block, call `org-edit-src-code'.
20735 When in a fixed-width region, call `org-edit-fixed-width-region'.
20736 When in an export block, call `org-edit-export-block'.
20737 When in a LaTeX environment, call `org-edit-latex-environment'.
20738 When at an #+INCLUDE keyword, visit the included file.
20739 When at a footnote reference, call `org-edit-footnote-reference'
20740 On a link, call `ffap' to visit the link at point.
20741 Otherwise, return a user error."
20742 (interactive "P")
20743 (let ((element (org-element-at-point)))
20744 (barf-if-buffer-read-only)
20745 (pcase (org-element-type element)
20746 (`src-block
20747 (if (not arg) (org-edit-src-code)
20748 (let* ((info (org-babel-get-src-block-info))
20749 (lang (nth 0 info))
20750 (params (nth 2 info))
20751 (session (cdr (assq :session params))))
20752 (if (not session) (org-edit-src-code)
20753 ;; At a src-block with a session and function called with
20754 ;; an ARG: switch to the buffer related to the inferior
20755 ;; process.
20756 (switch-to-buffer
20757 (funcall (intern (concat "org-babel-prep-session:" lang))
20758 session params))))))
20759 (`keyword
20760 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20761 (org-open-link-from-string
20762 (format "[[%s]]"
20763 (expand-file-name
20764 (let ((value (org-element-property :value element)))
20765 (cond ((org-file-url-p value)
20766 (user-error "The file is specified as a URL, cannot be edited"))
20767 ((not (org-string-nw-p value))
20768 (user-error "No file to edit"))
20769 ((string-match "\\`\"\\(.*?\\)\"" value)
20770 (match-string 1 value))
20771 ((string-match "\\`[^ \t\"]\\S-*" value)
20772 (match-string 0 value))
20773 (t (user-error "No valid file specified")))))))
20774 (user-error "No special environment to edit here")))
20775 (`table
20776 (if (eq (org-element-property :type element) 'table.el)
20777 (org-edit-table.el)
20778 (call-interactively 'org-table-edit-formulas)))
20779 ;; Only Org tables contain `table-row' type elements.
20780 (`table-row (call-interactively 'org-table-edit-formulas))
20781 (`example-block (org-edit-src-code))
20782 (`export-block (org-edit-export-block))
20783 (`fixed-width (org-edit-fixed-width-region))
20784 (`latex-environment (org-edit-latex-environment))
20786 ;; No notable element at point. Though, we may be at a link or
20787 ;; a footnote reference, which are objects. Thus, scan deeper.
20788 (let ((context (org-element-context element)))
20789 (pcase (org-element-type context)
20790 (`footnote-reference (org-edit-footnote-reference))
20791 (`inline-src-block (org-edit-inline-src-code))
20792 (`link (call-interactively #'ffap))
20793 (_ (user-error "No special environment to edit here"))))))))
20795 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20796 (defun org-ctrl-c-ctrl-c (&optional arg)
20797 "Set tags in headline, or update according to changed information at point.
20799 This command does many different things, depending on context:
20801 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20802 this is what we do.
20804 - If the cursor is on a statistics cookie, update it.
20806 - If the cursor is in a headline, prompt for tags and insert them
20807 into the current line, aligned to `org-tags-column'. When called
20808 with prefix arg, realign all tags in the current buffer.
20810 - If the cursor is in one of the special #+KEYWORD lines, this
20811 triggers scanning the buffer for these lines and updating the
20812 information.
20814 - If the cursor is inside a table, realign the table. This command
20815 works even if the automatic table editor has been turned off.
20817 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20818 the entire table.
20820 - If the cursor is at a footnote reference or definition, jump to
20821 the corresponding definition or references, respectively.
20823 - If the cursor is a the beginning of a dynamic block, update it.
20825 - If the current buffer is a capture buffer, close note and file it.
20827 - If the cursor is on a <<<target>>>, update radio targets and
20828 corresponding links in this buffer.
20830 - If the cursor is on a numbered item in a plain list, renumber the
20831 ordered list.
20833 - If the cursor is on a checkbox, toggle it.
20835 - If the cursor is on a code block, evaluate it. The variable
20836 `org-confirm-babel-evaluate' can be used to control prompting
20837 before code block evaluation, by default every code block
20838 evaluation requires confirmation. Code block evaluation can be
20839 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20840 (interactive "P")
20841 (cond
20842 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20843 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20844 (org-remove-occur-highlights)
20845 (message "Temporary highlights/overlays removed from current buffer"))
20846 ((and (local-variable-p 'org-finish-function)
20847 (fboundp org-finish-function))
20848 (funcall org-finish-function))
20849 ((org-babel-hash-at-point))
20850 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20852 (let* ((context
20853 (org-element-lineage
20854 (org-element-context)
20855 ;; Limit to supported contexts.
20856 '(babel-call clock dynamic-block footnote-definition
20857 footnote-reference inline-babel-call inline-src-block
20858 inlinetask item keyword node-property paragraph
20859 plain-list property-drawer radio-target src-block
20860 statistics-cookie table table-cell table-row
20861 timestamp)
20863 (type (org-element-type context)))
20864 ;; For convenience: at the first line of a paragraph on the same
20865 ;; line as an item, apply function on that item instead.
20866 (when (eq type 'paragraph)
20867 (let ((parent (org-element-property :parent context)))
20868 (when (and (eq (org-element-type parent) 'item)
20869 (= (line-beginning-position)
20870 (org-element-property :begin parent)))
20871 (setq context parent)
20872 (setq type 'item))))
20873 ;; Act according to type of element or object at point.
20875 ;; Do nothing on a blank line, except if it is contained in
20876 ;; a src block. Hence, we first check if point is in such
20877 ;; a block and then if it is at a blank line.
20878 (pcase type
20879 ((or `inline-src-block `src-block)
20880 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20881 (org-babel-eval-wipe-error-buffer)
20882 (org-babel-execute-src-block
20883 current-prefix-arg (org-babel-get-src-block-info nil context))))
20884 ((guard (org-match-line "[ \t]*$"))
20885 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20886 (user-error
20887 (substitute-command-keys
20888 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20889 ((or `babel-call `inline-babel-call)
20890 (let ((info (org-babel-lob-get-info context)))
20891 (when info (org-babel-execute-src-block nil info))))
20892 (`clock (org-clock-update-time-maybe))
20893 (`dynamic-block
20894 (save-excursion
20895 (goto-char (org-element-property :post-affiliated context))
20896 (org-update-dblock)))
20897 (`footnote-definition
20898 (goto-char (org-element-property :post-affiliated context))
20899 (call-interactively 'org-footnote-action))
20900 (`footnote-reference (call-interactively #'org-footnote-action))
20901 ((or `headline `inlinetask)
20902 (save-excursion (goto-char (org-element-property :begin context))
20903 (call-interactively #'org-set-tags)))
20904 (`item
20905 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20906 ;; unconditionally, whereas `C-u' will toggle its presence.
20907 ;; Without a universal argument, if the item has a checkbox,
20908 ;; toggle it. Otherwise repair the list.
20909 (let* ((box (org-element-property :checkbox context))
20910 (struct (org-element-property :structure context))
20911 (old-struct (copy-tree struct))
20912 (parents (org-list-parents-alist struct))
20913 (prevs (org-list-prevs-alist struct))
20914 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20915 (org-list-set-checkbox
20916 (org-element-property :begin context) struct
20917 (cond ((equal arg '(16)) "[-]")
20918 ((and (not box) (equal arg '(4))) "[ ]")
20919 ((or (not box) (equal arg '(4))) nil)
20920 ((eq box 'on) "[ ]")
20921 (t "[X]")))
20922 ;; Mimic `org-list-write-struct' but with grabbing a return
20923 ;; value from `org-list-struct-fix-box'.
20924 (org-list-struct-fix-ind struct parents 2)
20925 (org-list-struct-fix-item-end struct)
20926 (org-list-struct-fix-bul struct prevs)
20927 (org-list-struct-fix-ind struct parents)
20928 (let ((block-item
20929 (org-list-struct-fix-box struct parents prevs orderedp)))
20930 (if (and box (equal struct old-struct))
20931 (if (equal arg '(16))
20932 (message "Checkboxes already reset")
20933 (user-error "Cannot toggle this checkbox: %s"
20934 (if (eq box 'on)
20935 "all subitems checked"
20936 "unchecked subitems")))
20937 (org-list-struct-apply-struct struct old-struct)
20938 (org-update-checkbox-count-maybe))
20939 (when block-item
20940 (message "Checkboxes were removed due to empty box at line %d"
20941 (org-current-line block-item))))))
20942 (`keyword
20943 (let ((org-inhibit-startup-visibility-stuff t)
20944 (org-startup-align-all-tables nil))
20945 (when (boundp 'org-table-coordinate-overlays)
20946 (mapc #'delete-overlay org-table-coordinate-overlays)
20947 (setq org-table-coordinate-overlays nil))
20948 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20949 (message "Local setup has been refreshed"))
20950 (`plain-list
20951 ;; At a plain list, with a double C-u argument, set
20952 ;; checkboxes of each item to "[-]", whereas a single one
20953 ;; will toggle their presence according to the state of the
20954 ;; first item in the list. Without an argument, repair the
20955 ;; list.
20956 (let* ((begin (org-element-property :contents-begin context))
20957 (beginm (move-marker (make-marker) begin))
20958 (struct (org-element-property :structure context))
20959 (old-struct (copy-tree struct))
20960 (first-box (save-excursion
20961 (goto-char begin)
20962 (looking-at org-list-full-item-re)
20963 (match-string-no-properties 3)))
20964 (new-box (cond ((equal arg '(16)) "[-]")
20965 ((equal arg '(4)) (unless first-box "[ ]"))
20966 ((equal first-box "[X]") "[ ]")
20967 (t "[X]"))))
20968 (cond
20969 (arg
20970 (dolist (pos
20971 (org-list-get-all-items
20972 begin struct (org-list-prevs-alist struct)))
20973 (org-list-set-checkbox pos struct new-box)))
20974 ((and first-box (eq (point) begin))
20975 ;; For convenience, when point is at bol on the first
20976 ;; item of the list and no argument is provided, simply
20977 ;; toggle checkbox of that item, if any.
20978 (org-list-set-checkbox begin struct new-box)))
20979 (org-list-write-struct
20980 struct (org-list-parents-alist struct) old-struct)
20981 (org-update-checkbox-count-maybe)
20982 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20983 ((or `property-drawer `node-property)
20984 (call-interactively #'org-property-action))
20985 (`radio-target
20986 (call-interactively #'org-update-radio-target-regexp))
20987 (`statistics-cookie
20988 (call-interactively #'org-update-statistics-cookies))
20989 ((or `table `table-cell `table-row)
20990 ;; At a table, recalculate every field and align it. Also
20991 ;; send the table if necessary. If the table has
20992 ;; a `table.el' type, just give up. At a table row or cell,
20993 ;; maybe recalculate line but always align table.
20994 (if (eq (org-element-property :type context) 'table.el)
20995 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20996 Use `\\[org-edit-special]' to edit table.el tables"))
20997 (let ((org-enable-table-editor t))
20998 (if (or (eq type 'table)
20999 ;; Check if point is at a TBLFM line.
21000 (and (eq type 'table-row)
21001 (= (point) (org-element-property :end context))))
21002 (save-excursion
21003 (if (org-at-TBLFM-p)
21004 (progn (require 'org-table)
21005 (org-table-calc-current-TBLFM))
21006 (goto-char (org-element-property :contents-begin context))
21007 (org-call-with-arg 'org-table-recalculate (or arg t))
21008 (orgtbl-send-table 'maybe)))
21009 (org-table-maybe-eval-formula)
21010 (cond (arg (call-interactively #'org-table-recalculate))
21011 ((org-table-maybe-recalculate-line))
21012 (t (org-table-align)))))))
21013 (`timestamp (org-timestamp-change 0 'day))
21014 ((and `nil (guard (org-at-heading-p)))
21015 ;; When point is on an unsupported object type, we can miss
21016 ;; the fact that it also is at a heading. Handle it here.
21017 (call-interactively #'org-set-tags))
21018 ((guard
21019 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21021 (user-error
21022 (substitute-command-keys
21023 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21025 (defun org-mode-restart ()
21026 (interactive)
21027 (let ((indent-status (bound-and-true-p org-indent-mode)))
21028 (funcall major-mode)
21029 (hack-local-variables)
21030 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21031 (org-indent-mode -1))
21032 (org-reset-file-cache))
21033 (message "%s restarted" major-mode))
21035 (defun org-kill-note-or-show-branches ()
21036 "Abort storing current note, or call `outline-show-branches'."
21037 (interactive)
21038 (if (not org-finish-function)
21039 (progn
21040 (outline-hide-subtree)
21041 (call-interactively 'outline-show-branches))
21042 (let ((org-note-abort t))
21043 (funcall org-finish-function))))
21045 (defun org-delete-indentation (&optional arg)
21046 "Join current line to previous and fix whitespace at join.
21048 If previous line is a headline add to headline title. Otherwise
21049 the function calls `delete-indentation'.
21051 With a non-nil optional argument, join it to the following one."
21052 (interactive "*P")
21053 (if (save-excursion
21054 (beginning-of-line (if arg 1 0))
21055 (let ((case-fold-search nil))
21056 (looking-at org-complex-heading-regexp)))
21057 ;; At headline.
21058 (let ((tags-column (when (match-beginning 5)
21059 (save-excursion (goto-char (match-beginning 5))
21060 (current-column))))
21061 (string (concat " " (progn (when arg (forward-line 1))
21062 (org-trim (delete-and-extract-region
21063 (line-beginning-position)
21064 (line-end-position)))))))
21065 (unless (bobp) (delete-region (point) (1- (point))))
21066 (goto-char (or (match-end 4)
21067 (match-beginning 5)
21068 (match-end 0)))
21069 (skip-chars-backward " \t")
21070 (save-excursion (insert string))
21071 ;; Adjust alignment of tags.
21072 (cond
21073 ((not tags-column)) ;no tags
21074 (org-auto-align-tags (org-set-tags nil t))
21075 (t (org--align-tags-here tags-column)))) ;preserve tags column
21076 (delete-indentation arg)))
21078 (defun org-open-line (n)
21079 "Insert a new row in tables, call `open-line' elsewhere.
21080 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21081 As a special case, when a document starts with a table, allow to
21082 call `open-line' on the very first character."
21083 (interactive "*p")
21084 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21085 (org-table-insert-row)
21086 (open-line n)))
21088 (defun org-return (&optional indent)
21089 "Goto next table row or insert a newline.
21091 Calls `org-table-next-row' or `newline', depending on context.
21093 When optional INDENT argument is non-nil, call
21094 `newline-and-indent' instead of `newline'.
21096 When `org-return-follows-link' is non-nil and point is on
21097 a timestamp or a link, call `org-open-at-point'. However, it
21098 will not happen if point is in a table or on a \"dead\"
21099 object (e.g., within a comment). In these case, you need to use
21100 `org-open-at-point' directly."
21101 (interactive)
21102 (let ((context (if org-return-follows-link (org-element-context)
21103 (org-element-at-point))))
21104 (cond
21105 ;; In a table, call `org-table-next-row'.
21106 ((or (and (eq (org-element-type context) 'table)
21107 (>= (point) (org-element-property :contents-begin context))
21108 (< (point) (org-element-property :contents-end context)))
21109 (org-element-lineage context '(table-row table-cell) t))
21110 (org-table-justify-field-maybe)
21111 (call-interactively #'org-table-next-row))
21112 ;; On a link or a timestamp, call `org-open-at-point' if
21113 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21114 ;; locations, e.g., in a comment, as `org-open-at-point'.
21115 ((and org-return-follows-link
21116 (or (org-in-regexp org-ts-regexp-both nil t)
21117 (org-in-regexp org-tsr-regexp-both nil t)
21118 (org-in-regexp org-any-link-re nil t)))
21119 (call-interactively #'org-open-at-point))
21120 ;; Insert newline in heading, but preserve tags.
21121 ((and (not (bolp))
21122 (save-excursion (beginning-of-line)
21123 (let ((case-fold-search nil))
21124 (looking-at org-complex-heading-regexp))))
21125 ;; At headline. Split line. However, if point is on keyword,
21126 ;; priority cookie or tags, do not break any of them: add
21127 ;; a newline after the headline instead.
21128 (let ((tags-column (and (match-beginning 5)
21129 (save-excursion (goto-char (match-beginning 5))
21130 (current-column))))
21131 (string
21132 (when (and (match-end 4) (org-point-in-group (point) 4))
21133 (delete-and-extract-region (point) (match-end 4)))))
21134 ;; Adjust tag alignment.
21135 (cond
21136 ((not (and tags-column string)))
21137 (org-auto-align-tags (org-set-tags nil t))
21138 (t (org--align-tags-here tags-column))) ;preserve tags column
21139 (end-of-line)
21140 (org-show-entry)
21141 (if indent (newline-and-indent) (newline))
21142 (when string (save-excursion (insert (org-trim string))))))
21143 ;; In a list, make sure indenting keeps trailing text within.
21144 ((and indent
21145 (not (eolp))
21146 (org-element-lineage context '(item)))
21147 (let ((trailing-data
21148 (delete-and-extract-region (point) (line-end-position))))
21149 (newline-and-indent)
21150 (save-excursion (insert trailing-data))))
21151 (t (if indent (newline-and-indent) (newline))))))
21153 (defun org-return-indent ()
21154 "Goto next table row or insert a newline and indent.
21155 Calls `org-table-next-row' or `newline-and-indent', depending on
21156 context. See the individual commands for more information."
21157 (interactive)
21158 (org-return t))
21160 (defun org-ctrl-c-star ()
21161 "Compute table, or change heading status of lines.
21162 Calls `org-table-recalculate' or `org-toggle-heading',
21163 depending on context."
21164 (interactive)
21165 (cond
21166 ((org-at-table-p)
21167 (call-interactively 'org-table-recalculate))
21169 ;; Convert all lines in region to list items
21170 (call-interactively 'org-toggle-heading))))
21172 (defun org-ctrl-c-minus ()
21173 "Insert separator line in table or modify bullet status of line.
21174 Also turns a plain line or a region of lines into list items.
21175 Calls `org-table-insert-hline', `org-toggle-item', or
21176 `org-cycle-list-bullet', depending on context."
21177 (interactive)
21178 (cond
21179 ((org-at-table-p)
21180 (call-interactively 'org-table-insert-hline))
21181 ((org-region-active-p)
21182 (call-interactively 'org-toggle-item))
21183 ((org-in-item-p)
21184 (call-interactively 'org-cycle-list-bullet))
21186 (call-interactively 'org-toggle-item))))
21188 (defun org-toggle-heading (&optional nstars)
21189 "Convert headings to normal text, or items or text to headings.
21190 If there is no active region, only convert the current line.
21192 With a `\\[universal-argument]' prefix, convert the whole list at
21193 point into heading.
21195 In a region:
21197 - If the first non blank line is a headline, remove the stars
21198 from all headlines in the region.
21200 - If it is a normal line, turn each and every normal line (i.e.,
21201 not an heading or an item) in the region into headings. If you
21202 want to convert only the first line of this region, use one
21203 universal prefix argument.
21205 - If it is a plain list item, turn all plain list items into headings.
21207 When converting a line into a heading, the number of stars is chosen
21208 such that the lines become children of the current entry. However,
21209 when a numeric prefix argument is given, its value determines the
21210 number of stars to add."
21211 (interactive "P")
21212 (let ((skip-blanks
21213 (function
21214 ;; Return beginning of first non-blank line, starting from
21215 ;; line at POS.
21216 (lambda (pos)
21217 (save-excursion
21218 (goto-char pos)
21219 (while (org-at-comment-p) (forward-line))
21220 (skip-chars-forward " \r\t\n")
21221 (point-at-bol)))))
21222 beg end toggled)
21223 ;; Determine boundaries of changes. If a universal prefix has
21224 ;; been given, put the list in a region. If region ends at a bol,
21225 ;; do not consider the last line to be in the region.
21227 (when (and current-prefix-arg (org-at-item-p))
21228 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21229 (org-mark-element))
21231 (if (org-region-active-p)
21232 (setq beg (funcall skip-blanks (region-beginning))
21233 end (copy-marker (save-excursion
21234 (goto-char (region-end))
21235 (if (bolp) (point) (point-at-eol)))))
21236 (setq beg (funcall skip-blanks (point-at-bol))
21237 end (copy-marker (point-at-eol))))
21238 ;; Ensure inline tasks don't count as headings.
21239 (org-with-limited-levels
21240 (save-excursion
21241 (goto-char beg)
21242 (cond
21243 ;; Case 1. Started at an heading: de-star headings.
21244 ((org-at-heading-p)
21245 (while (< (point) end)
21246 (when (org-at-heading-p t)
21247 (looking-at org-outline-regexp) (replace-match "")
21248 (setq toggled t))
21249 (forward-line)))
21250 ;; Case 2. Started at an item: change items into headlines.
21251 ;; One star will be added by `org-list-to-subtree'.
21252 ((org-at-item-p)
21253 (while (< (point) end)
21254 (when (org-at-item-p)
21255 ;; Pay attention to cases when region ends before list.
21256 (let* ((struct (org-list-struct))
21257 (list-end
21258 (min (org-list-get-bottom-point struct) (1+ end))))
21259 (save-restriction
21260 (narrow-to-region (point) list-end)
21261 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21262 (setq toggled t))
21263 (forward-line)))
21264 ;; Case 3. Started at normal text: make every line an heading,
21265 ;; skipping headlines and items.
21266 (t (let* ((stars
21267 (make-string
21268 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21269 (add-stars
21270 (cond (nstars "") ; stars from prefix only
21271 ((equal stars "") "*") ; before first heading
21272 (org-odd-levels-only "**") ; inside heading, odd
21273 (t "*"))) ; inside heading, oddeven
21274 (rpl (concat stars add-stars " "))
21275 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21276 (while (< (point) (if (equal nstars '(4)) lend end))
21277 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21278 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21279 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21280 (forward-line)))))))
21281 (unless toggled (message "Cannot toggle heading from here"))))
21283 (defun org-meta-return (&optional arg)
21284 "Insert a new heading or wrap a region in a table.
21285 Calls `org-insert-heading', `org-insert-item' or
21286 `org-table-wrap-region', depending on context. When called with
21287 an argument, unconditionally call `org-insert-heading'."
21288 (interactive "P")
21289 (org-check-before-invisible-edit 'insert)
21290 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21291 (call-interactively (cond (arg #'org-insert-heading)
21292 ((org-at-table-p) #'org-table-wrap-region)
21293 ((org-in-item-p) #'org-insert-item)
21294 (t #'org-insert-heading)))))
21296 ;;; Menu entries
21298 (defsubst org-in-subtree-not-table-p ()
21299 "Are we in a subtree and not in a table?"
21300 (and (not (org-before-first-heading-p))
21301 (not (org-at-table-p))))
21303 ;; Define the Org mode menus
21304 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21305 '("Tbl"
21306 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21307 ["Next Field" org-cycle (org-at-table-p)]
21308 ["Previous Field" org-shifttab (org-at-table-p)]
21309 ["Next Row" org-return (org-at-table-p)]
21310 "--"
21311 ["Blank Field" org-table-blank-field (org-at-table-p)]
21312 ["Edit Field" org-table-edit-field (org-at-table-p)]
21313 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21314 "--"
21315 ("Column"
21316 ["Move Column Left" org-metaleft (org-at-table-p)]
21317 ["Move Column Right" org-metaright (org-at-table-p)]
21318 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21319 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21320 ("Row"
21321 ["Move Row Up" org-metaup (org-at-table-p)]
21322 ["Move Row Down" org-metadown (org-at-table-p)]
21323 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21324 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21325 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21326 "--"
21327 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21328 ("Rectangle"
21329 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21330 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21331 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21332 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21333 "--"
21334 ("Calculate"
21335 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21336 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21337 ["Edit Formulas" org-edit-special (org-at-table-p)]
21338 "--"
21339 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21340 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21341 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21342 "--"
21343 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21344 "--"
21345 ["Sum Column/Rectangle" org-table-sum
21346 (or (org-at-table-p) (org-region-active-p))]
21347 ["Which Column?" org-table-current-column (org-at-table-p)])
21348 ["Debug Formulas"
21349 org-table-toggle-formula-debugger
21350 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21351 ["Show Col/Row Numbers"
21352 org-table-toggle-coordinate-overlays
21353 :style toggle
21354 :selected (bound-and-true-p org-table-overlay-coordinates)]
21355 "--"
21356 ["Create" org-table-create (and (not (org-at-table-p))
21357 org-enable-table-editor)]
21358 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21359 ["Import from File" org-table-import (not (org-at-table-p))]
21360 ["Export to File" org-table-export (org-at-table-p)]
21361 "--"
21362 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21363 "--"
21364 ("Plot"
21365 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21366 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21368 (easy-menu-define org-org-menu org-mode-map "Org menu"
21369 '("Org"
21370 ("Show/Hide"
21371 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21372 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21373 ["Sparse Tree..." org-sparse-tree t]
21374 ["Reveal Context" org-reveal t]
21375 ["Show All" outline-show-all t]
21376 "--"
21377 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21378 "--"
21379 ["New Heading" org-insert-heading t]
21380 ("Navigate Headings"
21381 ["Up" outline-up-heading t]
21382 ["Next" outline-next-visible-heading t]
21383 ["Previous" outline-previous-visible-heading t]
21384 ["Next Same Level" outline-forward-same-level t]
21385 ["Previous Same Level" outline-backward-same-level t]
21386 "--"
21387 ["Jump" org-goto t])
21388 ("Edit Structure"
21389 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21390 "--"
21391 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21392 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21393 "--"
21394 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21395 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21396 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21397 "--"
21398 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21399 "--"
21400 ["Copy visible text" org-copy-visible t]
21401 "--"
21402 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21403 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21404 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21405 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21406 "--"
21407 ["Sort Region/Children" org-sort t]
21408 "--"
21409 ["Convert to odd levels" org-convert-to-odd-levels t]
21410 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21411 ("Editing"
21412 ["Emphasis..." org-emphasize t]
21413 ["Edit Source Example" org-edit-special t]
21414 "--"
21415 ["Footnote new/jump" org-footnote-action t]
21416 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21417 ("Archive"
21418 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21419 "--"
21420 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21421 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21422 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21424 "--"
21425 ("Hyperlinks"
21426 ["Store Link (Global)" org-store-link t]
21427 ["Find existing link to here" org-occur-link-in-agenda-files t]
21428 ["Insert Link" org-insert-link t]
21429 ["Follow Link" org-open-at-point t]
21430 "--"
21431 ["Next link" org-next-link t]
21432 ["Previous link" org-previous-link t]
21433 "--"
21434 ["Descriptive Links"
21435 org-toggle-link-display
21436 :style radio
21437 :selected org-descriptive-links
21439 ["Literal Links"
21440 org-toggle-link-display
21441 :style radio
21442 :selected (not org-descriptive-links)])
21443 "--"
21444 ("TODO Lists"
21445 ["TODO/DONE/-" org-todo t]
21446 ("Select keyword"
21447 ["Next keyword" org-shiftright (org-at-heading-p)]
21448 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21449 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21450 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21451 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21452 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21453 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21454 "--"
21455 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21456 :selected org-enforce-todo-dependencies :style toggle :active t]
21457 "Settings for tree at point"
21458 ["Do Children sequentially" org-toggle-ordered-property :style radio
21459 :selected (org-entry-get nil "ORDERED")
21460 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21461 ["Do Children parallel" org-toggle-ordered-property :style radio
21462 :selected (not (org-entry-get nil "ORDERED"))
21463 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21464 "--"
21465 ["Set Priority" org-priority t]
21466 ["Priority Up" org-shiftup t]
21467 ["Priority Down" org-shiftdown t]
21468 "--"
21469 ["Get news from all feeds" org-feed-update-all t]
21470 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21471 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21472 ("TAGS and Properties"
21473 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21474 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21475 "--"
21476 ["Set property" org-set-property (not (org-before-first-heading-p))]
21477 ["Column view of properties" org-columns t]
21478 ["Insert Column View DBlock" org-columns-insert-dblock t])
21479 ("Dates and Scheduling"
21480 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21481 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21482 ("Change Date"
21483 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21484 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21485 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21486 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21487 ["Compute Time Range" org-evaluate-time-range t]
21488 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21489 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21490 "--"
21491 ["Custom time format" org-toggle-time-stamp-overlays
21492 :style radio :selected org-display-custom-times]
21493 "--"
21494 ["Goto Calendar" org-goto-calendar t]
21495 ["Date from Calendar" org-date-from-calendar t]
21496 "--"
21497 ["Start/Restart Timer" org-timer-start t]
21498 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21499 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21500 ["Insert Timer String" org-timer t]
21501 ["Insert Timer Item" org-timer-item t])
21502 ("Logging work"
21503 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21504 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21505 ["Clock out" org-clock-out t]
21506 ["Clock cancel" org-clock-cancel t]
21507 "--"
21508 ["Mark as default task" org-clock-mark-default-task t]
21509 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21510 ["Goto running clock" org-clock-goto t]
21511 "--"
21512 ["Display times" org-clock-display t]
21513 ["Create clock table" org-clock-report t]
21514 "--"
21515 ["Record DONE time"
21516 (progn (setq org-log-done (not org-log-done))
21517 (message "Switching to %s will %s record a timestamp"
21518 (car org-done-keywords)
21519 (if org-log-done "automatically" "not")))
21520 :style toggle :selected org-log-done])
21521 "--"
21522 ["Agenda Command..." org-agenda t]
21523 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21524 ("File List for Agenda")
21525 ("Special views current file"
21526 ["TODO Tree" org-show-todo-tree t]
21527 ["Check Deadlines" org-check-deadlines t]
21528 ["Tags/Property tree" org-match-sparse-tree t])
21529 "--"
21530 ["Export/Publish..." org-export-dispatch t]
21531 ("LaTeX"
21532 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21533 :selected org-cdlatex-mode]
21534 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21535 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21536 ["Modify math symbol" org-cdlatex-math-modify
21537 (org-inside-LaTeX-fragment-p)]
21538 ["Insert citation" org-reftex-citation t])
21539 "--"
21540 ("MobileOrg"
21541 ["Push Files and Views" org-mobile-push t]
21542 ["Get Captured and Flagged" org-mobile-pull t]
21543 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21544 "--"
21545 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21546 "--"
21547 ("Documentation"
21548 ["Show Version" org-version t]
21549 ["Info Documentation" org-info t])
21550 ("Customize"
21551 ["Browse Org Group" org-customize t]
21552 "--"
21553 ["Expand This Menu" org-create-customize-menu
21554 (fboundp 'customize-menu-create)])
21555 ["Send bug report" org-submit-bug-report t]
21556 "--"
21557 ("Refresh/Reload"
21558 ["Refresh setup current buffer" org-mode-restart t]
21559 ["Reload Org (after update)" org-reload t]
21560 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21563 (defun org-info (&optional node)
21564 "Read documentation for Org in the info system.
21565 With optional NODE, go directly to that node."
21566 (interactive)
21567 (info (format "(org)%s" (or node ""))))
21569 ;;;###autoload
21570 (defun org-submit-bug-report ()
21571 "Submit a bug report on Org via mail.
21573 Don't hesitate to report any problems or inaccurate documentation.
21575 If you don't have setup sending mail from (X)Emacs, please copy the
21576 output buffer into your mail program, as it gives us important
21577 information about your Org version and configuration."
21578 (interactive)
21579 (require 'reporter)
21580 (defvar reporter-prompt-for-summary-p)
21581 (org-load-modules-maybe)
21582 (org-require-autoloaded-modules)
21583 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21584 (reporter-submit-bug-report
21585 "emacs-orgmode@gnu.org"
21586 (org-version nil 'full)
21587 (let (list)
21588 (save-window-excursion
21589 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21590 (delete-other-windows)
21591 (erase-buffer)
21592 (insert "You are about to submit a bug report to the Org mailing list.
21594 We would like to add your full Org and Outline configuration to the
21595 bug report. This greatly simplifies the work of the maintainer and
21596 other experts on the mailing list.
21598 HOWEVER, some variables you have customized may contain private
21599 information. The names of customers, colleagues, or friends, might
21600 appear in the form of file names, tags, todo states, or search strings.
21601 If you answer yes to the prompt, you might want to check and remove
21602 such private information before sending the email.")
21603 (add-text-properties (point-min) (point-max) '(face org-warning))
21604 (when (yes-or-no-p "Include your Org configuration ")
21605 (mapatoms
21606 (lambda (v)
21607 (and (boundp v)
21608 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21609 (or (and (symbol-value v)
21610 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21611 (and
21612 (get v 'custom-type) (get v 'standard-value)
21613 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21614 (push v list)))))
21615 (kill-buffer (get-buffer "*Warn about privacy*"))
21616 list))
21617 nil nil
21618 "Remember to cover the basics, that is, what you expected to happen and
21619 what in fact did happen. You don't know how to make a good report? See
21621 http://orgmode.org/manual/Feedback.html#Feedback
21623 Your bug report will be posted to the Org mailing list.
21624 ------------------------------------------------------------------------")
21625 (save-excursion
21626 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21627 (replace-match "\\1Bug: \\3 [\\2]")))))
21630 (defun org-install-agenda-files-menu ()
21631 (let ((bl (buffer-list)))
21632 (save-excursion
21633 (while bl
21634 (set-buffer (pop bl))
21635 (when (derived-mode-p 'org-mode) (setq bl nil)))
21636 (when (derived-mode-p 'org-mode)
21637 (easy-menu-change
21638 '("Org") "File List for Agenda"
21639 (append
21640 (list
21641 ["Edit File List" (org-edit-agenda-file-list) t]
21642 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21643 ["Remove Current File from List" org-remove-file t]
21644 ["Cycle through agenda files" org-cycle-agenda-files t]
21645 ["Occur in all agenda files" org-occur-in-agenda-files t]
21646 "--")
21647 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21649 ;;;; Documentation
21651 (defun org-require-autoloaded-modules ()
21652 (interactive)
21653 (mapc #'require
21654 '(org-agenda org-archive org-attach org-clock org-colview org-id
21655 org-table org-timer)))
21657 ;;;###autoload
21658 (defun org-reload (&optional uncompiled)
21659 "Reload all org lisp files.
21660 With prefix arg UNCOMPILED, load the uncompiled versions."
21661 (interactive "P")
21662 (require 'loadhist)
21663 (let* ((org-dir (org-find-library-dir "org"))
21664 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21665 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21666 (remove-re (format "\\`%s\\'"
21667 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21668 (feats (delete-dups
21669 (mapcar 'file-name-sans-extension
21670 (mapcar 'file-name-nondirectory
21671 (delq nil
21672 (mapcar 'feature-file
21673 features))))))
21674 (lfeat (append
21675 (sort
21676 (setq feats
21677 (delq nil (mapcar
21678 (lambda (f)
21679 (if (and (string-match feature-re f)
21680 (not (string-match remove-re f)))
21681 f nil))
21682 feats)))
21683 'string-lessp)
21684 (list "org-version" "org")))
21685 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21686 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21687 load-uncore load-misses)
21688 (setq load-misses
21689 (delq 't
21690 (mapcar (lambda (f)
21691 (or (org-load-noerror-mustsuffix (concat org-dir f))
21692 (and (string= org-dir contrib-dir)
21693 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21694 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21695 (add-to-list 'load-uncore f 'append)
21698 lfeat)))
21699 (when load-uncore
21700 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21701 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21702 (if load-misses
21703 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21704 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21705 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21707 ;;;###autoload
21708 (defun org-customize ()
21709 "Call the customize function with org as argument."
21710 (interactive)
21711 (org-load-modules-maybe)
21712 (org-require-autoloaded-modules)
21713 (customize-browse 'org))
21715 (defun org-create-customize-menu ()
21716 "Create a full customization menu for Org mode, insert it into the menu."
21717 (interactive)
21718 (org-load-modules-maybe)
21719 (org-require-autoloaded-modules)
21720 (if (fboundp 'customize-menu-create)
21721 (progn
21722 (easy-menu-change
21723 '("Org") "Customize"
21724 `(["Browse Org group" org-customize t]
21725 "--"
21726 ,(customize-menu-create 'org)
21727 ["Set" Custom-set t]
21728 ["Save" Custom-save t]
21729 ["Reset to Current" Custom-reset-current t]
21730 ["Reset to Saved" Custom-reset-saved t]
21731 ["Reset to Standard Settings" Custom-reset-standard t]))
21732 (message "\"Org\"-menu now contains full customization menu"))
21733 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21735 ;;;; Miscellaneous stuff
21737 ;;; Generally useful functions
21739 (defun org-get-at-eol (property n)
21740 "Get text property PROPERTY at the end of line less N characters."
21741 (get-text-property (- (point-at-eol) n) property))
21743 (defun org-find-text-property-in-string (prop s)
21744 "Return the first non-nil value of property PROP in string S."
21745 (or (get-text-property 0 prop s)
21746 (get-text-property (or (next-single-property-change 0 prop s) 0)
21747 prop s)))
21749 (defun org-display-warning (message)
21750 "Display the given MESSAGE as a warning."
21751 (display-warning 'org message :warning))
21753 (defun org-eval (form)
21754 "Eval FORM and return result."
21755 (condition-case error
21756 (eval form)
21757 (error (format "%%![Error: %s]" error))))
21759 (defun org-in-clocktable-p ()
21760 "Check if the cursor is in a clocktable."
21761 (let ((pos (point)) start)
21762 (save-excursion
21763 (end-of-line 1)
21764 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21765 (setq start (match-beginning 0))
21766 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21767 (>= (match-end 0) pos)
21768 start))))
21770 (defun org-in-verbatim-emphasis ()
21771 (save-match-data
21772 (and (org-in-regexp org-verbatim-re 2)
21773 (>= (point) (match-beginning 3))
21774 (<= (point) (match-end 4)))))
21776 (defun org-overlay-display (ovl text &optional face evap)
21777 "Make overlay OVL display TEXT with face FACE."
21778 (overlay-put ovl 'display text)
21779 (if face (overlay-put ovl 'face face))
21780 (if evap (overlay-put ovl 'evaporate t)))
21782 (defun org-overlay-before-string (ovl text &optional face evap)
21783 "Make overlay OVL display TEXT with face FACE."
21784 (if face (org-add-props text nil 'face face))
21785 (overlay-put ovl 'before-string text)
21786 (if evap (overlay-put ovl 'evaporate t)))
21788 (defun org-find-overlays (prop &optional pos delete)
21789 "Find all overlays specifying PROP at POS or point.
21790 If DELETE is non-nil, delete all those overlays."
21791 (let (found)
21792 (dolist (ov (overlays-at (or pos (point))) found)
21793 (cond ((not (overlay-get ov prop)))
21794 (delete (delete-overlay ov))
21795 (t (push ov found))))))
21797 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21798 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21799 (if (and marker (marker-buffer marker)
21800 (buffer-live-p (marker-buffer marker)))
21801 (progn
21802 (pop-to-buffer-same-window (marker-buffer marker))
21803 (when (or (> marker (point-max)) (< marker (point-min)))
21804 (widen))
21805 (goto-char marker)
21806 (org-show-context 'org-goto))
21807 (if bookmark
21808 (bookmark-jump bookmark)
21809 (error "Cannot find location"))))
21811 (defun org-quote-csv-field (s)
21812 "Quote field for inclusion in CSV material."
21813 (if (string-match "[\",]" s)
21814 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21817 (defun org-force-self-insert (N)
21818 "Needed to enforce self-insert under remapping."
21819 (interactive "p")
21820 (self-insert-command N))
21822 (defun org-string-width (s)
21823 "Compute width of string, ignoring invisible characters.
21824 This ignores character with invisibility property `org-link', and also
21825 characters with property `org-cwidth', because these will become invisible
21826 upon the next fontification round."
21827 (let (b l)
21828 (when (or (eq t buffer-invisibility-spec)
21829 (assq 'org-link buffer-invisibility-spec))
21830 (while (setq b (text-property-any 0 (length s)
21831 'invisible 'org-link s))
21832 (setq s (concat (substring s 0 b)
21833 (substring s (or (next-single-property-change
21834 b 'invisible s)
21835 (length s)))))))
21836 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21837 (setq s (concat (substring s 0 b)
21838 (substring s (or (next-single-property-change
21839 b 'org-cwidth s)
21840 (length s))))))
21841 (setq l (string-width s) b -1)
21842 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21843 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21846 (defun org-shorten-string (s maxlength)
21847 "Shorten string S so that it is no longer than MAXLENGTH characters.
21848 If the string is shorter or has length MAXLENGTH, just return the
21849 original string. If it is longer, the functions finds a space in the
21850 string, breaks this string off at that locations and adds three dots
21851 as ellipsis. Including the ellipsis, the string will not be longer
21852 than MAXLENGTH. If finding a good breaking point in the string does
21853 not work, the string is just chopped off in the middle of a word
21854 if necessary."
21855 (if (<= (length s) maxlength)
21857 (let* ((n (max (- maxlength 4) 1))
21858 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21859 (if (string-match re s)
21860 (concat (match-string 1 s) "...")
21861 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21863 (defun org-get-indentation (&optional line)
21864 "Get the indentation of the current line, interpreting tabs.
21865 When LINE is given, assume it represents a line and compute its indentation."
21866 (if line
21867 (when (string-match "^ *" (org-remove-tabs line))
21868 (match-end 0))
21869 (save-excursion
21870 (beginning-of-line 1)
21871 (skip-chars-forward " \t")
21872 (current-column))))
21874 (defun org-get-string-indentation (s)
21875 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21876 (let ((n -1) (i 0) (w tab-width) c)
21877 (catch 'exit
21878 (while (< (setq n (1+ n)) (length s))
21879 (setq c (aref s n))
21880 (cond ((= c ?\ ) (setq i (1+ i)))
21881 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21882 (t (throw 'exit t)))))
21885 (defun org-remove-tabs (s &optional width)
21886 "Replace tabulators in S with spaces.
21887 Assumes that s is a single line, starting in column 0."
21888 (setq width (or width tab-width))
21889 (while (string-match "\t" s)
21890 (setq s (replace-match
21891 (make-string
21892 (- (* width (/ (+ (match-beginning 0) width) width))
21893 (match-beginning 0)) ?\ )
21894 t t s)))
21897 (defun org-fix-indentation (line ind)
21898 "Fix indentation in LINE.
21899 IND is a cons cell with target and minimum indentation.
21900 If the current indentation in LINE is smaller than the minimum,
21901 leave it alone. If it is larger than ind, set it to the target."
21902 (let* ((l (org-remove-tabs line))
21903 (i (org-get-indentation l))
21904 (i1 (car ind)) (i2 (cdr ind)))
21905 (when (>= i i2) (setq l (substring line i2)))
21906 (if (> i1 0)
21907 (concat (make-string i1 ?\ ) l)
21908 l)))
21910 (defun org-remove-indentation (code &optional n)
21911 "Remove maximum common indentation in string CODE and return it.
21912 N may optionally be the number of columns to remove. Return CODE
21913 as-is if removal failed."
21914 (with-temp-buffer
21915 (insert code)
21916 (if (org-do-remove-indentation n) (buffer-string) code)))
21918 (defun org-do-remove-indentation (&optional n)
21919 "Remove the maximum common indentation from the buffer.
21920 When optional argument N is a positive integer, remove exactly
21921 that much characters from indentation, if possible. Return nil
21922 if it fails."
21923 (catch :exit
21924 (goto-char (point-min))
21925 ;; Find maximum common indentation, if not specified.
21926 (let ((n (or n
21927 (let ((min-ind (point-max)))
21928 (save-excursion
21929 (while (re-search-forward "^[ \t]*\\S-" nil t)
21930 (let ((ind (1- (current-column))))
21931 (if (zerop ind) (throw :exit nil)
21932 (setq min-ind (min min-ind ind))))))
21933 min-ind))))
21934 (if (zerop n) (throw :exit nil)
21935 ;; Remove exactly N indentation, but give up if not possible.
21936 (while (not (eobp))
21937 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21938 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21939 ((< ind n) (throw :exit nil))
21940 (t (indent-line-to (- ind n))))
21941 (forward-line)))
21942 ;; Signal success.
21943 t))))
21945 (defun org-fill-template (template alist)
21946 "Find each %key of ALIST in TEMPLATE and replace it."
21947 (let ((case-fold-search nil))
21948 (dolist (entry (sort (copy-sequence alist)
21949 (lambda (a b) (< (length (car a)) (length (car b))))))
21950 (setq template
21951 (replace-regexp-in-string
21952 (concat "%" (regexp-quote (car entry)))
21953 (or (cdr entry) "") template t t)))
21954 template))
21956 (defun org-base-buffer (buffer)
21957 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21958 (if (not buffer)
21959 buffer
21960 (or (buffer-base-buffer buffer)
21961 buffer)))
21963 (defun org-wrap (string &optional width lines)
21964 "Wrap string to either a number of lines, or a width in characters.
21965 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21966 that costs. If there is a word longer than WIDTH, the text is actually
21967 wrapped to the length of that word.
21968 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21969 many lines, whatever width that takes.
21970 The return value is a list of lines, without newlines at the end."
21971 (let* ((words (org-split-string string "[ \t\n]+"))
21972 (maxword (apply 'max (mapcar 'org-string-width words)))
21973 w ll)
21974 (cond (width
21975 (org-do-wrap words (max maxword width)))
21976 (lines
21977 (setq w maxword)
21978 (setq ll (org-do-wrap words maxword))
21979 (if (<= (length ll) lines)
21981 (setq ll words)
21982 (while (> (length ll) lines)
21983 (setq w (1+ w))
21984 (setq ll (org-do-wrap words w)))
21985 ll))
21986 (t (error "Cannot wrap this")))))
21988 (defun org-do-wrap (words width)
21989 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21990 (let (lines line)
21991 (while words
21992 (setq line (pop words))
21993 (while (and words (< (+ (length line) (length (car words))) width))
21994 (setq line (concat line " " (pop words))))
21995 (setq lines (push line lines)))
21996 (nreverse lines)))
21998 (defun org-split-string (string &optional separators)
21999 "Splits STRING into substrings at SEPARATORS.
22000 SEPARATORS is a regular expression.
22001 No empty strings are returned if there are matches at the beginning
22002 and end of string."
22003 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22004 (let ((start 0) notfirst list)
22005 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22006 (if (and notfirst
22007 (= start (match-beginning 0))
22008 (< start (length string)))
22009 (1+ start) start))
22010 (< (match-beginning 0) (length string)))
22011 (setq notfirst t)
22012 (or (eq (match-beginning 0) 0)
22013 (and (eq (match-beginning 0) (match-end 0))
22014 (eq (match-beginning 0) start))
22015 (push (substring string start (match-beginning 0)) list))
22016 (setq start (match-end 0)))
22017 (or (eq start (length string))
22018 (push (substring string start) list))
22019 (nreverse list)))
22021 (defun org-quote-vert (s)
22022 "Replace \"|\" with \"\\vert\"."
22023 (while (string-match "|" s)
22024 (setq s (replace-match "\\vert" t t s)))
22027 (defun org-uuidgen-p (s)
22028 "Is S an ID created by UUIDGEN?"
22029 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22031 (defun org-in-src-block-p (&optional inside)
22032 "Whether point is in a code source block.
22033 When INSIDE is non-nil, don't consider we are within a src block
22034 when point is at #+BEGIN_SRC or #+END_SRC."
22035 (let ((case-fold-search t))
22036 (or (and (eq (get-char-property (point) 'src-block) t))
22037 (and (not inside)
22038 (save-match-data
22039 (save-excursion
22040 (beginning-of-line)
22041 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22043 (defun org-context ()
22044 "Return a list of contexts of the current cursor position.
22045 If several contexts apply, all are returned.
22046 Each context entry is a list with a symbol naming the context, and
22047 two positions indicating start and end of the context. Possible
22048 contexts are:
22050 :headline anywhere in a headline
22051 :headline-stars on the leading stars in a headline
22052 :todo-keyword on a TODO keyword (including DONE) in a headline
22053 :tags on the TAGS in a headline
22054 :priority on the priority cookie in a headline
22055 :item on the first line of a plain list item
22056 :item-bullet on the bullet/number of a plain list item
22057 :checkbox on the checkbox in a plain list item
22058 :table in an Org table
22059 :table-special on a special filed in a table
22060 :table-table in a table.el table
22061 :clocktable in a clocktable
22062 :src-block in a source block
22063 :link on a hyperlink
22064 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22065 :target on a <<target>>
22066 :radio-target on a <<<radio-target>>>
22067 :latex-fragment on a LaTeX fragment
22068 :latex-preview on a LaTeX fragment with overlaid preview image
22070 This function expects the position to be visible because it uses font-lock
22071 faces as a help to recognize the following contexts: :table-special, :link,
22072 and :keyword."
22073 (let* ((f (get-text-property (point) 'face))
22074 (faces (if (listp f) f (list f)))
22075 (case-fold-search t)
22076 (p (point)) clist o)
22077 ;; First the large context
22078 (cond
22079 ((org-at-heading-p t)
22080 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22081 (when (progn
22082 (beginning-of-line 1)
22083 (looking-at org-todo-line-tags-regexp))
22084 (push (org-point-in-group p 1 :headline-stars) clist)
22085 (push (org-point-in-group p 2 :todo-keyword) clist)
22086 (push (org-point-in-group p 4 :tags) clist))
22087 (goto-char p)
22088 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22089 (when (looking-at "\\[#[A-Z0-9]\\]")
22090 (push (org-point-in-group p 0 :priority) clist)))
22092 ((org-at-item-p)
22093 (push (org-point-in-group p 2 :item-bullet) clist)
22094 (push (list :item (point-at-bol)
22095 (save-excursion (org-end-of-item) (point)))
22096 clist)
22097 (and (org-at-item-checkbox-p)
22098 (push (org-point-in-group p 0 :checkbox) clist)))
22100 ((org-at-table-p)
22101 (push (list :table (org-table-begin) (org-table-end)) clist)
22102 (when (memq 'org-formula faces)
22103 (push (list :table-special
22104 (previous-single-property-change p 'face)
22105 (next-single-property-change p 'face)) clist)))
22106 ((org-at-table-p 'any)
22107 (push (list :table-table) clist)))
22108 (goto-char p)
22110 (let ((case-fold-search t))
22111 ;; New the "medium" contexts: clocktables, source blocks
22112 (cond ((org-in-clocktable-p)
22113 (push (list :clocktable
22114 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22115 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22116 (match-beginning 1))
22117 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22118 (match-end 0))) clist))
22119 ((org-in-src-block-p)
22120 (push (list :src-block
22121 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22122 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22123 (match-beginning 1))
22124 (and (search-forward "#+END_SRC" nil t)
22125 (match-beginning 0))) clist))))
22126 (goto-char p)
22128 ;; Now the small context
22129 (cond
22130 ((org-at-timestamp-p)
22131 (push (org-point-in-group p 0 :timestamp) clist))
22132 ((memq 'org-link faces)
22133 (push (list :link
22134 (previous-single-property-change p 'face)
22135 (next-single-property-change p 'face)) clist))
22136 ((memq 'org-special-keyword faces)
22137 (push (list :keyword
22138 (previous-single-property-change p 'face)
22139 (next-single-property-change p 'face)) clist))
22140 ((org-at-target-p)
22141 (push (org-point-in-group p 0 :target) clist)
22142 (goto-char (1- (match-beginning 0)))
22143 (when (looking-at org-radio-target-regexp)
22144 (push (org-point-in-group p 0 :radio-target) clist))
22145 (goto-char p))
22146 ((setq o (cl-some
22147 (lambda (o)
22148 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22150 (overlays-at (point))))
22151 (push (list :latex-fragment
22152 (overlay-start o) (overlay-end o)) clist)
22153 (push (list :latex-preview
22154 (overlay-start o) (overlay-end o)) clist))
22155 ((org-inside-LaTeX-fragment-p)
22156 ;; FIXME: positions wrong.
22157 (push (list :latex-fragment (point) (point)) clist)))
22159 (setq clist (nreverse (delq nil clist)))
22160 clist))
22162 (defun org-in-regexp (regexp &optional nlines visually)
22163 "Check if point is inside a match of REGEXP.
22165 Normally only the current line is checked, but you can include
22166 NLINES extra lines around point into the search. If VISUALLY is
22167 set, require that the cursor is not after the match but really
22168 on, so that the block visually is on the match.
22170 Return nil or a cons cell (BEG . END) where BEG and END are,
22171 respectively, the positions at the beginning and the end of the
22172 match."
22173 (catch :exit
22174 (let ((pos (point))
22175 (eol (line-end-position (if nlines (1+ nlines) 1))))
22176 (save-excursion
22177 (beginning-of-line (- 1 (or nlines 0)))
22178 (while (and (re-search-forward regexp eol t)
22179 (<= (match-beginning 0) pos))
22180 (let ((end (match-end 0)))
22181 (when (or (> end pos) (and (= end pos) (not visually)))
22182 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22184 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22185 "Non-nil when point is between matches of START-RE and END-RE.
22187 Also return a non-nil value when point is on one of the matches.
22189 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22190 buffer positions. Default values are the positions of headlines
22191 surrounding the point.
22193 The functions returns a cons cell whose car (resp. cdr) is the
22194 position before START-RE (resp. after END-RE)."
22195 (save-match-data
22196 (let ((pos (point))
22197 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22198 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22199 beg end)
22200 (save-excursion
22201 ;; Point is on a block when on START-RE or if START-RE can be
22202 ;; found before it...
22203 (and (or (org-in-regexp start-re)
22204 (re-search-backward start-re limit-up t))
22205 (setq beg (match-beginning 0))
22206 ;; ... and END-RE after it...
22207 (goto-char (match-end 0))
22208 (re-search-forward end-re limit-down t)
22209 (> (setq end (match-end 0)) pos)
22210 ;; ... without another START-RE in-between.
22211 (goto-char (match-beginning 0))
22212 (not (re-search-backward start-re (1+ beg) t))
22213 ;; Return value.
22214 (cons beg end))))))
22216 (defun org-in-block-p (names)
22217 "Non-nil when point belongs to a block whose name belongs to NAMES.
22219 NAMES is a list of strings containing names of blocks.
22221 Return first block name matched, or nil. Beware that in case of
22222 nested blocks, the returned name may not belong to the closest
22223 block from point."
22224 (save-match-data
22225 (catch 'exit
22226 (let ((case-fold-search t)
22227 (lim-up (save-excursion (outline-previous-heading)))
22228 (lim-down (save-excursion (outline-next-heading))))
22229 (dolist (name names)
22230 (let ((n (regexp-quote name)))
22231 (when (org-between-regexps-p
22232 (concat "^[ \t]*#\\+begin_" n)
22233 (concat "^[ \t]*#\\+end_" n)
22234 lim-up lim-down)
22235 (throw 'exit n)))))
22236 nil)))
22238 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22239 "Call `multi-occur' with buffers for all agenda files."
22240 (interactive "sOrg-files matching: ")
22241 (let* ((files (org-agenda-files))
22242 (tnames (mapcar #'file-truename files))
22243 (extra org-agenda-text-search-extra-files))
22244 (when (eq (car extra) 'agenda-archives)
22245 (setq extra (cdr extra))
22246 (setq files (org-add-archive-files files)))
22247 (dolist (f extra)
22248 (unless (member (file-truename f) tnames)
22249 (unless (member f files) (setq files (append files (list f))))
22250 (setq tnames (append tnames (list (file-truename f))))))
22251 (multi-occur
22252 (mapcar (lambda (x)
22253 (with-current-buffer
22254 ;; FIXME: Why not just (find-file-noselect x)?
22255 ;; Is it to avoid the "revert buffer" prompt?
22256 (or (get-file-buffer x) (find-file-noselect x))
22257 (widen)
22258 (current-buffer)))
22259 files)
22260 regexp)))
22262 (add-hook 'occur-mode-find-occurrence-hook
22263 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22265 (defun org-occur-link-in-agenda-files ()
22266 "Create a link and search for it in the agendas.
22267 The link is not stored in `org-stored-links', it is just created
22268 for the search purpose."
22269 (interactive)
22270 (let ((link (condition-case nil
22271 (org-store-link nil)
22272 (error "Unable to create a link to here"))))
22273 (org-occur-in-agenda-files (regexp-quote link))))
22275 (defun org-reverse-string (string)
22276 "Return the reverse of STRING."
22277 (apply 'string (reverse (string-to-list string))))
22279 ;; defsubst org-uniquify must be defined before first use
22281 (defun org-uniquify-alist (alist)
22282 "Merge elements of ALIST with the same key.
22284 For example, in this alist:
22286 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22287 => \\='((a 1 3) (b 2))
22289 merge (a 1) and (a 3) into (a 1 3).
22291 The function returns the new ALIST."
22292 (let (rtn)
22293 (dolist (e alist rtn)
22294 (let (n)
22295 (if (not (assoc (car e) rtn))
22296 (push e rtn)
22297 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22298 (setq rtn (assq-delete-all (car e) rtn))
22299 (push n rtn))))))
22301 (defun org-delete-all (elts list)
22302 "Remove all elements in ELTS from LIST.
22303 Comparison is done with `equal'. It is a destructive operation
22304 that may remove elements by altering the list structure."
22305 (while elts
22306 (setq list (delete (pop elts) list)))
22307 list)
22309 (defun org-back-over-empty-lines ()
22310 "Move backwards over whitespace, to the beginning of the first empty line.
22311 Returns the number of empty lines passed."
22312 (let ((pos (point)))
22313 (if (cdr (assq 'heading org-blank-before-new-entry))
22314 (skip-chars-backward " \t\n\r")
22315 (unless (eobp)
22316 (forward-line -1)))
22317 (beginning-of-line 2)
22318 (goto-char (min (point) pos))
22319 (count-lines (point) pos)))
22321 (defun org-skip-whitespace ()
22322 (skip-chars-forward " \t\n\r"))
22324 (defun org-point-in-group (point group &optional context)
22325 "Check if POINT is in match-group GROUP.
22326 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22327 match. If the match group does not exist or point is not inside it,
22328 return nil."
22329 (and (match-beginning group)
22330 (>= point (match-beginning group))
22331 (<= point (match-end group))
22332 (if context
22333 (list context (match-beginning group) (match-end group))
22334 t)))
22336 (defun org-switch-to-buffer-other-window (&rest args)
22337 "Switch to buffer in a second window on the current frame.
22338 In particular, do not allow pop-up frames.
22339 Returns the newly created buffer."
22340 (org-no-popups
22341 (apply 'switch-to-buffer-other-window args)))
22343 (defun org-combine-plists (&rest plists)
22344 "Create a single property list from all plists in PLISTS.
22345 The process starts by copying the first list, and then setting properties
22346 from the other lists. Settings in the last list are the most significant
22347 ones and overrule settings in the other lists."
22348 (let ((rtn (copy-sequence (pop plists)))
22349 p v ls)
22350 (while plists
22351 (setq ls (pop plists))
22352 (while ls
22353 (setq p (pop ls) v (pop ls))
22354 (setq rtn (plist-put rtn p v))))
22355 rtn))
22357 (defun org-replace-escapes (string table)
22358 "Replace %-escapes in STRING with values in TABLE.
22359 TABLE is an association list with keys like \"%a\" and string values.
22360 The sequences in STRING may contain normal field width and padding information,
22361 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22362 so values can contain further %-escapes if they are define later in TABLE."
22363 (let ((tbl (copy-alist table))
22364 (case-fold-search nil)
22365 (pchg 0)
22366 re rpl)
22367 (dolist (e tbl)
22368 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22369 (when (and (cdr e) (string-match re (cdr e)))
22370 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22371 (safe "SREF"))
22372 (add-text-properties 0 3 (list 'sref sref) safe)
22373 (setcdr e (replace-match safe t t (cdr e)))))
22374 (while (string-match re string)
22375 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22376 (cdr e)))
22377 (setq string (replace-match rpl t t string))))
22378 (while (setq pchg (next-property-change pchg string))
22379 (let ((sref (get-text-property pchg 'sref string)))
22380 (when (and sref (string-match "SREF" string pchg))
22381 (setq string (replace-match sref t t string)))))
22382 string))
22384 (defun org-find-base-buffer-visiting (file)
22385 "Like `find-buffer-visiting' but always return the base buffer and
22386 not an indirect buffer."
22387 (let ((buf (or (get-file-buffer file)
22388 (find-buffer-visiting file))))
22389 (if buf
22390 (or (buffer-base-buffer buf) buf)
22391 nil)))
22393 ;;; TODO: Only called once, from ox-odt which should probably use
22394 ;;; org-export-inline-image-p or something.
22395 (defun org-file-image-p (file)
22396 "Return non-nil if FILE is an image."
22397 (save-match-data
22398 (string-match (image-file-name-regexp) file)))
22400 (defun org-get-cursor-date (&optional with-time)
22401 "Return the date at cursor in as a time.
22402 This works in the calendar and in the agenda, anywhere else it just
22403 returns the current time.
22404 If WITH-TIME is non-nil, returns the time of the event at point (in
22405 the agenda) or the current time of the day."
22406 (let (date day defd tp hod mod)
22407 (when with-time
22408 (setq tp (get-text-property (point) 'time))
22409 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22410 (setq hod (string-to-number (match-string 1 tp))
22411 mod (string-to-number (match-string 2 tp))))
22412 (or tp (let ((now (decode-time)))
22413 (setq hod (nth 2 now)
22414 mod (nth 1 now)))))
22415 (cond
22416 ((eq major-mode 'calendar-mode)
22417 (setq date (calendar-cursor-to-date)
22418 defd (encode-time 0 (or mod 0) (or hod 0)
22419 (nth 1 date) (nth 0 date) (nth 2 date))))
22420 ((eq major-mode 'org-agenda-mode)
22421 (setq day (get-text-property (point) 'day))
22422 (when day
22423 (setq date (calendar-gregorian-from-absolute day)
22424 defd (encode-time 0 (or mod 0) (or hod 0)
22425 (nth 1 date) (nth 0 date) (nth 2 date))))))
22426 (or defd (current-time))))
22428 (defun org-mark-subtree (&optional up)
22429 "Mark the current subtree.
22430 This puts point at the start of the current subtree, and mark at
22431 the end. If a numeric prefix UP is given, move up into the
22432 hierarchy of headlines by UP levels before marking the subtree."
22433 (interactive "P")
22434 (org-with-limited-levels
22435 (cond ((org-at-heading-p) (beginning-of-line))
22436 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22437 (t (outline-previous-visible-heading 1))))
22438 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22439 (if (called-interactively-p 'any)
22440 (call-interactively 'org-mark-element)
22441 (org-mark-element)))
22443 (defun org-file-newer-than-p (file time)
22444 "Non-nil if FILE is newer than TIME.
22445 FILE is a filename, as a string, TIME is a list of integers, as
22446 returned by, e.g., `current-time'."
22447 (and (file-exists-p file)
22448 ;; Only compare times up to whole seconds as some file-systems
22449 ;; (e.g. HFS+) do not retain any finer granularity. As
22450 ;; a consequence, make sure we return non-nil when the two
22451 ;; times are equal.
22452 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22453 (cl-subseq time 0 2)))))
22455 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22456 "Compile a SOURCE file using PROCESS.
22458 PROCESS is either a function or a list of shell commands, as
22459 strings. EXT is a file extension, without the leading dot, as
22460 a string. It is used to check if the process actually succeeded.
22462 PROCESS must create a file with the same base name and directory
22463 as SOURCE, but ending with EXT. The function then returns its
22464 filename. Otherwise, it raises an error. The error message can
22465 then be refined by providing string ERR-MSG, which is appended to
22466 the standard message.
22468 If PROCESS is a function, it is called with a single argument:
22469 the SOURCE file.
22471 If it is a list of commands, each of them is called using
22472 `shell-command'. By default, in each command, %b, %f, %F, %o and
22473 %O are replaced with, respectively, SOURCE base name, name, full
22474 name, directory and absolute output file name. It is possible,
22475 however, to use more place-holders by specifying them in optional
22476 argument SPEC, as an alist following the pattern
22478 (CHARACTER . REPLACEMENT-STRING).
22480 When PROCESS is a list of commands, optional argument LOG-BUF can
22481 be set to a buffer or a buffer name. `shell-command' then uses
22482 it for output."
22483 (let* ((base-name (file-name-base source))
22484 (full-name (file-truename source))
22485 (out-dir (or (file-name-directory source) "./"))
22486 (output (expand-file-name (concat base-name "." ext) out-dir))
22487 (time (current-time))
22488 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22489 (save-window-excursion
22490 (pcase process
22491 ((pred functionp) (funcall process (shell-quote-argument source)))
22492 ((pred consp)
22493 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22494 (spec (append spec
22495 `((?b . ,(shell-quote-argument base-name))
22496 (?f . ,(shell-quote-argument source))
22497 (?F . ,(shell-quote-argument full-name))
22498 (?o . ,(shell-quote-argument out-dir))
22499 (?O . ,(shell-quote-argument output))))))
22500 (dolist (command process)
22501 (shell-command (format-spec command spec) log-buf))
22502 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22503 (_ (error "No valid command to process %S%s" source err-msg))))
22504 ;; Check for process failure. Output file is expected to be
22505 ;; located in the same directory as SOURCE.
22506 (unless (org-file-newer-than-p output time)
22507 (error (format "File %S wasn't produced%s" output err-msg)))
22508 output))
22510 ;;; Indentation
22512 (defvar org-element-greater-elements)
22513 (defun org--get-expected-indentation (element contentsp)
22514 "Expected indentation column for current line, according to ELEMENT.
22515 ELEMENT is an element containing point. CONTENTSP is non-nil
22516 when indentation is to be computed according to contents of
22517 ELEMENT."
22518 (let ((type (org-element-type element))
22519 (start (org-element-property :begin element))
22520 (post-affiliated (org-element-property :post-affiliated element)))
22521 (org-with-wide-buffer
22522 (cond
22523 (contentsp
22524 (cl-case type
22525 ((diary-sexp footnote-definition) 0)
22526 ((headline inlinetask nil)
22527 (if (not org-adapt-indentation) 0
22528 (let ((level (org-current-level)))
22529 (if level (1+ level) 0))))
22530 ((item plain-list) (org-list-item-body-column post-affiliated))
22532 (goto-char start)
22533 (org-get-indentation))))
22534 ((memq type '(headline inlinetask nil))
22535 (if (org-match-line "[ \t]*$")
22536 (org--get-expected-indentation element t)
22538 ((memq type '(diary-sexp footnote-definition)) 0)
22539 ;; First paragraph of a footnote definition or an item.
22540 ;; Indent like parent.
22541 ((< (line-beginning-position) start)
22542 (org--get-expected-indentation
22543 (org-element-property :parent element) t))
22544 ;; At first line: indent according to previous sibling, if any,
22545 ;; ignoring footnote definitions and inline tasks, or parent's
22546 ;; contents.
22547 ((= (line-beginning-position) start)
22548 (catch 'exit
22549 (while t
22550 (if (= (point-min) start) (throw 'exit 0)
22551 (goto-char (1- start))
22552 (let* ((previous (org-element-at-point))
22553 (parent previous))
22554 (while (and parent (<= (org-element-property :end parent) start))
22555 (setq previous parent
22556 parent (org-element-property :parent parent)))
22557 (cond
22558 ((not previous) (throw 'exit 0))
22559 ((> (org-element-property :end previous) start)
22560 (throw 'exit (org--get-expected-indentation previous t)))
22561 ((memq (org-element-type previous)
22562 '(footnote-definition inlinetask))
22563 (setq start (org-element-property :begin previous)))
22564 (t (goto-char (org-element-property :begin previous))
22565 (throw 'exit
22566 (if (bolp) (org-get-indentation)
22567 ;; At first paragraph in an item or
22568 ;; a footnote definition.
22569 (org--get-expected-indentation
22570 (org-element-property :parent previous) t))))))))))
22571 ;; Otherwise, move to the first non-blank line above.
22573 (beginning-of-line)
22574 (let ((pos (point)))
22575 (skip-chars-backward " \r\t\n")
22576 (cond
22577 ;; Two blank lines end a footnote definition or a plain
22578 ;; list. When we indent an empty line after them, the
22579 ;; containing list or footnote definition is over, so it
22580 ;; qualifies as a previous sibling. Therefore, we indent
22581 ;; like its first line.
22582 ((and (memq type '(footnote-definition plain-list))
22583 (> (count-lines (point) pos) 2))
22584 (goto-char start)
22585 (org-get-indentation))
22586 ;; Line above is the first one of a paragraph at the
22587 ;; beginning of an item or a footnote definition. Indent
22588 ;; like parent.
22589 ((< (line-beginning-position) start)
22590 (org--get-expected-indentation
22591 (org-element-property :parent element) t))
22592 ;; Line above is the beginning of an element, i.e., point
22593 ;; was originally on the blank lines between element's start
22594 ;; and contents.
22595 ((= (line-beginning-position) post-affiliated)
22596 (org--get-expected-indentation element t))
22597 ;; POS is after contents in a greater element. Indent like
22598 ;; the beginning of the element.
22599 ((and (memq type org-element-greater-elements)
22600 (let ((cend (org-element-property :contents-end element)))
22601 (and cend (<= cend pos))))
22602 ;; As a special case, if point is at the end of a footnote
22603 ;; definition or an item, indent like the very last element
22604 ;; within. If that last element is an item, indent like
22605 ;; its contents.
22606 (if (memq type '(footnote-definition item plain-list))
22607 (let ((last (org-element-at-point)))
22608 (goto-char pos)
22609 (org--get-expected-indentation
22610 last (eq (org-element-type last) 'item)))
22611 (goto-char start)
22612 (org-get-indentation)))
22613 ;; In any other case, indent like the current line.
22614 (t (org-get-indentation)))))))))
22616 (defun org--align-node-property ()
22617 "Align node property at point.
22618 Alignment is done according to `org-property-format', which see."
22619 (when (save-excursion
22620 (beginning-of-line)
22621 (looking-at org-property-re))
22622 (replace-match
22623 (concat (match-string 4)
22624 (org-trim
22625 (format org-property-format (match-string 1) (match-string 3))))
22626 t t)))
22628 (defun org-indent-line ()
22629 "Indent line depending on context.
22631 Indentation is done according to the following rules:
22633 - Footnote definitions, diary sexps, headlines and inline tasks
22634 have to start at column 0.
22636 - On the very first line of an element, consider, in order, the
22637 next rules until one matches:
22639 1. If there's a sibling element before, ignoring footnote
22640 definitions and inline tasks, indent like its first line.
22642 2. If element has a parent, indent like its contents. More
22643 precisely, if parent is an item, indent after the
22644 description part, if any, or the bullet (see
22645 `org-list-description-max-indent'). Else, indent like
22646 parent's first line.
22648 3. Otherwise, indent relatively to current level, if
22649 `org-adapt-indentation' is non-nil, or to left margin.
22651 - On a blank line at the end of an element, indent according to
22652 the type of the element. More precisely
22654 1. If element is a plain list, an item, or a footnote
22655 definition, indent like the very last element within.
22657 2. If element is a paragraph, indent like its last non blank
22658 line.
22660 3. Otherwise, indent like its very first line.
22662 - In the code part of a source block, use language major mode
22663 to indent current line if `org-src-tab-acts-natively' is
22664 non-nil. If it is nil, do nothing.
22666 - Otherwise, indent like the first non-blank line above.
22668 The function doesn't indent an item as it could break the whole
22669 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22670 `\\[org-shiftmetaright]'.
22672 Also align node properties according to `org-property-format'."
22673 (interactive)
22674 (cond
22675 (orgstruct-is-++
22676 (let ((indent-line-function
22677 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22678 (indent-according-to-mode)))
22679 ((org-at-heading-p) 'noindent)
22681 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22682 (type (org-element-type element)))
22683 (cond ((and (memq type '(plain-list item))
22684 (= (line-beginning-position)
22685 (org-element-property :post-affiliated element)))
22686 'noindent)
22687 ((and (eq type 'latex-environment)
22688 (>= (point) (org-element-property :post-affiliated element))
22689 (< (point) (org-with-wide-buffer
22690 (goto-char (org-element-property :end element))
22691 (skip-chars-backward " \r\t\n")
22692 (line-beginning-position 2))))
22693 'noindent)
22694 ((and (eq type 'src-block)
22695 org-src-tab-acts-natively
22696 (> (line-beginning-position)
22697 (org-element-property :post-affiliated element))
22698 (< (line-beginning-position)
22699 (org-with-wide-buffer
22700 (goto-char (org-element-property :end element))
22701 (skip-chars-backward " \r\t\n")
22702 (line-beginning-position))))
22703 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22705 (let ((column (org--get-expected-indentation element nil)))
22706 ;; Preserve current column.
22707 (if (<= (current-column) (current-indentation))
22708 (indent-line-to column)
22709 (save-excursion (indent-line-to column))))
22710 ;; Align node property. Also preserve current column.
22711 (when (eq type 'node-property)
22712 (let ((column (current-column)))
22713 (org--align-node-property)
22714 (org-move-to-column column)))))))))
22716 (defun org-indent-region (start end)
22717 "Indent each non-blank line in the region.
22718 Called from a program, START and END specify the region to
22719 indent. The function will not indent contents of example blocks,
22720 verse blocks and export blocks as leading white spaces are
22721 assumed to be significant there."
22722 (interactive "r")
22723 (save-excursion
22724 (goto-char start)
22725 (skip-chars-forward " \r\t\n")
22726 (unless (eobp) (beginning-of-line))
22727 (let ((indent-to
22728 (lambda (ind pos)
22729 ;; Set IND as indentation for all lines between point and
22730 ;; POS. Blank lines are ignored. Leave point after POS
22731 ;; once done.
22732 (let ((limit (copy-marker pos)))
22733 (while (< (point) limit)
22734 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22735 (forward-line))
22736 (set-marker limit nil))))
22737 (end (copy-marker end)))
22738 (while (< (point) end)
22739 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22740 (let* ((element (org-element-at-point))
22741 (type (org-element-type element))
22742 (element-end (copy-marker (org-element-property :end element)))
22743 (ind (org--get-expected-indentation element nil)))
22744 (cond
22745 ;; Element indented as a single block. Example blocks
22746 ;; preserving indentation are a special case since the
22747 ;; "contents" must not be indented whereas the block
22748 ;; boundaries can.
22749 ((or (memq type '(export-block latex-environment))
22750 (and (eq type 'example-block)
22751 (not
22752 (or org-src-preserve-indentation
22753 (org-element-property :preserve-indent element)))))
22754 (let ((offset (- ind (org-get-indentation))))
22755 (unless (zerop offset)
22756 (indent-rigidly (org-element-property :begin element)
22757 (org-element-property :end element)
22758 offset)))
22759 (goto-char element-end))
22760 ;; Elements indented line wise. Be sure to exclude
22761 ;; example blocks (preserving indentation) and source
22762 ;; blocks from this category as they are treated
22763 ;; specially later.
22764 ((or (memq type '(paragraph table table-row))
22765 (not (or (org-element-property :contents-begin element)
22766 (memq type '(example-block src-block)))))
22767 (when (eq type 'node-property)
22768 (org--align-node-property)
22769 (beginning-of-line))
22770 (funcall indent-to ind (min element-end end)))
22771 ;; Elements consisting of three parts: before the
22772 ;; contents, the contents, and after the contents. The
22773 ;; contents are treated specially, according to the
22774 ;; element type, or not indented at all. Other parts are
22775 ;; indented as a single block.
22777 (let* ((post (copy-marker
22778 (org-element-property :post-affiliated element)))
22779 (cbeg
22780 (copy-marker
22781 (cond
22782 ((not (org-element-property :contents-begin element))
22783 ;; Fake contents for source blocks.
22784 (org-with-wide-buffer
22785 (goto-char post)
22786 (line-beginning-position 2)))
22787 ((memq type '(footnote-definition item plain-list))
22788 ;; Contents in these elements could start on
22789 ;; the same line as the beginning of the
22790 ;; element. Make sure we start indenting
22791 ;; from the second line.
22792 (org-with-wide-buffer
22793 (goto-char post)
22794 (end-of-line)
22795 (skip-chars-forward " \r\t\n")
22796 (if (eobp) (point) (line-beginning-position))))
22797 (t (org-element-property :contents-begin element)))))
22798 (cend (copy-marker
22799 (or (org-element-property :contents-end element)
22800 ;; Fake contents for source blocks.
22801 (org-with-wide-buffer
22802 (goto-char element-end)
22803 (skip-chars-backward " \r\t\n")
22804 (line-beginning-position)))
22805 t)))
22806 ;; Do not change items indentation individually as it
22807 ;; might break the list as a whole. On the other
22808 ;; hand, when at a plain list, indent it as a whole.
22809 (cond ((eq type 'plain-list)
22810 (let ((offset (- ind (org-get-indentation))))
22811 (unless (zerop offset)
22812 (indent-rigidly (org-element-property :begin element)
22813 (org-element-property :end element)
22814 offset))
22815 (goto-char cbeg)))
22816 ((eq type 'item) (goto-char cbeg))
22817 (t (funcall indent-to ind (min cbeg end))))
22818 (when (< (point) end)
22819 (cl-case type
22820 ((example-block verse-block))
22821 (src-block
22822 ;; In a source block, indent source code
22823 ;; according to language major mode, but only if
22824 ;; `org-src-tab-acts-natively' is non-nil.
22825 (when (and (< (point) end) org-src-tab-acts-natively)
22826 (ignore-errors
22827 (org-babel-do-in-edit-buffer
22828 (indent-region (point-min) (point-max))))))
22829 (t (org-indent-region (point) (min cend end))))
22830 (goto-char (min cend end))
22831 (when (< (point) end)
22832 (funcall indent-to ind (min element-end end))))
22833 (set-marker post nil)
22834 (set-marker cbeg nil)
22835 (set-marker cend nil))))
22836 (set-marker element-end nil))))
22837 (set-marker end nil))))
22839 (defun org-indent-drawer ()
22840 "Indent the drawer at point."
22841 (interactive)
22842 (unless (save-excursion
22843 (beginning-of-line)
22844 (looking-at-p org-drawer-regexp))
22845 (user-error "Not at a drawer"))
22846 (let ((element (org-element-at-point)))
22847 (unless (memq (org-element-type element) '(drawer property-drawer))
22848 (user-error "Not at a drawer"))
22849 (org-with-wide-buffer
22850 (org-indent-region (org-element-property :begin element)
22851 (org-element-property :end element))))
22852 (message "Drawer at point indented"))
22854 (defun org-indent-block ()
22855 "Indent the block at point."
22856 (interactive)
22857 (unless (save-excursion
22858 (beginning-of-line)
22859 (let ((case-fold-search t))
22860 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22861 (user-error "Not at a block"))
22862 (let ((element (org-element-at-point)))
22863 (unless (memq (org-element-type element)
22864 '(comment-block center-block dynamic-block example-block
22865 export-block quote-block special-block
22866 src-block verse-block))
22867 (user-error "Not at a block"))
22868 (org-with-wide-buffer
22869 (org-indent-region (org-element-property :begin element)
22870 (org-element-property :end element))))
22871 (message "Block at point indented"))
22874 ;;; Filling
22876 ;; We use our own fill-paragraph and auto-fill functions.
22878 ;; `org-fill-paragraph' relies on adaptive filling and context
22879 ;; checking. Appropriate `fill-prefix' is computed with
22880 ;; `org-adaptive-fill-function'.
22882 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22883 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22884 ;; `org-adaptive-fill-function' value. Internally,
22885 ;; `org-comment-line-break-function' breaks the line.
22887 ;; `org-setup-filling' installs filling and auto-filling related
22888 ;; variables during `org-mode' initialization.
22890 (defvar org-element-paragraph-separate) ; org-element.el
22891 (defun org-setup-filling ()
22892 (require 'org-element)
22893 ;; Prevent auto-fill from inserting unwanted new items.
22894 (when (boundp 'fill-nobreak-predicate)
22895 (setq-local
22896 fill-nobreak-predicate
22897 (org-uniquify
22898 (append fill-nobreak-predicate
22899 '(org-fill-line-break-nobreak-p
22900 org-fill-n-macro-as-item-nobreak-p
22901 org-fill-paragraph-with-timestamp-nobreak-p)))))
22902 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22903 (setq-local paragraph-start paragraph-ending)
22904 (setq-local paragraph-separate paragraph-ending))
22905 (setq-local fill-paragraph-function 'org-fill-paragraph)
22906 (setq-local auto-fill-inhibit-regexp nil)
22907 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22908 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22909 (setq-local comment-line-break-function 'org-comment-line-break-function))
22911 (defun org-fill-line-break-nobreak-p ()
22912 "Non-nil when a new line at point would create an Org line break."
22913 (save-excursion
22914 (skip-chars-backward "[ \t]")
22915 (skip-chars-backward "\\\\")
22916 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22918 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22919 "Non-nil when a new line at point would split a timestamp."
22920 (and (org-at-timestamp-p 'lax)
22921 (not (looking-at org-ts-regexp-both))))
22923 (defun org-fill-n-macro-as-item-nobreak-p ()
22924 "Non-nil when a new line at point would create a new list."
22925 ;; During export, a "n" macro followed by a dot or a closing
22926 ;; parenthesis can end up being parsed as a new list item.
22927 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22929 (declare-function message-in-body-p "message" ())
22930 (defvar orgtbl-line-start-regexp) ; From org-table.el
22931 (defun org-adaptive-fill-function ()
22932 "Compute a fill prefix for the current line.
22933 Return fill prefix, as a string, or nil if current line isn't
22934 meant to be filled. For convenience, if `adaptive-fill-regexp'
22935 matches in paragraphs or comments, use it."
22936 (catch 'exit
22937 (when (derived-mode-p 'message-mode)
22938 (save-excursion
22939 (beginning-of-line)
22940 (cond ((not (message-in-body-p)) (throw 'exit nil))
22941 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22942 ((looking-at message-cite-prefix-regexp)
22943 (throw 'exit (match-string-no-properties 0)))
22944 ((looking-at org-outline-regexp)
22945 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22946 (org-with-wide-buffer
22947 (unless (org-at-heading-p)
22948 (let* ((p (line-beginning-position))
22949 (element (save-excursion
22950 (beginning-of-line)
22951 (org-element-at-point)))
22952 (type (org-element-type element))
22953 (post-affiliated (org-element-property :post-affiliated element)))
22954 (unless (< p post-affiliated)
22955 (cl-case type
22956 (comment
22957 (save-excursion
22958 (beginning-of-line)
22959 (looking-at "[ \t]*")
22960 (concat (match-string 0) "# ")))
22961 (footnote-definition "")
22962 ((item plain-list)
22963 (make-string (org-list-item-body-column post-affiliated) ?\s))
22964 (paragraph
22965 ;; Fill prefix is usually the same as the current line,
22966 ;; unless the paragraph is at the beginning of an item.
22967 (let ((parent (org-element-property :parent element)))
22968 (save-excursion
22969 (beginning-of-line)
22970 (cond ((eq (org-element-type parent) 'item)
22971 (make-string (org-list-item-body-column
22972 (org-element-property :begin parent))
22973 ?\s))
22974 ((and adaptive-fill-regexp
22975 ;; Locally disable
22976 ;; `adaptive-fill-function' to let
22977 ;; `fill-context-prefix' handle
22978 ;; `adaptive-fill-regexp' variable.
22979 (let (adaptive-fill-function)
22980 (fill-context-prefix
22981 post-affiliated
22982 (org-element-property :end element)))))
22983 ((looking-at "[ \t]+") (match-string 0))
22984 (t "")))))
22985 (comment-block
22986 ;; Only fill contents if P is within block boundaries.
22987 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22988 (forward-line)
22989 (point)))
22990 (cend (save-excursion
22991 (goto-char (org-element-property :end element))
22992 (skip-chars-backward " \r\t\n")
22993 (line-beginning-position))))
22994 (when (and (>= p cbeg) (< p cend))
22995 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22996 (match-string 0)
22997 "")))))))))))
22999 (declare-function message-goto-body "message" ())
23000 (defvar message-cite-prefix-regexp) ; From message.el
23002 (defun org-fill-element (&optional justify)
23003 "Fill element at point, when applicable.
23005 This function only applies to comment blocks, comments, example
23006 blocks and paragraphs. Also, as a special case, re-align table
23007 when point is at one.
23009 If JUSTIFY is non-nil (interactively, with prefix argument),
23010 justify as well. If `sentence-end-double-space' is non-nil, then
23011 period followed by one space does not end a sentence, so don't
23012 break a line there. The variable `fill-column' controls the
23013 width for filling.
23015 For convenience, when point is at a plain list, an item or
23016 a footnote definition, try to fill the first paragraph within."
23017 (with-syntax-table org-mode-transpose-word-syntax-table
23018 ;; Move to end of line in order to get the first paragraph within
23019 ;; a plain list or a footnote definition.
23020 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
23021 ;; First check if point is in a blank line at the beginning of
23022 ;; the buffer. In that case, ignore filling.
23023 (cl-case (org-element-type element)
23024 ;; Use major mode filling function is src blocks.
23025 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23026 ;; Align Org tables, leave table.el tables as-is.
23027 (table-row (org-table-align) t)
23028 (table
23029 (when (eq (org-element-property :type element) 'org)
23030 (save-excursion
23031 (goto-char (org-element-property :post-affiliated element))
23032 (org-table-align)))
23034 (paragraph
23035 ;; Paragraphs may contain `line-break' type objects.
23036 (let ((beg (max (point-min)
23037 (org-element-property :contents-begin element)))
23038 (end (min (point-max)
23039 (org-element-property :contents-end element))))
23040 ;; Do nothing if point is at an affiliated keyword.
23041 (if (< (line-end-position) beg) t
23042 (when (derived-mode-p 'message-mode)
23043 ;; In `message-mode', do not fill following citation
23044 ;; in current paragraph nor text before message body.
23045 (let ((body-start (save-excursion (message-goto-body))))
23046 (when body-start (setq beg (max body-start beg))))
23047 (when (save-excursion
23048 (re-search-forward
23049 (concat "^" message-cite-prefix-regexp) end t))
23050 (setq end (match-beginning 0))))
23051 ;; Fill paragraph, taking line breaks into account.
23052 (save-excursion
23053 (goto-char beg)
23054 (let ((cuts (list beg)))
23055 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23056 (when (eq 'line-break
23057 (org-element-type
23058 (save-excursion (backward-char)
23059 (org-element-context))))
23060 (push (point) cuts)))
23061 (dolist (c (delq end cuts))
23062 (fill-region-as-paragraph c end justify)
23063 (setq end c))))
23064 t)))
23065 ;; Contents of `comment-block' type elements should be
23066 ;; filled as plain text, but only if point is within block
23067 ;; markers.
23068 (comment-block
23069 (let* ((case-fold-search t)
23070 (beg (save-excursion
23071 (goto-char (org-element-property :begin element))
23072 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23073 (forward-line)
23074 (point)))
23075 (end (save-excursion
23076 (goto-char (org-element-property :end element))
23077 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23078 (line-beginning-position))))
23079 (if (or (< (point) beg) (> (point) end)) t
23080 (fill-region-as-paragraph
23081 (save-excursion (end-of-line)
23082 (re-search-backward "^[ \t]*$" beg 'move)
23083 (line-beginning-position))
23084 (save-excursion (beginning-of-line)
23085 (re-search-forward "^[ \t]*$" end 'move)
23086 (line-beginning-position))
23087 justify))))
23088 ;; Fill comments.
23089 (comment
23090 (let ((begin (org-element-property :post-affiliated element))
23091 (end (org-element-property :end element)))
23092 (when (and (>= (point) begin) (<= (point) end))
23093 (let ((begin (save-excursion
23094 (end-of-line)
23095 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23096 (progn (forward-line) (point))
23097 begin)))
23098 (end (save-excursion
23099 (end-of-line)
23100 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23101 (1- (line-beginning-position))
23102 (skip-chars-backward " \r\t\n")
23103 (line-end-position)))))
23104 ;; Do not fill comments when at a blank line.
23105 (when (> end begin)
23106 (let ((fill-prefix
23107 (save-excursion
23108 (beginning-of-line)
23109 (looking-at "[ \t]*#")
23110 (let ((comment-prefix (match-string 0)))
23111 (goto-char (match-end 0))
23112 (if (looking-at adaptive-fill-regexp)
23113 (concat comment-prefix (match-string 0))
23114 (concat comment-prefix " "))))))
23115 (save-excursion
23116 (fill-region-as-paragraph begin end justify))))))
23118 ;; Ignore every other element.
23119 (otherwise t)))))
23121 (defun org-fill-paragraph (&optional justify region)
23122 "Fill element at point, when applicable.
23124 This function only applies to comment blocks, comments, example
23125 blocks and paragraphs. Also, as a special case, re-align table
23126 when point is at one.
23128 For convenience, when point is at a plain list, an item or
23129 a footnote definition, try to fill the first paragraph within.
23131 If JUSTIFY is non-nil (interactively, with prefix argument),
23132 justify as well. If `sentence-end-double-space' is non-nil, then
23133 period followed by one space does not end a sentence, so don't
23134 break a line there. The variable `fill-column' controls the
23135 width for filling.
23137 The REGION argument is non-nil if called interactively; in that
23138 case, if Transient Mark mode is enabled and the mark is active,
23139 fill each of the elements in the active region, instead of just
23140 filling the current element."
23141 (interactive (progn
23142 (barf-if-buffer-read-only)
23143 (list (if current-prefix-arg 'full) t)))
23144 (cond
23145 ((and (derived-mode-p 'message-mode)
23146 (or (not (message-in-body-p))
23147 (save-excursion (move-beginning-of-line 1)
23148 (looking-at message-cite-prefix-regexp))))
23149 ;; First ensure filling is correct in message-mode.
23150 (let ((fill-paragraph-function
23151 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23152 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23153 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23154 (paragraph-separate
23155 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23156 (fill-paragraph nil)))
23157 ((and region transient-mark-mode mark-active
23158 (not (eq (region-beginning) (region-end))))
23159 (let ((origin (point-marker))
23160 (start (region-beginning)))
23161 (unwind-protect
23162 (progn
23163 (goto-char (region-end))
23164 (while (> (point) start)
23165 (org-backward-paragraph)
23166 (org-fill-element justify)))
23167 (goto-char origin)
23168 (set-marker origin nil))))
23169 (t (org-fill-element justify))))
23170 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23172 (defun org-auto-fill-function ()
23173 "Auto-fill function."
23174 ;; Check if auto-filling is meaningful.
23175 (let ((fc (current-fill-column)))
23176 (when (and fc (> (current-column) fc))
23177 (let* ((fill-prefix (org-adaptive-fill-function))
23178 ;; Enforce empty fill prefix, if required. Otherwise, it
23179 ;; will be computed again.
23180 (adaptive-fill-mode (not (equal fill-prefix ""))))
23181 (when fill-prefix (do-auto-fill))))))
23183 (defun org-comment-line-break-function (&optional soft)
23184 "Break line at point and indent, continuing comment if within one.
23185 The inserted newline is marked hard if variable
23186 `use-hard-newlines' is true, unless optional argument SOFT is
23187 non-nil."
23188 (if soft (insert-and-inherit ?\n) (newline 1))
23189 (save-excursion (forward-char -1) (delete-horizontal-space))
23190 (delete-horizontal-space)
23191 (indent-to-left-margin)
23192 (insert-before-markers-and-inherit fill-prefix))
23195 ;;; Fixed Width Areas
23197 (defun org-toggle-fixed-width ()
23198 "Toggle fixed-width markup.
23200 Add or remove fixed-width markup on current line, whenever it
23201 makes sense. Return an error otherwise.
23203 If a region is active and if it contains only fixed-width areas
23204 or blank lines, remove all fixed-width markup in it. If the
23205 region contains anything else, convert all non-fixed-width lines
23206 to fixed-width ones.
23208 Blank lines at the end of the region are ignored unless the
23209 region only contains such lines."
23210 (interactive)
23211 (if (not (org-region-active-p))
23212 ;; No region:
23214 ;; Remove fixed width marker only in a fixed-with element.
23216 ;; Add fixed width maker in paragraphs, in blank lines after
23217 ;; elements or at the beginning of a headline or an inlinetask,
23218 ;; and before any one-line elements (e.g., a clock).
23219 (progn
23220 (beginning-of-line)
23221 (let* ((element (org-element-at-point))
23222 (type (org-element-type element)))
23223 (cond
23224 ((and (eq type 'fixed-width)
23225 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23226 (replace-match
23227 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23228 ((and (memq type '(babel-call clock comment diary-sexp headline
23229 horizontal-rule keyword paragraph
23230 planning))
23231 (<= (org-element-property :post-affiliated element) (point)))
23232 (skip-chars-forward " \t")
23233 (insert ": "))
23234 ((and (looking-at-p "[ \t]*$")
23235 (or (eq type 'inlinetask)
23236 (save-excursion
23237 (skip-chars-forward " \r\t\n")
23238 (<= (org-element-property :end element) (point)))))
23239 (delete-region (point) (line-end-position))
23240 (org-indent-line)
23241 (insert ": "))
23242 (t (user-error "Cannot insert a fixed-width line here")))))
23243 ;; Region active.
23244 (let* ((begin (save-excursion
23245 (goto-char (region-beginning))
23246 (line-beginning-position)))
23247 (end (copy-marker
23248 (save-excursion
23249 (goto-char (region-end))
23250 (unless (eolp) (beginning-of-line))
23251 (if (save-excursion (re-search-backward "\\S-" begin t))
23252 (progn (skip-chars-backward " \r\t\n") (point))
23253 (point)))))
23254 (all-fixed-width-p
23255 (catch 'not-all-p
23256 (save-excursion
23257 (goto-char begin)
23258 (skip-chars-forward " \r\t\n")
23259 (when (eobp) (throw 'not-all-p nil))
23260 (while (< (point) end)
23261 (let ((element (org-element-at-point)))
23262 (if (eq (org-element-type element) 'fixed-width)
23263 (goto-char (org-element-property :end element))
23264 (throw 'not-all-p nil))))
23265 t))))
23266 (if all-fixed-width-p
23267 (save-excursion
23268 (goto-char begin)
23269 (while (< (point) end)
23270 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23271 (replace-match
23272 "" nil nil nil
23273 (if (= (line-end-position) (match-end 0)) 0 1)))
23274 (forward-line)))
23275 (let ((min-ind (point-max)))
23276 ;; Find minimum indentation across all lines.
23277 (save-excursion
23278 (goto-char begin)
23279 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23280 (setq min-ind 0)
23281 (catch 'zerop
23282 (while (< (point) end)
23283 (unless (looking-at-p "[ \t]*$")
23284 (let ((ind (org-get-indentation)))
23285 (setq min-ind (min min-ind ind))
23286 (when (zerop ind) (throw 'zerop t))))
23287 (forward-line)))))
23288 ;; Loop over all lines and add fixed-width markup everywhere
23289 ;; but in fixed-width lines.
23290 (save-excursion
23291 (goto-char begin)
23292 (while (< (point) end)
23293 (cond
23294 ((org-at-heading-p)
23295 (insert ": ")
23296 (forward-line)
23297 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23298 (insert ":")
23299 (forward-line)))
23300 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23301 (let* ((element (org-element-at-point))
23302 (element-end (org-element-property :end element)))
23303 (if (eq (org-element-type element) 'fixed-width)
23304 (progn (goto-char element-end)
23305 (skip-chars-backward " \r\t\n")
23306 (forward-line))
23307 (let ((limit (min end element-end)))
23308 (while (< (point) limit)
23309 (org-move-to-column min-ind t)
23310 (insert ": ")
23311 (forward-line))))))
23313 (org-move-to-column min-ind t)
23314 (insert ": ")
23315 (forward-line)))))))
23316 (set-marker end nil))))
23319 ;;; Comments
23321 ;; Org comments syntax is quite complex. It requires the entire line
23322 ;; to be just a comment. Also, even with the right syntax at the
23323 ;; beginning of line, some elements (e.g., verse-block or
23324 ;; example-block) don't accept comments. Usual Emacs comment commands
23325 ;; cannot cope with those requirements. Therefore, Org replaces them.
23327 ;; Org still relies on `comment-dwim', but cannot trust
23328 ;; `comment-only-p'. So, `comment-region-function' and
23329 ;; `uncomment-region-function' both point
23330 ;; to`org-comment-or-uncomment-region'. Eventually,
23331 ;; `org-insert-comment' takes care of insertion of comments at the
23332 ;; beginning of line.
23334 ;; `org-setup-comments-handling' install comments related variables
23335 ;; during `org-mode' initialization.
23337 (defun org-setup-comments-handling ()
23338 (interactive)
23339 (setq-local comment-use-syntax nil)
23340 (setq-local comment-start "# ")
23341 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23342 (setq-local comment-insert-comment-function 'org-insert-comment)
23343 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23344 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23346 (defun org-insert-comment ()
23347 "Insert an empty comment above current line.
23348 If the line is empty, insert comment at its beginning. When
23349 point is within a source block, comment according to the related
23350 major mode."
23351 (if (let ((element (org-element-at-point)))
23352 (and (eq (org-element-type element) 'src-block)
23353 (< (save-excursion
23354 (goto-char (org-element-property :post-affiliated element))
23355 (line-end-position))
23356 (point))
23357 (> (save-excursion
23358 (goto-char (org-element-property :end element))
23359 (skip-chars-backward " \r\t\n")
23360 (line-beginning-position))
23361 (point))))
23362 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23363 (beginning-of-line)
23364 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23365 (open-line 1))
23366 (org-indent-line)
23367 (insert "# ")))
23369 (defvar comment-empty-lines) ; From newcomment.el.
23370 (defun org-comment-or-uncomment-region (beg end &rest _)
23371 "Comment or uncomment each non-blank line in the region.
23372 Uncomment each non-blank line between BEG and END if it only
23373 contains commented lines. Otherwise, comment them. If region is
23374 strictly within a source block, use appropriate comment syntax."
23375 (if (let ((element (org-element-at-point)))
23376 (and (eq (org-element-type element) 'src-block)
23377 (< (save-excursion
23378 (goto-char (org-element-property :post-affiliated element))
23379 (line-end-position))
23380 beg)
23381 (>= (save-excursion
23382 (goto-char (org-element-property :end element))
23383 (skip-chars-backward " \r\t\n")
23384 (line-beginning-position))
23385 end)))
23386 ;; Translate region boundaries for the Org buffer to the source
23387 ;; buffer.
23388 (let ((offset (- end beg)))
23389 (save-excursion
23390 (goto-char beg)
23391 (org-babel-do-in-edit-buffer
23392 (comment-or-uncomment-region (point) (+ offset (point))))))
23393 (save-restriction
23394 ;; Restrict region
23395 (narrow-to-region (save-excursion (goto-char beg)
23396 (skip-chars-forward " \r\t\n" end)
23397 (line-beginning-position))
23398 (save-excursion (goto-char end)
23399 (skip-chars-backward " \r\t\n" beg)
23400 (line-end-position)))
23401 (let ((uncommentp
23402 ;; UNCOMMENTP is non-nil when every non blank line between
23403 ;; BEG and END is a comment.
23404 (save-excursion
23405 (goto-char (point-min))
23406 (while (and (not (eobp))
23407 (let ((element (org-element-at-point)))
23408 (and (eq (org-element-type element) 'comment)
23409 (goto-char (min (point-max)
23410 (org-element-property
23411 :end element)))))))
23412 (eobp))))
23413 (if uncommentp
23414 ;; Only blank lines and comments in region: uncomment it.
23415 (save-excursion
23416 (goto-char (point-min))
23417 (while (not (eobp))
23418 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23419 (replace-match "" nil nil nil 1))
23420 (forward-line)))
23421 ;; Comment each line in region.
23422 (let ((min-indent (point-max)))
23423 ;; First find the minimum indentation across all lines.
23424 (save-excursion
23425 (goto-char (point-min))
23426 (while (and (not (eobp)) (not (zerop min-indent)))
23427 (unless (looking-at "[ \t]*$")
23428 (setq min-indent (min min-indent (current-indentation))))
23429 (forward-line)))
23430 ;; Then loop over all lines.
23431 (save-excursion
23432 (goto-char (point-min))
23433 (while (not (eobp))
23434 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23435 ;; Don't get fooled by invisible text (e.g. link path)
23436 ;; when moving to column MIN-INDENT.
23437 (let ((buffer-invisibility-spec nil))
23438 (org-move-to-column min-indent t))
23439 (insert comment-start))
23440 (forward-line)))))))))
23442 (defun org-comment-dwim (_arg)
23443 "Call `comment-dwim' within a source edit buffer if needed."
23444 (interactive "*P")
23445 (if (org-in-src-block-p)
23446 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23447 (call-interactively 'comment-dwim)))
23450 ;;; Timestamps API
23452 ;; This section contains tools to operate on timestamp objects, as
23453 ;; returned by, e.g. `org-element-context'.
23455 (defun org-timestamp--to-internal-time (timestamp &optional end)
23456 "Encode TIMESTAMP object into Emacs internal time.
23457 Use end of date range or time range when END is non-nil."
23458 (apply #'encode-time
23459 (cons 0
23460 (mapcar
23461 (lambda (prop) (or (org-element-property prop timestamp) 0))
23462 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23463 '(:minute-start :hour-start :day-start :month-start
23464 :year-start))))))
23466 (defun org-timestamp-has-time-p (timestamp)
23467 "Non-nil when TIMESTAMP has a time specified."
23468 (org-element-property :hour-start timestamp))
23470 (defun org-timestamp-format (timestamp format &optional end utc)
23471 "Format a TIMESTAMP object into a string.
23473 FORMAT is a format specifier to be passed to
23474 `format-time-string'.
23476 When optional argument END is non-nil, use end of date-range or
23477 time-range, if possible.
23479 When optional argument UTC is non-nil, time will be expressed as
23480 Universal Time."
23481 (format-time-string
23482 format (org-timestamp--to-internal-time timestamp end)
23483 (and utc t)))
23485 (defun org-timestamp-split-range (timestamp &optional end)
23486 "Extract a TIMESTAMP object from a date or time range.
23488 END, when non-nil, means extract the end of the range.
23489 Otherwise, extract its start.
23491 Return a new timestamp object."
23492 (let ((type (org-element-property :type timestamp)))
23493 (if (memq type '(active inactive diary)) timestamp
23494 (let ((split-ts (org-element-copy timestamp)))
23495 ;; Set new type.
23496 (org-element-put-property
23497 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23498 ;; Copy start properties over end properties if END is
23499 ;; non-nil. Otherwise, copy end properties over `start' ones.
23500 (let ((p-alist '((:minute-start . :minute-end)
23501 (:hour-start . :hour-end)
23502 (:day-start . :day-end)
23503 (:month-start . :month-end)
23504 (:year-start . :year-end))))
23505 (dolist (p-cell p-alist)
23506 (org-element-put-property
23507 split-ts
23508 (funcall (if end #'car #'cdr) p-cell)
23509 (org-element-property
23510 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23511 ;; Eventually refresh `:raw-value'.
23512 (org-element-put-property split-ts :raw-value nil)
23513 (org-element-put-property
23514 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23516 (defun org-timestamp-translate (timestamp &optional boundary)
23517 "Translate TIMESTAMP object to custom format.
23519 Format string is defined in `org-time-stamp-custom-formats',
23520 which see.
23522 When optional argument BOUNDARY is non-nil, it is either the
23523 symbol `start' or `end'. In this case, only translate the
23524 starting or ending part of TIMESTAMP if it is a date or time
23525 range. Otherwise, translate both parts.
23527 Return timestamp as-is if `org-display-custom-times' is nil or if
23528 it has a `diary' type."
23529 (let ((type (org-element-property :type timestamp)))
23530 (if (or (not org-display-custom-times) (eq type 'diary))
23531 (org-element-interpret-data timestamp)
23532 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23533 org-time-stamp-custom-formats)))
23534 (if (and (not boundary) (memq type '(active-range inactive-range)))
23535 (concat (org-timestamp-format timestamp fmt)
23536 "--"
23537 (org-timestamp-format timestamp fmt t))
23538 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23542 ;;; Other stuff.
23544 (defvar reftex-docstruct-symbol)
23545 (defvar org--rds)
23547 (defun org-reftex-citation ()
23548 "Use reftex-citation to insert a citation into the buffer.
23549 This looks for a line like
23551 #+BIBLIOGRAPHY: foo plain option:-d
23553 and derives from it that foo.bib is the bibliography file relevant
23554 for this document. It then installs the necessary environment for RefTeX
23555 to work in this buffer and calls `reftex-citation' to insert a citation
23556 into the buffer.
23558 Export of such citations to both LaTeX and HTML is handled by the contributed
23559 package ox-bibtex by Taru Karttunen."
23560 (interactive)
23561 (let ((reftex-docstruct-symbol 'org--rds)
23562 org--rds bib)
23563 (org-with-wide-buffer
23564 (let ((case-fold-search t)
23565 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23566 (if (not (save-excursion
23567 (or (re-search-forward re nil t)
23568 (re-search-backward re nil t))))
23569 (user-error "No bibliography defined in file")
23570 (setq bib (concat (match-string 1) ".bib")
23571 org--rds (list (list 'bib bib))))))
23572 (call-interactively 'reftex-citation)))
23574 ;;;; Functions extending outline functionality
23576 (defun org-beginning-of-line (&optional n)
23577 "Go to the beginning of the current visible line.
23579 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23580 tags on the first attempt, and only move to after the tags when
23581 the cursor is already beyond the end of the headline.
23583 With argument N not nil or 1, move forward N - 1 lines first."
23584 (interactive "^p")
23585 (let ((origin (point))
23586 (special (pcase org-special-ctrl-a/e
23587 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23588 deactivate-mark)
23589 ;; First move to a visible line.
23590 (if (bound-and-true-p visual-line-mode)
23591 (beginning-of-visual-line n)
23592 (move-beginning-of-line n)
23593 ;; `move-beginning-of-line' may leave point after invisible
23594 ;; characters if line starts with such of these (e.g., with
23595 ;; a link at column 0). Really move to the beginning of the
23596 ;; current visible line.
23597 (beginning-of-line))
23598 (cond
23599 ;; No special behavior. Point is already at the beginning of
23600 ;; a line, logical or visual.
23601 ((not special))
23602 ;; `beginning-of-visual-line' left point before logical beginning
23603 ;; of line: point is at the beginning of a visual line. Bail
23604 ;; out.
23605 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23606 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23607 ;; At a headline, special position is before the title, but
23608 ;; after any TODO keyword or priority cookie.
23609 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23610 (line-end-position)))
23611 (bol (point)))
23612 (if (eq special 'reversed)
23613 (when (and (= origin bol) (eq last-command this-command))
23614 (goto-char refpos))
23615 (when (or (> origin refpos) (= origin bol))
23616 (goto-char refpos)))))
23617 ((and (looking-at org-list-full-item-re)
23618 (memq (org-element-type (save-match-data (org-element-at-point)))
23619 '(item plain-list)))
23620 ;; Set special position at first white space character after
23621 ;; bullet, and check-box, if any.
23622 (let ((after-bullet
23623 (let ((box (match-end 3)))
23624 (cond ((not box) (match-end 1))
23625 ((eq (char-after box) ?\s) (1+ box))
23626 (t box)))))
23627 (if (eq special 'reversed)
23628 (when (and (= (point) origin) (eq last-command this-command))
23629 (goto-char after-bullet))
23630 (when (or (> origin after-bullet) (= (point) origin))
23631 (goto-char after-bullet)))))
23632 ;; No special context. Point is already at beginning of line.
23633 (t nil))))
23635 (defun org-end-of-line (&optional n)
23636 "Go to the end of the line, but before ellipsis, if any.
23638 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23639 tags on the first attempt, and only move to after the tags when
23640 the cursor is already beyond the end of the headline.
23642 With argument N not nil or 1, move forward N - 1 lines first."
23643 (interactive "^p")
23644 (let ((origin (point))
23645 (special (pcase org-special-ctrl-a/e
23646 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23647 deactivate-mark)
23648 ;; First move to a visible line.
23649 (if (bound-and-true-p visual-line-mode)
23650 (beginning-of-visual-line n)
23651 (move-beginning-of-line n))
23652 (cond
23653 ;; At a headline, with tags.
23654 ((and special
23655 (save-excursion
23656 (beginning-of-line)
23657 (let ((case-fold-search nil))
23658 (looking-at org-complex-heading-regexp)))
23659 (match-end 5))
23660 (let ((tags (save-excursion
23661 (goto-char (match-beginning 5))
23662 (skip-chars-backward " \t")
23663 (point)))
23664 (visual-end (and (bound-and-true-p visual-line-mode)
23665 (save-excursion
23666 (end-of-visual-line)
23667 (point)))))
23668 ;; If `end-of-visual-line' brings us before end of line or
23669 ;; even tags, i.e., the headline spans over multiple visual
23670 ;; lines, move there.
23671 (cond ((and visual-end
23672 (< visual-end tags)
23673 (<= origin visual-end))
23674 (goto-char visual-end))
23675 ((eq special 'reversed)
23676 (if (and (= origin (line-end-position))
23677 (eq this-command last-command))
23678 (goto-char tags)
23679 (end-of-line)))
23681 (if (or (< origin tags) (= origin (line-end-position)))
23682 (goto-char tags)
23683 (end-of-line))))))
23684 ((bound-and-true-p visual-line-mode)
23685 (let ((bol (line-beginning-position)))
23686 (end-of-visual-line)
23687 ;; If `end-of-visual-line' gets us past the ellipsis at the
23688 ;; end of a line, backtrack and use `end-of-line' instead.
23689 (when (/= bol (line-beginning-position))
23690 (goto-char bol)
23691 (end-of-line))))
23692 (t (end-of-line)))))
23694 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23695 (define-key org-mode-map "\C-e" 'org-end-of-line)
23697 (defun org-backward-sentence (&optional _arg)
23698 "Go to beginning of sentence, or beginning of table field.
23699 This will call `backward-sentence' or `org-table-beginning-of-field',
23700 depending on context."
23701 (interactive)
23702 (let* ((element (org-element-at-point))
23703 (contents-begin (org-element-property :contents-begin element))
23704 (table (org-element-lineage element '(table) t)))
23705 (if (and table
23706 (> (point) contents-begin)
23707 (<= (point) (org-element-property :contents-end table)))
23708 (call-interactively #'org-table-beginning-of-field)
23709 (save-restriction
23710 (when (and contents-begin
23711 (< (point-min) contents-begin)
23712 (> (point) contents-begin))
23713 (narrow-to-region contents-begin
23714 (org-element-property :contents-end element)))
23715 (call-interactively #'backward-sentence)))))
23717 (defun org-forward-sentence (&optional _arg)
23718 "Go to end of sentence, or end of table field.
23719 This will call `forward-sentence' or `org-table-end-of-field',
23720 depending on context."
23721 (interactive)
23722 (let* ((element (org-element-at-point))
23723 (contents-end (org-element-property :contents-end element))
23724 (table (org-element-lineage element '(table) t)))
23725 (if (and table
23726 (>= (point) (org-element-property :contents-begin table))
23727 (< (point) contents-end))
23728 (call-interactively #'org-table-end-of-field)
23729 (save-restriction
23730 (when (and contents-end
23731 (> (point-max) contents-end)
23732 ;; Skip blank lines between elements.
23733 (< (org-element-property :end element)
23734 (save-excursion (goto-char contents-end)
23735 (skip-chars-forward " \r\t\n"))))
23736 (narrow-to-region (org-element-property :contents-begin element)
23737 contents-end))
23738 (call-interactively #'forward-sentence)))))
23740 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23741 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23743 (defun org-kill-line (&optional _arg)
23744 "Kill line, to tags or end of line."
23745 (interactive)
23746 (cond
23747 ((or (not org-special-ctrl-k)
23748 (bolp)
23749 (not (org-at-heading-p)))
23750 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23751 org-ctrl-k-protect-subtree
23752 (or (eq org-ctrl-k-protect-subtree 'error)
23753 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23754 (user-error "C-k aborted as it would kill a hidden subtree"))
23755 (call-interactively
23756 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23757 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23758 (kill-region (point) (match-beginning 1))
23759 (org-set-tags nil t))
23760 (t (kill-region (point) (point-at-eol)))))
23762 (define-key org-mode-map "\C-k" 'org-kill-line)
23764 (defun org-yank (&optional arg)
23765 "Yank. If the kill is a subtree, treat it specially.
23766 This command will look at the current kill and check if is a single
23767 subtree, or a series of subtrees[1]. If it passes the test, and if the
23768 cursor is at the beginning of a line or after the stars of a currently
23769 empty headline, then the yank is handled specially. How exactly depends
23770 on the value of the following variables.
23772 `org-yank-folded-subtrees'
23773 By default, this variable is non-nil, which results in
23774 subtree(s) being folded after insertion, except if doing so
23775 would swallow text after the yanked text.
23777 `org-yank-adjusted-subtrees'
23778 When non-nil (the default value is nil), the subtree will be
23779 promoted or demoted in order to fit into the local outline tree
23780 structure, which means that the level will be adjusted so that it
23781 becomes the smaller one of the two *visible* surrounding headings.
23783 Any prefix to this command will cause `yank' to be called directly with
23784 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23785 will just
23786 plainly yank the text as it is.
23788 \[1] The test checks if the first non-white line is a heading
23789 and if there are no other headings with fewer stars."
23790 (interactive "P")
23791 (org-yank-generic 'yank arg))
23793 (defun org-yank-generic (command arg)
23794 "Perform some yank-like command.
23796 This function implements the behavior described in the `org-yank'
23797 documentation. However, it has been generalized to work for any
23798 interactive command with similar behavior."
23800 ;; pretend to be command COMMAND
23801 (setq this-command command)
23803 (if arg
23804 (call-interactively command)
23806 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23807 (and (org-kill-is-subtree-p)
23808 (or (bolp)
23809 (and (looking-at "[ \t]*$")
23810 (string-match
23811 "\\`\\*+\\'"
23812 (buffer-substring (point-at-bol) (point)))))))
23813 swallowp)
23814 (cond
23815 ((and subtreep org-yank-folded-subtrees)
23816 (let ((beg (point))
23817 end)
23818 (if (and subtreep org-yank-adjusted-subtrees)
23819 (org-paste-subtree nil nil 'for-yank)
23820 (call-interactively command))
23822 (setq end (point))
23823 (goto-char beg)
23824 (when (and (bolp) subtreep
23825 (not (setq swallowp
23826 (org-yank-folding-would-swallow-text beg end))))
23827 (org-with-limited-levels
23828 (or (looking-at org-outline-regexp)
23829 (re-search-forward org-outline-regexp-bol end t))
23830 (while (and (< (point) end) (looking-at org-outline-regexp))
23831 (outline-hide-subtree)
23832 (org-cycle-show-empty-lines 'folded)
23833 (condition-case nil
23834 (outline-forward-same-level 1)
23835 (error (goto-char end))))))
23836 (when swallowp
23837 (message
23838 "Inserted text not folded because that would swallow text"))
23840 (goto-char end)
23841 (skip-chars-forward " \t\n\r")
23842 (beginning-of-line 1)
23843 (push-mark beg 'nomsg)))
23844 ((and subtreep org-yank-adjusted-subtrees)
23845 (let ((beg (point-at-bol)))
23846 (org-paste-subtree nil nil 'for-yank)
23847 (push-mark beg 'nomsg)))
23849 (call-interactively command))))))
23851 (defun org-yank-folding-would-swallow-text (beg end)
23852 "Would hide-subtree at BEG swallow any text after END?"
23853 (let (level)
23854 (org-with-limited-levels
23855 (save-excursion
23856 (goto-char beg)
23857 (when (or (looking-at org-outline-regexp)
23858 (re-search-forward org-outline-regexp-bol end t))
23859 (setq level (org-outline-level)))
23860 (goto-char end)
23861 (skip-chars-forward " \t\r\n\v\f")
23862 (not (or (eobp)
23863 (and (bolp) (looking-at-p org-outline-regexp)
23864 (<= (org-outline-level) level))))))))
23866 (define-key org-mode-map "\C-y" 'org-yank)
23868 (defun org-truely-invisible-p ()
23869 "Check if point is at a character currently not visible.
23870 This version does not only check the character property, but also
23871 `visible-mode'."
23872 (unless (bound-and-true-p visible-mode)
23873 (org-invisible-p)))
23875 (defun org-invisible-p2 ()
23876 "Check if point is at a character currently not visible.
23878 If the point is at EOL (and not at the beginning of a buffer too),
23879 move it back by one char before doing this check."
23880 (save-excursion
23881 (when (and (eolp) (not (bobp)))
23882 (backward-char 1))
23883 (org-invisible-p)))
23885 (defun org-back-to-heading (&optional invisible-ok)
23886 "Call `outline-back-to-heading', but provide a better error message."
23887 (condition-case nil
23888 (outline-back-to-heading invisible-ok)
23889 (error (error "Before first headline at position %d in buffer %s"
23890 (point) (current-buffer)))))
23892 (defun org-before-first-heading-p ()
23893 "Before first heading?"
23894 (save-excursion
23895 (end-of-line)
23896 (null (re-search-backward org-outline-regexp-bol nil t))))
23898 (defun org-at-heading-p (&optional ignored)
23899 (outline-on-heading-p t))
23901 (defun org-in-commented-heading-p (&optional no-inheritance)
23902 "Non-nil if point is under a commented heading.
23903 This function also checks ancestors of the current headline,
23904 unless optional argument NO-INHERITANCE is non-nil."
23905 (cond
23906 ((org-before-first-heading-p) nil)
23907 ((let ((headline (nth 4 (org-heading-components))))
23908 (and headline
23909 (let ((case-fold-search nil))
23910 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23911 headline)))))
23912 (no-inheritance nil)
23914 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23916 (defun org-at-comment-p nil
23917 "Is cursor in a commented line?"
23918 (save-excursion
23919 (save-match-data
23920 (beginning-of-line)
23921 (looking-at "^[ \t]*# "))))
23923 (defun org-at-drawer-p nil
23924 "Is cursor at a drawer keyword?"
23925 (save-excursion
23926 (move-beginning-of-line 1)
23927 (looking-at org-drawer-regexp)))
23929 (defun org-at-block-p nil
23930 "Is cursor at a block keyword?"
23931 (save-excursion
23932 (move-beginning-of-line 1)
23933 (looking-at org-block-regexp)))
23935 (defun org-point-at-end-of-empty-headline ()
23936 "If point is at the end of an empty headline, return t, else nil.
23937 If the heading only contains a TODO keyword, it is still still considered
23938 empty."
23939 (let ((case-fold-search nil))
23940 (and (looking-at "[ \t]*$")
23941 org-todo-line-regexp
23942 (save-excursion
23943 (beginning-of-line)
23944 (looking-at org-todo-line-regexp)
23945 (string= (match-string 3) "")))))
23947 (defun org-at-heading-or-item-p ()
23948 (or (org-at-heading-p) (org-at-item-p)))
23950 (defun org-at-target-p ()
23951 (or (org-in-regexp org-radio-target-regexp)
23952 (org-in-regexp org-target-regexp)))
23953 ;; Compatibility alias with Org versions < 7.8.03
23954 (defalias 'org-on-target-p 'org-at-target-p)
23956 (defun org-up-heading-all (arg)
23957 "Move to the heading line of which the present line is a subheading.
23958 This function considers both visible and invisible heading lines.
23959 With argument, move up ARG levels."
23960 (outline-up-heading arg t))
23962 (defun org-up-heading-safe ()
23963 "Move to the heading line of which the present line is a subheading.
23964 This version will not throw an error. It will return the level of the
23965 headline found, or nil if no higher level is found.
23967 Also, this function will be a lot faster than `outline-up-heading',
23968 because it relies on stars being the outline starters. This can really
23969 make a significant difference in outlines with very many siblings."
23970 (when (ignore-errors (org-back-to-heading t))
23971 (let ((level-up (1- (funcall outline-level))))
23972 (and (> level-up 0)
23973 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23974 (funcall outline-level)))))
23976 (defun org-first-sibling-p ()
23977 "Is this heading the first child of its parents?"
23978 (interactive)
23979 (let ((re org-outline-regexp-bol)
23980 level l)
23981 (unless (org-at-heading-p t)
23982 (user-error "Not at a heading"))
23983 (setq level (funcall outline-level))
23984 (save-excursion
23985 (if (not (re-search-backward re nil t))
23987 (setq l (funcall outline-level))
23988 (< l level)))))
23990 (defun org-goto-sibling (&optional previous)
23991 "Goto the next sibling, even if it is invisible.
23992 When PREVIOUS is set, go to the previous sibling instead. Returns t
23993 when a sibling was found. When none is found, return nil and don't
23994 move point."
23995 (let ((fun (if previous 're-search-backward 're-search-forward))
23996 (pos (point))
23997 (re org-outline-regexp-bol)
23998 level l)
23999 (when (ignore-errors (org-back-to-heading t))
24000 (setq level (funcall outline-level))
24001 (catch 'exit
24002 (or previous (forward-char 1))
24003 (while (funcall fun re nil t)
24004 (setq l (funcall outline-level))
24005 (when (< l level) (goto-char pos) (throw 'exit nil))
24006 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24007 (goto-char pos)
24008 nil))))
24010 (defun org-show-siblings ()
24011 "Show all siblings of the current headline."
24012 (save-excursion
24013 (while (org-goto-sibling) (org-flag-heading nil)))
24014 (save-excursion
24015 (while (org-goto-sibling 'previous)
24016 (org-flag-heading nil))))
24018 (defun org-goto-first-child ()
24019 "Goto the first child, even if it is invisible.
24020 Return t when a child was found. Otherwise don't move point and
24021 return nil."
24022 (let (level (pos (point)) (re org-outline-regexp-bol))
24023 (when (ignore-errors (org-back-to-heading t))
24024 (setq level (outline-level))
24025 (forward-char 1)
24026 (if (and (re-search-forward re nil t) (> (outline-level) level))
24027 (progn (goto-char (match-beginning 0)) t)
24028 (goto-char pos) nil))))
24030 (defun org-show-hidden-entry ()
24031 "Show an entry where even the heading is hidden."
24032 (save-excursion
24033 (org-show-entry)))
24035 (defun org-flag-heading (flag &optional entry)
24036 "Flag the current heading. FLAG non-nil means make invisible.
24037 When ENTRY is non-nil, show the entire entry."
24038 (save-excursion
24039 (org-back-to-heading t)
24040 ;; Check if we should show the entire entry
24041 (if entry
24042 (progn
24043 (org-show-entry)
24044 (save-excursion
24045 (and (outline-next-heading)
24046 (org-flag-heading nil))))
24047 (outline-flag-region (max (point-min) (1- (point)))
24048 (save-excursion (outline-end-of-heading) (point))
24049 flag))))
24051 (defun org-get-next-sibling ()
24052 "Move to next heading of the same level, and return point.
24053 If there is no such heading, return nil.
24054 This is like outline-next-sibling, but invisible headings are ok."
24055 (let ((level (funcall outline-level)))
24056 (outline-next-heading)
24057 (while (and (not (eobp)) (> (funcall outline-level) level))
24058 (outline-next-heading))
24059 (unless (or (eobp) (< (funcall outline-level) level))
24060 (point))))
24062 (defun org-get-last-sibling ()
24063 "Move to previous heading of the same level, and return point.
24064 If there is no such heading, return nil."
24065 (let ((opoint (point))
24066 (level (funcall outline-level)))
24067 (outline-previous-heading)
24068 (when (and (/= (point) opoint) (outline-on-heading-p t))
24069 (while (and (> (funcall outline-level) level)
24070 (not (bobp)))
24071 (outline-previous-heading))
24072 (unless (< (funcall outline-level) level)
24073 (point)))))
24075 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24076 "Goto to the end of a subtree."
24077 ;; This contains an exact copy of the original function, but it uses
24078 ;; `org-back-to-heading', to make it work also in invisible
24079 ;; trees. And is uses an invisible-ok argument.
24080 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24081 ;; Furthermore, when used inside Org, finding the end of a large subtree
24082 ;; with many children and grandchildren etc, this can be much faster
24083 ;; than the outline version.
24084 (org-back-to-heading invisible-ok)
24085 (let ((first t)
24086 (level (funcall outline-level)))
24087 (if (and (derived-mode-p 'org-mode) (< level 1000))
24088 ;; A true heading (not a plain list item), in Org
24089 ;; This means we can easily find the end by looking
24090 ;; only for the right number of stars. Using a regexp to do
24091 ;; this is so much faster than using a Lisp loop.
24092 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24093 (forward-char 1)
24094 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24095 ;; something else, do it the slow way
24096 (while (and (not (eobp))
24097 (or first (> (funcall outline-level) level)))
24098 (setq first nil)
24099 (outline-next-heading)))
24100 (unless to-heading
24101 (when (memq (preceding-char) '(?\n ?\^M))
24102 ;; Go to end of line before heading
24103 (forward-char -1)
24104 (when (memq (preceding-char) '(?\n ?\^M))
24105 ;; leave blank line before heading
24106 (forward-char -1)))))
24107 (point))
24109 (defun org-end-of-meta-data (&optional full)
24110 "Skip planning line and properties drawer in current entry.
24111 When optional argument FULL is non-nil, also skip empty lines,
24112 clocking lines and regular drawers at the beginning of the
24113 entry."
24114 (org-back-to-heading t)
24115 (forward-line)
24116 (when (looking-at-p org-planning-line-re) (forward-line))
24117 (when (looking-at org-property-drawer-re)
24118 (goto-char (match-end 0))
24119 (forward-line))
24120 (when (and full (not (org-at-heading-p)))
24121 (catch 'exit
24122 (let ((end (save-excursion (outline-next-heading) (point)))
24123 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24124 (while (not (eobp))
24125 (cond ((looking-at-p org-drawer-regexp)
24126 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24127 (forward-line)
24128 (throw 'exit t)))
24129 ((looking-at-p re) (forward-line))
24130 (t (throw 'exit t))))))))
24132 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24133 "Move forward to the ARG'th subheading at same level as this one.
24134 Stop at the first and last subheadings of a superior heading.
24135 Normally this only looks at visible headings, but when INVISIBLE-OK is
24136 non-nil it will also look at invisible ones."
24137 (interactive "p")
24138 (let ((backward? (and arg (< arg 0))))
24139 (if (org-before-first-heading-p)
24140 (if backward? (goto-char (point-min)) (outline-next-heading))
24141 (org-back-to-heading invisible-ok)
24142 (unless backward? (end-of-line)) ;do not match current headline
24143 (let ((level (- (match-end 0) (match-beginning 0) 1))
24144 (f (if backward? #'re-search-backward #'re-search-forward))
24145 (count (if arg (abs arg) 1))
24146 (result (point)))
24147 (while (and (> count 0)
24148 (funcall f org-outline-regexp-bol nil 'move))
24149 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24150 (cond ((< l level) (setq count 0))
24151 ((and (= l level)
24152 (or invisible-ok
24153 (not (org-invisible-p
24154 (line-beginning-position)))))
24155 (cl-decf count)
24156 (when (= l level) (setq result (point)))))))
24157 (goto-char result))
24158 (beginning-of-line))))
24160 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24161 "Move backward to the ARG'th subheading at same level as this one.
24162 Stop at the first and last subheadings of a superior heading."
24163 (interactive "p")
24164 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24166 (defun org-next-visible-heading (arg)
24167 "Move to the next visible heading.
24169 This function wraps `outline-next-visible-heading' with
24170 `org-with-limited-levels' in order to skip over inline tasks and
24171 respect customization of `org-odd-levels-only'."
24172 (interactive "p")
24173 (org-with-limited-levels
24174 (outline-next-visible-heading arg)))
24176 (defun org-previous-visible-heading (arg)
24177 "Move to the previous visible heading.
24179 This function wraps `outline-previous-visible-heading' with
24180 `org-with-limited-levels' in order to skip over inline tasks and
24181 respect customization of `org-odd-levels-only'."
24182 (interactive "p")
24183 (org-with-limited-levels
24184 (outline-previous-visible-heading arg)))
24186 (defun org-next-block (arg &optional backward block-regexp)
24187 "Jump to the next block.
24189 With a prefix argument ARG, jump forward ARG many blocks.
24191 When BACKWARD is non-nil, jump to the previous block.
24193 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24194 Match data is set according to this regexp when the function
24195 returns.
24197 Return point at beginning of the opening line of found block.
24198 Throw an error if no block is found."
24199 (interactive "p")
24200 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24201 (case-fold-search t)
24202 (search-fn (if backward #'re-search-backward #'re-search-forward))
24203 (count (or arg 1))
24204 (origin (point))
24205 last-element)
24206 (if backward (beginning-of-line) (end-of-line))
24207 (while (and (> count 0) (funcall search-fn re nil t))
24208 (let ((element (save-excursion
24209 (goto-char (match-beginning 0))
24210 (save-match-data (org-element-at-point)))))
24211 (when (and (memq (org-element-type element)
24212 '(center-block comment-block dynamic-block
24213 example-block export-block quote-block
24214 special-block src-block verse-block))
24215 (<= (match-beginning 0)
24216 (org-element-property :post-affiliated element)))
24217 (setq last-element element)
24218 (cl-decf count))))
24219 (if (= count 0)
24220 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24221 (save-match-data (org-show-context)))
24222 (goto-char origin)
24223 (user-error "No %s code blocks" (if backward "previous" "further")))))
24225 (defun org-previous-block (arg &optional block-regexp)
24226 "Jump to the previous block.
24227 With a prefix argument ARG, jump backward ARG many source blocks.
24228 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24229 (interactive "p")
24230 (org-next-block arg t block-regexp))
24232 (defun org-forward-paragraph ()
24233 "Move forward to beginning of next paragraph or equivalent.
24235 The function moves point to the beginning of the next visible
24236 structural element, which can be a paragraph, a table, a list
24237 item, etc. It also provides some special moves for convenience:
24239 - On an affiliated keyword, jump to the beginning of the
24240 relative element.
24241 - On an item or a footnote definition, move to the second
24242 element inside, if any.
24243 - On a table or a property drawer, jump after it.
24244 - On a verse or source block, stop after blank lines."
24245 (interactive)
24246 (when (eobp) (user-error "Cannot move further down"))
24247 (let* ((deactivate-mark nil)
24248 (element (org-element-at-point))
24249 (type (org-element-type element))
24250 (post-affiliated (org-element-property :post-affiliated element))
24251 (contents-begin (org-element-property :contents-begin element))
24252 (contents-end (org-element-property :contents-end element))
24253 (end (let ((end (org-element-property :end element)) (parent element))
24254 (while (and (setq parent (org-element-property :parent parent))
24255 (= (org-element-property :contents-end parent) end))
24256 (setq end (org-element-property :end parent)))
24257 end)))
24258 (cond ((not element)
24259 (skip-chars-forward " \r\t\n")
24260 (or (eobp) (beginning-of-line)))
24261 ;; On affiliated keywords, move to element's beginning.
24262 ((< (point) post-affiliated)
24263 (goto-char post-affiliated))
24264 ;; At a table row, move to the end of the table. Similarly,
24265 ;; at a node property, move to the end of the property
24266 ;; drawer.
24267 ((memq type '(node-property table-row))
24268 (goto-char (org-element-property
24269 :end (org-element-property :parent element))))
24270 ((memq type '(property-drawer table)) (goto-char end))
24271 ;; Consider blank lines as separators in verse and source
24272 ;; blocks to ease editing.
24273 ((memq type '(src-block verse-block))
24274 (when (eq type 'src-block)
24275 (setq contents-end
24276 (save-excursion (goto-char end)
24277 (skip-chars-backward " \r\t\n")
24278 (line-beginning-position))))
24279 (beginning-of-line)
24280 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24281 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24282 (goto-char end)
24283 (skip-chars-forward " \r\t\n")
24284 (if (= (point) contents-end) (goto-char end)
24285 (beginning-of-line))))
24286 ;; With no contents, just skip element.
24287 ((not contents-begin) (goto-char end))
24288 ;; If contents are invisible, skip the element altogether.
24289 ((org-invisible-p (line-end-position))
24290 (cl-case type
24291 (headline
24292 (org-with-limited-levels (outline-next-visible-heading 1)))
24293 ;; At a plain list, make sure we move to the next item
24294 ;; instead of skipping the whole list.
24295 (plain-list (forward-char)
24296 (org-forward-paragraph))
24297 (otherwise (goto-char end))))
24298 ((>= (point) contents-end) (goto-char end))
24299 ((>= (point) contents-begin)
24300 ;; This can only happen on paragraphs and plain lists.
24301 (cl-case type
24302 (paragraph (goto-char end))
24303 ;; At a plain list, try to move to second element in
24304 ;; first item, if possible.
24305 (plain-list (end-of-line)
24306 (org-forward-paragraph))))
24307 ;; When contents start on the middle of a line (e.g. in
24308 ;; items and footnote definitions), try to reach first
24309 ;; element starting after current line.
24310 ((> (line-end-position) contents-begin)
24311 (end-of-line)
24312 (org-forward-paragraph))
24313 (t (goto-char contents-begin)))))
24315 (defun org-backward-paragraph ()
24316 "Move backward to start of previous paragraph or equivalent.
24318 The function moves point to the beginning of the current
24319 structural element, which can be a paragraph, a table, a list
24320 item, etc., or to the beginning of the previous visible one if
24321 point is already there. It also provides some special moves for
24322 convenience:
24324 - On an affiliated keyword, jump to the first one.
24325 - On a table or a property drawer, move to its beginning.
24326 - On a verse or source block, stop before blank lines."
24327 (interactive)
24328 (when (bobp) (user-error "Cannot move further up"))
24329 (let* ((deactivate-mark nil)
24330 (element (org-element-at-point))
24331 (type (org-element-type element))
24332 (contents-begin (org-element-property :contents-begin element))
24333 (contents-end (org-element-property :contents-end element))
24334 (post-affiliated (org-element-property :post-affiliated element))
24335 (begin (org-element-property :begin element)))
24336 (cond
24337 ((not element) (goto-char (point-min)))
24338 ((= (point) begin)
24339 (backward-char)
24340 (org-backward-paragraph))
24341 ((<= (point) post-affiliated) (goto-char begin))
24342 ((memq type '(node-property table-row))
24343 (goto-char (org-element-property
24344 :post-affiliated (org-element-property :parent element))))
24345 ((memq type '(property-drawer table)) (goto-char begin))
24346 ((memq type '(src-block verse-block))
24347 (when (eq type 'src-block)
24348 (setq contents-begin
24349 (save-excursion (goto-char begin) (forward-line) (point))))
24350 (if (= (point) contents-begin) (goto-char post-affiliated)
24351 ;; Inside a verse block, see blank lines as paragraph
24352 ;; separators.
24353 (let ((origin (point)))
24354 (skip-chars-backward " \r\t\n" contents-begin)
24355 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24356 (skip-chars-forward " \r\t\n" origin)
24357 (if (= (point) origin) (goto-char contents-begin)
24358 (beginning-of-line))))))
24359 ((not contents-begin) (goto-char (or post-affiliated begin)))
24360 ((eq type 'paragraph)
24361 (goto-char contents-begin)
24362 ;; When at first paragraph in an item or a footnote definition,
24363 ;; move directly to beginning of line.
24364 (let ((parent-contents
24365 (org-element-property
24366 :contents-begin (org-element-property :parent element))))
24367 (when (and parent-contents (= parent-contents contents-begin))
24368 (beginning-of-line))))
24369 ;; At the end of a greater element, move to the beginning of the
24370 ;; last element within.
24371 ((>= (point) contents-end)
24372 (goto-char (1- contents-end))
24373 (org-backward-paragraph))
24374 (t (goto-char (or post-affiliated begin))))
24375 ;; Ensure we never leave point invisible.
24376 (when (org-invisible-p (point)) (beginning-of-visual-line))))
24378 (defun org-forward-element ()
24379 "Move forward by one element.
24380 Move to the next element at the same level, when possible."
24381 (interactive)
24382 (cond ((eobp) (user-error "Cannot move further down"))
24383 ((org-with-limited-levels (org-at-heading-p))
24384 (let ((origin (point)))
24385 (goto-char (org-end-of-subtree nil t))
24386 (unless (org-with-limited-levels (org-at-heading-p))
24387 (goto-char origin)
24388 (user-error "Cannot move further down"))))
24390 (let* ((elem (org-element-at-point))
24391 (end (org-element-property :end elem))
24392 (parent (org-element-property :parent elem)))
24393 (cond ((and parent (= (org-element-property :contents-end parent) end))
24394 (goto-char (org-element-property :end parent)))
24395 ((integer-or-marker-p end) (goto-char end))
24396 (t (message "No element at point")))))))
24398 (defun org-backward-element ()
24399 "Move backward by one element.
24400 Move to the previous element at the same level, when possible."
24401 (interactive)
24402 (cond ((bobp) (user-error "Cannot move further up"))
24403 ((org-with-limited-levels (org-at-heading-p))
24404 ;; At a headline, move to the previous one, if any, or stay
24405 ;; here.
24406 (let ((origin (point)))
24407 (org-with-limited-levels (org-backward-heading-same-level 1))
24408 ;; When current headline has no sibling above, move to its
24409 ;; parent.
24410 (when (= (point) origin)
24411 (or (org-with-limited-levels (org-up-heading-safe))
24412 (progn (goto-char origin)
24413 (user-error "Cannot move further up"))))))
24415 (let* ((elem (org-element-at-point))
24416 (beg (org-element-property :begin elem)))
24417 (cond
24418 ;; Move to beginning of current element if point isn't
24419 ;; there already.
24420 ((null beg) (message "No element at point"))
24421 ((/= (point) beg) (goto-char beg))
24422 (t (goto-char beg)
24423 (skip-chars-backward " \r\t\n")
24424 (unless (bobp)
24425 (let ((prev (org-element-at-point)))
24426 (goto-char (org-element-property :begin prev))
24427 (while (and (setq prev (org-element-property :parent prev))
24428 (<= (org-element-property :end prev) beg))
24429 (goto-char (org-element-property :begin prev)))))))))))
24431 (defun org-up-element ()
24432 "Move to upper element."
24433 (interactive)
24434 (if (org-with-limited-levels (org-at-heading-p))
24435 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24436 (let* ((elem (org-element-at-point))
24437 (parent (org-element-property :parent elem)))
24438 (if parent (goto-char (org-element-property :begin parent))
24439 (if (org-with-limited-levels (org-before-first-heading-p))
24440 (user-error "No surrounding element")
24441 (org-with-limited-levels (org-back-to-heading)))))))
24443 (defun org-down-element ()
24444 "Move to inner element."
24445 (interactive)
24446 (let ((element (org-element-at-point)))
24447 (cond
24448 ((memq (org-element-type element) '(plain-list table))
24449 (goto-char (org-element-property :contents-begin element))
24450 (forward-char))
24451 ((memq (org-element-type element) org-element-greater-elements)
24452 ;; If contents are hidden, first disclose them.
24453 (when (org-invisible-p (line-end-position)) (org-cycle))
24454 (goto-char (or (org-element-property :contents-begin element)
24455 (user-error "No content for this element"))))
24456 (t (user-error "No inner element")))))
24458 (defun org-drag-element-backward ()
24459 "Move backward element at point."
24460 (interactive)
24461 (let ((elem (or (org-element-at-point)
24462 (user-error "No element at point"))))
24463 (if (eq (org-element-type elem) 'headline)
24464 ;; Preserve point when moving a whole tree, even if point was
24465 ;; on blank lines below the headline.
24466 (let ((offset (skip-chars-backward " \t\n")))
24467 (unwind-protect (org-move-subtree-up)
24468 (forward-char (- offset))))
24469 (let ((prev-elem
24470 (save-excursion
24471 (goto-char (org-element-property :begin elem))
24472 (skip-chars-backward " \r\t\n")
24473 (unless (bobp)
24474 (let* ((beg (org-element-property :begin elem))
24475 (prev (org-element-at-point))
24476 (up prev))
24477 (while (and (setq up (org-element-property :parent up))
24478 (<= (org-element-property :end up) beg))
24479 (setq prev up))
24480 prev)))))
24481 ;; Error out if no previous element or previous element is
24482 ;; a parent of the current one.
24483 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24484 (user-error "Cannot drag element backward")
24485 (let ((pos (point)))
24486 (org-element-swap-A-B prev-elem elem)
24487 (goto-char (+ (org-element-property :begin prev-elem)
24488 (- pos (org-element-property :begin elem))))))))))
24490 (defun org-drag-element-forward ()
24491 "Move forward element at point."
24492 (interactive)
24493 (let* ((pos (point))
24494 (elem (or (org-element-at-point)
24495 (user-error "No element at point"))))
24496 (when (= (point-max) (org-element-property :end elem))
24497 (user-error "Cannot drag element forward"))
24498 (goto-char (org-element-property :end elem))
24499 (let ((next-elem (org-element-at-point)))
24500 (when (or (org-element-nested-p elem next-elem)
24501 (and (eq (org-element-type next-elem) 'headline)
24502 (not (eq (org-element-type elem) 'headline))))
24503 (goto-char pos)
24504 (user-error "Cannot drag element forward"))
24505 ;; Compute new position of point: it's shifted by NEXT-ELEM
24506 ;; body's length (without final blanks) and by the length of
24507 ;; blanks between ELEM and NEXT-ELEM.
24508 (let ((size-next (- (save-excursion
24509 (goto-char (org-element-property :end next-elem))
24510 (skip-chars-backward " \r\t\n")
24511 (forward-line)
24512 ;; Small correction if buffer doesn't end
24513 ;; with a newline character.
24514 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24515 (org-element-property :begin next-elem)))
24516 (size-blank (- (org-element-property :end elem)
24517 (save-excursion
24518 (goto-char (org-element-property :end elem))
24519 (skip-chars-backward " \r\t\n")
24520 (forward-line)
24521 (point)))))
24522 (org-element-swap-A-B elem next-elem)
24523 (goto-char (+ pos size-next size-blank))))))
24525 (defun org-drag-line-forward (arg)
24526 "Drag the line at point ARG lines forward."
24527 (interactive "p")
24528 (dotimes (_ (abs arg))
24529 (let ((c (current-column)))
24530 (if (< 0 arg)
24531 (progn
24532 (beginning-of-line 2)
24533 (transpose-lines 1)
24534 (beginning-of-line 0))
24535 (transpose-lines 1)
24536 (beginning-of-line -1))
24537 (org-move-to-column c))))
24539 (defun org-drag-line-backward (arg)
24540 "Drag the line at point ARG lines backward."
24541 (interactive "p")
24542 (org-drag-line-forward (- arg)))
24544 (defun org-mark-element ()
24545 "Put point at beginning of this element, mark at end.
24547 Interactively, if this command is repeated or (in Transient Mark
24548 mode) if the mark is active, it marks the next element after the
24549 ones already marked."
24550 (interactive)
24551 (let (deactivate-mark)
24552 (if (and (called-interactively-p 'any)
24553 (or (and (eq last-command this-command) (mark t))
24554 (and transient-mark-mode mark-active)))
24555 (set-mark
24556 (save-excursion
24557 (goto-char (mark))
24558 (goto-char (org-element-property :end (org-element-at-point)))))
24559 (let ((element (org-element-at-point)))
24560 (end-of-line)
24561 (push-mark (org-element-property :end element) t t)
24562 (goto-char (org-element-property :begin element))))))
24564 (defun org-narrow-to-element ()
24565 "Narrow buffer to current element."
24566 (interactive)
24567 (let ((elem (org-element-at-point)))
24568 (cond
24569 ((eq (car elem) 'headline)
24570 (narrow-to-region
24571 (org-element-property :begin elem)
24572 (org-element-property :end elem)))
24573 ((memq (car elem) org-element-greater-elements)
24574 (narrow-to-region
24575 (org-element-property :contents-begin elem)
24576 (org-element-property :contents-end elem)))
24578 (narrow-to-region
24579 (org-element-property :begin elem)
24580 (org-element-property :end elem))))))
24582 (defun org-transpose-element ()
24583 "Transpose current and previous elements, keeping blank lines between.
24584 Point is moved after both elements."
24585 (interactive)
24586 (org-skip-whitespace)
24587 (let ((end (org-element-property :end (org-element-at-point))))
24588 (org-drag-element-backward)
24589 (goto-char end)))
24591 (defun org-unindent-buffer ()
24592 "Un-indent the visible part of the buffer.
24593 Relative indentation (between items, inside blocks, etc.) isn't
24594 modified."
24595 (interactive)
24596 (unless (eq major-mode 'org-mode)
24597 (user-error "Cannot un-indent a buffer not in Org mode"))
24598 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24599 (unindent-tree
24600 (lambda (contents)
24601 (dolist (element (reverse contents))
24602 (if (memq (org-element-type element) '(headline section))
24603 (funcall unindent-tree (org-element-contents element))
24604 (save-excursion
24605 (save-restriction
24606 (narrow-to-region
24607 (org-element-property :begin element)
24608 (org-element-property :end element))
24609 (org-do-remove-indentation))))))))
24610 (funcall unindent-tree (org-element-contents parse-tree))))
24612 (defun org-show-children (&optional level)
24613 "Show all direct subheadings of this heading.
24614 Prefix arg LEVEL is how many levels below the current level
24615 should be shown. Default is enough to cause the following
24616 heading to appear."
24617 (interactive "p")
24618 ;; If `orgstruct-mode' is active, use the slower version.
24619 (if orgstruct-mode (call-interactively #'outline-show-children)
24620 (save-excursion
24621 (org-back-to-heading t)
24622 (let* ((current-level (funcall outline-level))
24623 (max-level (org-get-valid-level
24624 current-level
24625 (if level (prefix-numeric-value level) 1)))
24626 (end (save-excursion (org-end-of-subtree t t)))
24627 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24628 (past-first-child nil)
24629 ;; Make sure to skip inlinetasks.
24630 (re (format regexp-fmt
24631 current-level
24632 (cond
24633 ((not (featurep 'org-inlinetask)) "")
24634 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24636 (t (1- org-inlinetask-min-level))))))
24637 ;; Display parent heading.
24638 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24639 (forward-line)
24640 ;; Display children. First child may be deeper than expected
24641 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24642 ;; MAX-LEVEL accordingly.
24643 (while (re-search-forward re end t)
24644 (unless past-first-child
24645 (setq re (format regexp-fmt
24646 current-level
24647 (max (funcall outline-level) max-level)))
24648 (setq past-first-child t))
24649 (outline-flag-region
24650 (line-end-position 0) (line-end-position) nil))))))
24652 (defun org-show-subtree ()
24653 "Show everything after this heading at deeper levels."
24654 (interactive)
24655 (outline-flag-region
24656 (point)
24657 (save-excursion
24658 (org-end-of-subtree t t))
24659 nil))
24661 (defun org-show-entry ()
24662 "Show the body directly following this heading.
24663 Show the heading too, if it is currently invisible."
24664 (interactive)
24665 (save-excursion
24666 (ignore-errors
24667 (org-back-to-heading t)
24668 (outline-flag-region
24669 (max (point-min) (1- (point)))
24670 (save-excursion
24671 (if (re-search-forward
24672 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24673 (match-beginning 1)
24674 (point-max)))
24675 nil)
24676 (org-cycle-hide-drawers 'children))))
24678 (defun org-make-options-regexp (kwds &optional extra)
24679 "Make a regular expression for keyword lines.
24680 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24681 when non-nil, is a regexp matching keywords names."
24682 (concat "^[ \t]*#\\+\\("
24683 (regexp-opt kwds)
24684 (and extra (concat (and kwds "\\|") extra))
24685 "\\):[ \t]*\\(.*\\)"))
24687 ;;;; Integration with and fixes for other packages
24689 ;;; Imenu support
24691 (defvar-local org-imenu-markers nil
24692 "All markers currently used by Imenu.")
24694 (defun org-imenu-new-marker (&optional pos)
24695 "Return a new marker for use by Imenu, and remember the marker."
24696 (let ((m (make-marker)))
24697 (move-marker m (or pos (point)))
24698 (push m org-imenu-markers)
24701 (defun org-imenu-get-tree ()
24702 "Produce the index for Imenu."
24703 (dolist (x org-imenu-markers) (move-marker x nil))
24704 (setq org-imenu-markers nil)
24705 (let* ((case-fold-search nil)
24706 (n org-imenu-depth)
24707 (re (concat "^" (org-get-limited-outline-regexp)))
24708 (subs (make-vector (1+ n) nil))
24709 (last-level 0)
24710 m level head0 head)
24711 (org-with-wide-buffer
24712 (goto-char (point-max))
24713 (while (re-search-backward re nil t)
24714 (setq level (org-reduced-level (funcall outline-level)))
24715 (when (and (<= level n)
24716 (looking-at org-complex-heading-regexp)
24717 (setq head0 (match-string-no-properties 4)))
24718 (setq head (org-link-display-format head0)
24719 m (org-imenu-new-marker))
24720 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24721 (if (>= level last-level)
24722 (push (cons head m) (aref subs level))
24723 (push (cons head (aref subs (1+ level))) (aref subs level))
24724 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24725 (setq last-level level))))
24726 (aref subs 1)))
24728 (eval-after-load "imenu"
24729 '(progn
24730 (add-hook 'imenu-after-jump-hook
24731 (lambda ()
24732 (when (derived-mode-p 'org-mode)
24733 (org-show-context 'org-goto))))))
24735 (defun org-link-display-format (s)
24736 "Replace links in string S with their description.
24737 If there is no description, use the link target."
24738 (save-match-data
24739 (replace-regexp-in-string
24740 org-bracket-link-analytic-regexp
24741 (lambda (m)
24742 (if (match-end 5) (match-string 5 m)
24743 (concat (match-string 1 m) (match-string 3 m))))
24744 s nil t)))
24746 (defun org-toggle-link-display ()
24747 "Toggle the literal or descriptive display of links."
24748 (interactive)
24749 (if org-descriptive-links
24750 (progn (org-remove-from-invisibility-spec '(org-link))
24751 (org-restart-font-lock)
24752 (setq org-descriptive-links nil))
24753 (progn (add-to-invisibility-spec '(org-link))
24754 (org-restart-font-lock)
24755 (setq org-descriptive-links t))))
24757 ;; Speedbar support
24759 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24760 "Overlay marking the agenda restriction line in speedbar.")
24761 (overlay-put org-speedbar-restriction-lock-overlay
24762 'face 'org-agenda-restriction-lock)
24763 (overlay-put org-speedbar-restriction-lock-overlay
24764 'help-echo "Agendas are currently limited to this item.")
24765 (delete-overlay org-speedbar-restriction-lock-overlay)
24767 (defun org-speedbar-set-agenda-restriction ()
24768 "Restrict future agenda commands to the location at point in speedbar.
24769 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24770 (interactive)
24771 (require 'org-agenda)
24772 (let (p m tp np dir txt)
24773 (cond
24774 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24775 'org-imenu t))
24776 (setq m (get-text-property p 'org-imenu-marker))
24777 (with-current-buffer (marker-buffer m)
24778 (goto-char m)
24779 (org-agenda-set-restriction-lock 'subtree)))
24780 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24781 'speedbar-function 'speedbar-find-file))
24782 (setq tp (previous-single-property-change
24783 (1+ p) 'speedbar-function)
24784 np (next-single-property-change
24785 tp 'speedbar-function)
24786 dir (speedbar-line-directory)
24787 txt (buffer-substring-no-properties (or tp (point-min))
24788 (or np (point-max))))
24789 (with-current-buffer (find-file-noselect
24790 (let ((default-directory dir))
24791 (expand-file-name txt)))
24792 (unless (derived-mode-p 'org-mode)
24793 (user-error "Cannot restrict to non-Org mode file"))
24794 (org-agenda-set-restriction-lock 'file)))
24795 (t (user-error "Don't know how to restrict Org mode agenda")))
24796 (move-overlay org-speedbar-restriction-lock-overlay
24797 (point-at-bol) (point-at-eol))
24798 (setq current-prefix-arg nil)
24799 (org-agenda-maybe-redo)))
24801 (defvar speedbar-file-key-map)
24802 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24803 (eval-after-load "speedbar"
24804 '(progn
24805 (speedbar-add-supported-extension ".org")
24806 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24807 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24808 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24809 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24810 (add-hook 'speedbar-visiting-tag-hook
24811 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24813 ;;; Fixes and Hacks for problems with other packages
24815 (defun org--flyspell-object-check-p (element)
24816 "Non-nil when Flyspell can check object at point.
24817 ELEMENT is the element at point."
24818 (let ((object (save-excursion
24819 (when (looking-at-p "\\>") (backward-char))
24820 (org-element-context element))))
24821 (cl-case (org-element-type object)
24822 ;; Prevent checks in links due to keybinding conflict with
24823 ;; Flyspell.
24824 ((code entity export-snippet inline-babel-call
24825 inline-src-block line-break latex-fragment link macro
24826 statistics-cookie target timestamp verbatim)
24827 nil)
24828 (footnote-reference
24829 ;; Only in inline footnotes, within the definition.
24830 (and (eq (org-element-property :type object) 'inline)
24831 (< (save-excursion
24832 (goto-char (org-element-property :begin object))
24833 (search-forward ":" nil t 2))
24834 (point))))
24835 (otherwise t))))
24837 (defun org-mode-flyspell-verify ()
24838 "Function used for `flyspell-generic-check-word-predicate'."
24839 (if (org-at-heading-p)
24840 ;; At a headline or an inlinetask, check title only. This is
24841 ;; faster than relying on `org-element-at-point'.
24842 (and (save-excursion (beginning-of-line)
24843 (and (let ((case-fold-search t))
24844 (not (looking-at-p "\\*+ END[ \t]*$")))
24845 (let ((case-fold-search nil))
24846 (looking-at org-complex-heading-regexp))))
24847 (match-beginning 4)
24848 (>= (point) (match-beginning 4))
24849 (or (not (match-beginning 5))
24850 (< (point) (match-beginning 5))))
24851 (let* ((element (org-element-at-point))
24852 (post-affiliated (org-element-property :post-affiliated element)))
24853 (cond
24854 ;; Ignore checks in all affiliated keywords but captions.
24855 ((< (point) post-affiliated)
24856 (and (save-excursion
24857 (beginning-of-line)
24858 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24859 (> (point) (match-end 0))
24860 (org--flyspell-object-check-p element)))
24861 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24862 ((let ((log (org-log-into-drawer)))
24863 (and log
24864 (let ((drawer (org-element-lineage element '(drawer))))
24865 (and drawer
24866 (eq (compare-strings
24867 log nil nil
24868 (org-element-property :drawer-name drawer) nil nil t)
24869 t)))))
24870 nil)
24872 (cl-case (org-element-type element)
24873 ((comment quote-section) t)
24874 (comment-block
24875 ;; Allow checks between block markers, not on them.
24876 (and (> (line-beginning-position) post-affiliated)
24877 (save-excursion
24878 (end-of-line)
24879 (skip-chars-forward " \r\t\n")
24880 (< (point) (org-element-property :end element)))))
24881 ;; Arbitrary list of keywords where checks are meaningful.
24882 ;; Make sure point is on the value part of the element.
24883 (keyword
24884 (and (member (org-element-property :key element)
24885 '("DESCRIPTION" "TITLE"))
24886 (save-excursion
24887 (search-backward ":" (line-beginning-position) t))))
24888 ;; Check is globally allowed in paragraphs verse blocks and
24889 ;; table rows (after affiliated keywords) but some objects
24890 ;; must not be affected.
24891 ((paragraph table-row verse-block)
24892 (let ((cbeg (org-element-property :contents-begin element))
24893 (cend (org-element-property :contents-end element)))
24894 (and cbeg (>= (point) cbeg) (< (point) cend)
24895 (org--flyspell-object-check-p element))))))))))
24896 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24898 (defun org-remove-flyspell-overlays-in (beg end)
24899 "Remove flyspell overlays in region."
24900 (and (bound-and-true-p flyspell-mode)
24901 (fboundp 'flyspell-delete-region-overlays)
24902 (flyspell-delete-region-overlays beg end)))
24904 (defvar flyspell-delayed-commands)
24905 (eval-after-load "flyspell"
24906 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24908 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24909 (eval-after-load "bookmark"
24910 '(if (boundp 'bookmark-after-jump-hook)
24911 ;; We can use the hook
24912 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24913 ;; Hook not available, use advice
24914 (defadvice bookmark-jump (after org-make-visible activate)
24915 "Make the position visible."
24916 (org-bookmark-jump-unhide))))
24918 ;; Make sure saveplace shows the location if it was hidden
24919 (eval-after-load "saveplace"
24920 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24921 "Make the position visible."
24922 (org-bookmark-jump-unhide)))
24924 ;; Make sure ecb shows the location if it was hidden
24925 (eval-after-load "ecb"
24926 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24927 "Make hierarchy visible when jumping into location from ECB tree buffer."
24928 (when (derived-mode-p 'org-mode)
24929 (org-show-context))))
24931 (defun org-bookmark-jump-unhide ()
24932 "Unhide the current position, to show the bookmark location."
24933 (and (derived-mode-p 'org-mode)
24934 (or (org-invisible-p)
24935 (save-excursion (goto-char (max (point-min) (1- (point))))
24936 (org-invisible-p)))
24937 (org-show-context 'bookmark-jump)))
24939 (defun org-mark-jump-unhide ()
24940 "Make the point visible with `org-show-context' after jumping to the mark."
24941 (when (and (derived-mode-p 'org-mode)
24942 (org-invisible-p))
24943 (org-show-context 'mark-goto)))
24945 (eval-after-load "simple"
24946 '(defadvice pop-to-mark-command (after org-make-visible activate)
24947 "Make the point visible with `org-show-context'."
24948 (org-mark-jump-unhide)))
24950 (eval-after-load "simple"
24951 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24952 "Make the point visible with `org-show-context'."
24953 (org-mark-jump-unhide)))
24955 (eval-after-load "simple"
24956 '(defadvice pop-global-mark (after org-make-visible activate)
24957 "Make the point visible with `org-show-context'."
24958 (org-mark-jump-unhide)))
24960 ;; Make session.el ignore our circular variable
24961 (defvar session-globals-exclude)
24962 (eval-after-load "session"
24963 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24965 ;;;; Finish up
24967 (provide 'org)
24969 (run-hooks 'org-load-hook)
24971 ;;; org.el ends here