Change emphasis regexp
[org-mode/org-tableheadings.git] / lisp / org.el
blob08ed909d8e2110c6ddc2b2236725089789393a76
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp) ;Silence byte-compiler
189 (defsubst org-uniquify (list)
190 "Non-destructively remove duplicate elements from LIST."
191 (let ((res (copy-sequence list))) (delete-dups res)))
193 (defsubst org-get-at-bol (property)
194 "Get text property PROPERTY at the beginning of line."
195 (get-text-property (point-at-bol) property))
197 (defsubst org-trim (s &optional keep-lead)
198 "Remove whitespace at the beginning and the end of string S.
199 When optional argument KEEP-LEAD is non-nil, removing blank lines
200 at the beginning of the string does not affect leading indentation."
201 (replace-regexp-in-string
202 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
203 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
205 ;; load languages based on value of `org-babel-load-languages'
206 (defvar org-babel-load-languages)
208 ;;;###autoload
209 (defun org-babel-do-load-languages (sym value)
210 "Load the languages defined in `org-babel-load-languages'."
211 (set-default sym value)
212 (dolist (pair org-babel-load-languages)
213 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
214 (if active
215 (require (intern (concat "ob-" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-execute:" lang)))
218 (funcall 'fmakunbound
219 (intern (concat "org-babel-expand-body:" lang)))))))
221 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
222 ;;;###autoload
223 (defun org-babel-load-file (file &optional compile)
224 "Load Emacs Lisp source code blocks in the Org FILE.
225 This function exports the source code using `org-babel-tangle'
226 and then loads the resulting file using `load-file'. With prefix
227 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
228 file to byte-code before it is loaded."
229 (interactive "fFile to load: \nP")
230 (let* ((age (lambda (file)
231 (float-time
232 (time-subtract (current-time)
233 (nth 5 (or (file-attributes (file-truename file))
234 (file-attributes file)))))))
235 (base-name (file-name-sans-extension file))
236 (exported-file (concat base-name ".el")))
237 ;; tangle if the Org file is newer than the elisp file
238 (unless (and (file-exists-p exported-file)
239 (> (funcall age file) (funcall age exported-file)))
240 ;; Tangle-file traversal returns reversed list of tangled files
241 ;; and we want to evaluate the first target.
242 (setq exported-file
243 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
244 (message "%s %s"
245 (if compile
246 (progn (byte-compile-file exported-file 'load)
247 "Compiled and loaded")
248 (progn (load-file exported-file) "Loaded"))
249 exported-file)))
251 (defcustom org-babel-load-languages '((emacs-lisp . t))
252 "Languages which can be evaluated in Org buffers.
253 This list can be used to load support for any of the languages
254 below, note that each language will depend on a different set of
255 system executables and/or Emacs modes. When a language is
256 \"loaded\", then code blocks in that language can be evaluated
257 with `org-babel-execute-src-block' bound by default to C-c
258 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
259 be set to remove code block evaluation from the C-c C-c
260 keybinding. By default only Emacs Lisp (which has no
261 requirements) is loaded."
262 :group 'org-babel
263 :set 'org-babel-do-load-languages
264 :version "24.1"
265 :type '(alist :tag "Babel Languages"
266 :key-type
267 (choice
268 (const :tag "Awk" awk)
269 (const :tag "C" C)
270 (const :tag "R" R)
271 (const :tag "Asymptote" asymptote)
272 (const :tag "Calc" calc)
273 (const :tag "Clojure" clojure)
274 (const :tag "CSS" css)
275 (const :tag "Ditaa" ditaa)
276 (const :tag "Dot" dot)
277 (const :tag "Ebnf2ps" ebnf2ps)
278 (const :tag "Emacs Lisp" emacs-lisp)
279 (const :tag "Forth" forth)
280 (const :tag "Fortran" fortran)
281 (const :tag "Gnuplot" gnuplot)
282 (const :tag "Haskell" haskell)
283 (const :tag "hledger" hledger)
284 (const :tag "IO" io)
285 (const :tag "J" J)
286 (const :tag "Java" java)
287 (const :tag "Javascript" js)
288 (const :tag "LaTeX" latex)
289 (const :tag "Ledger" ledger)
290 (const :tag "Lilypond" lilypond)
291 (const :tag "Lisp" lisp)
292 (const :tag "Makefile" makefile)
293 (const :tag "Maxima" maxima)
294 (const :tag "Matlab" matlab)
295 (const :tag "Mscgen" mscgen)
296 (const :tag "Ocaml" ocaml)
297 (const :tag "Octave" octave)
298 (const :tag "Org" org)
299 (const :tag "Perl" perl)
300 (const :tag "Pico Lisp" picolisp)
301 (const :tag "PlantUML" plantuml)
302 (const :tag "Python" python)
303 (const :tag "Ruby" ruby)
304 (const :tag "Sass" sass)
305 (const :tag "Scala" scala)
306 (const :tag "Scheme" scheme)
307 (const :tag "Screen" screen)
308 (const :tag "Shell Script" shell)
309 (const :tag "Shen" shen)
310 (const :tag "Sql" sql)
311 (const :tag "Sqlite" sqlite)
312 (const :tag "Stan" stan)
313 (const :tag "Vala" vala))
314 :value-type (boolean :tag "Activate" :value t)))
316 ;;;; Customization variables
317 (defcustom org-clone-delete-id nil
318 "Remove ID property of clones of a subtree.
319 When non-nil, clones of a subtree don't inherit the ID property.
320 Otherwise they inherit the ID property with a new unique
321 identifier."
322 :type 'boolean
323 :version "24.1"
324 :group 'org-id)
326 ;;; Version
327 (org-check-version)
329 ;;;###autoload
330 (defun org-version (&optional here full message)
331 "Show the Org version.
332 Interactively, or when MESSAGE is non-nil, show it in echo area.
333 With prefix argument, or when HERE is non-nil, insert it at point.
334 In non-interactive uses, a reduced version string is output unless
335 FULL is given."
336 (interactive (list current-prefix-arg t (not current-prefix-arg)))
337 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
338 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
339 (load-suffixes (list ".el"))
340 (org-install-dir
341 (ignore-errors (org-find-library-dir "org-loaddefs"))))
342 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
343 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
344 (let* ((load-suffixes save-load-suffixes)
345 (release (org-release))
346 (git-version (org-git-version))
347 (version (format "Org mode version %s (%s @ %s)"
348 release
349 git-version
350 (if org-install-dir
351 (if (string= org-dir org-install-dir)
352 org-install-dir
353 (concat "mixed installation! "
354 org-install-dir
355 " and "
356 org-dir))
357 "org-loaddefs.el can not be found!")))
358 (version1 (if full version release)))
359 (when here (insert version1))
360 (when message (message "%s" version1))
361 version1)))
363 (defconst org-version (org-version))
366 ;;; Syntax Constants
368 ;;;; Block
370 (defconst org-block-regexp
371 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
372 "Regular expression for hiding blocks.")
374 (defconst org-dblock-start-re
375 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
376 "Matches the start line of a dynamic block, with parameters.")
378 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
379 "Matches the end of a dynamic block.")
381 ;;;; Clock and Planning
383 (defconst org-clock-string "CLOCK:"
384 "String used as prefix for timestamps clocking work hours on an item.")
386 (defvar org-closed-string "CLOSED:"
387 "String used as the prefix for timestamps logging closing a TODO entry.")
389 (defvar org-deadline-string "DEADLINE:"
390 "String to mark deadline entries.
391 \\<org-mode-map>
392 A deadline is this string, followed by a time stamp. It must be
393 a word, terminated by a colon. You can insert a schedule keyword
394 and a timestamp with `\\[org-deadline]'.")
396 (defvar org-scheduled-string "SCHEDULED:"
397 "String to mark scheduled TODO entries.
398 \\<org-mode-map>
399 A schedule is this string, followed by a time stamp. It must be
400 a word, terminated by a colon. You can insert a schedule keyword
401 and a timestamp with `\\[org-schedule]'.")
403 (defconst org-ds-keyword-length
404 (+ 2
405 (apply #'max
406 (mapcar #'length
407 (list org-deadline-string org-scheduled-string
408 org-clock-string org-closed-string))))
409 "Maximum length of the DEADLINE and SCHEDULED keywords.")
411 (defconst org-planning-line-re
412 (concat "^[ \t]*"
413 (regexp-opt
414 (list org-closed-string org-deadline-string org-scheduled-string)
416 "Matches a line with planning info.
417 Matched keyword is in group 1.")
419 (defconst org-clock-line-re
420 (concat "^[ \t]*" org-clock-string)
421 "Matches a line with clock info.")
423 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
424 "Matches the DEADLINE keyword.")
426 (defconst org-deadline-time-regexp
427 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
428 "Matches the DEADLINE keyword together with a time stamp.")
430 (defconst org-deadline-time-hour-regexp
431 (concat "\\<" org-deadline-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
435 (defconst org-deadline-line-regexp
436 (concat "\\<\\(" org-deadline-string "\\).*")
437 "Matches the DEADLINE keyword and the rest of the line.")
439 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
440 "Matches the SCHEDULED keyword.")
442 (defconst org-scheduled-time-regexp
443 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
444 "Matches the SCHEDULED keyword together with a time stamp.")
446 (defconst org-scheduled-time-hour-regexp
447 (concat "\\<" org-scheduled-string
448 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
449 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
451 (defconst org-closed-time-regexp
452 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
453 "Matches the CLOSED keyword together with a time stamp.")
455 (defconst org-keyword-time-regexp
456 (concat "\\<"
457 (regexp-opt
458 (list org-scheduled-string org-deadline-string org-closed-string
459 org-clock-string)
461 " *[[<]\\([^]>]+\\)[]>]")
462 "Matches any of the 4 keywords, together with the time stamp.")
464 (defconst org-keyword-time-not-clock-regexp
465 (concat
466 "\\<"
467 (regexp-opt
468 (list org-scheduled-string org-deadline-string org-closed-string) t)
469 " *[[<]\\([^]>]+\\)[]>]")
470 "Matches any of the 3 keywords, together with the time stamp.")
472 (defconst org-maybe-keyword-time-regexp
473 (concat "\\(\\<"
474 (regexp-opt
475 (list org-scheduled-string org-deadline-string org-closed-string
476 org-clock-string)
478 "\\)?"
479 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
480 "\\|"
481 "<%%([^\r\n>]*>\\)")
482 "Matches a timestamp, possibly preceded by a keyword.")
484 (defconst org-all-time-keywords
485 (mapcar (lambda (w) (substring w 0 -1))
486 (list org-scheduled-string org-deadline-string
487 org-clock-string org-closed-string))
488 "List of time keywords.")
490 ;;;; Drawer
492 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
493 "Matches first or last line of a hidden block.
494 Group 1 contains drawer's name or \"END\".")
496 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
497 "Regular expression matching the first line of a property drawer.")
499 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
500 "Regular expression matching the last line of a property drawer.")
502 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
503 "Regular expression matching the first line of a clock drawer.")
505 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
506 "Regular expression matching the last line of a clock drawer.")
508 (defconst org-property-drawer-re
509 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
510 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
511 "[ \t]*:END:[ \t]*$")
512 "Matches an entire property drawer.")
514 (defconst org-clock-drawer-re
515 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
516 org-clock-drawer-end-re "\\)\n?")
517 "Matches an entire clock drawer.")
519 ;;;; Headline
521 (defconst org-heading-keyword-regexp-format
522 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
523 "Printf format for a regexp matching a headline with some keyword.
524 This regexp will match the headline of any node which has the
525 exact keyword that is put into the format. The keyword isn't in
526 any group by default, but the stars and the body are.")
528 (defconst org-heading-keyword-maybe-regexp-format
529 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
530 "Printf format for a regexp matching a headline, possibly with some keyword.
531 This regexp can match any headline with the specified keyword, or
532 without a keyword. The keyword isn't in any group by default,
533 but the stars and the body are.")
535 (defconst org-archive-tag "ARCHIVE"
536 "The tag that marks a subtree as archived.
537 An archived subtree does not open during visibility cycling, and does
538 not contribute to the agenda listings.")
540 (eval-and-compile
541 (defconst org-comment-string "COMMENT"
542 "Entries starting with this keyword will never be exported.
543 \\<org-mode-map>
544 An entry can be toggled between COMMENT and normal with
545 `\\[org-toggle-comment]'."))
548 ;;;; LaTeX Environments and Fragments
550 (defconst org-latex-regexps
551 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
552 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
553 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
554 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
555 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
556 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
557 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
558 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
559 "Regular expressions for matching embedded LaTeX.")
561 ;;;; Node Property
563 (defconst org-effort-property "Effort"
564 "The property that is being used to keep track of effort estimates.
565 Effort estimates given in this property need to have the format H:MM.")
567 ;;;; Table
569 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
570 "Detect an org-type or table-type table.")
572 (defconst org-table-line-regexp "^[ \t]*|"
573 "Detect an org-type table line.")
575 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
576 "Detect an org-type table line.")
578 (defconst org-table-hline-regexp "^[ \t]*|-"
579 "Detect an org-type table hline.")
581 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
582 "Detect a table-type table hline.")
584 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
585 "Detect the first line outside a table when searching from within it.
586 This works for both table types.")
588 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
589 "Detect a #+TBLFM line.")
591 ;;;; Timestamp
593 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
594 "Regular expression for fast time stamp matching.")
596 (defconst org-ts-regexp-inactive
597 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
598 "Regular expression for fast inactive time stamp matching.")
600 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
601 "Regular expression for fast time stamp matching.")
603 (defconst org-ts-regexp0
604 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
605 "Regular expression matching time strings for analysis.
606 This one does not require the space after the date, so it can be used
607 on a string that terminates immediately after the date.")
609 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
610 "Regular expression matching time strings for analysis.")
612 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
613 "Regular expression matching time stamps, with groups.")
615 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
616 "Regular expression matching time stamps (also [..]), with groups.")
618 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tr-regexp-both
622 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
623 "Regular expression matching a time stamp range.")
625 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
626 org-ts-regexp "\\)?")
627 "Regular expression matching a time stamp or time stamp range.")
629 (defconst org-tsr-regexp-both
630 (concat org-ts-regexp-both "\\(--?-?"
631 org-ts-regexp-both "\\)?")
632 "Regular expression matching a time stamp or time stamp range.
633 The time stamps may be either active or inactive.")
635 (defconst org-repeat-re
636 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
637 "Regular expression for specifying repeated events.
638 After a match, group 1 contains the repeat expression.")
640 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
641 "Formats for `format-time-string' which are used for time stamps.")
644 ;;; The custom variables
646 (defgroup org nil
647 "Outline-based notes management and organizer."
648 :tag "Org"
649 :group 'outlines
650 :group 'calendar)
652 (defcustom org-mode-hook nil
653 "Mode hook for Org mode, run after the mode was turned on."
654 :group 'org
655 :type 'hook)
657 (defcustom org-load-hook nil
658 "Hook that is run after org.el has been loaded."
659 :group 'org
660 :type 'hook)
662 (defcustom org-log-buffer-setup-hook nil
663 "Hook that is run after an Org log buffer is created."
664 :group 'org
665 :version "24.1"
666 :type 'hook)
668 (defvar org-modules) ; defined below
669 (defvar org-modules-loaded nil
670 "Have the modules been loaded already?")
672 (defun org-load-modules-maybe (&optional force)
673 "Load all extensions listed in `org-modules'."
674 (when (or force (not org-modules-loaded))
675 (dolist (ext org-modules)
676 (condition-case nil (require ext)
677 (error (message "Problems while trying to load feature `%s'" ext))))
678 (setq org-modules-loaded t)))
680 (defun org-set-modules (var value)
681 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
682 (set var value)
683 (when (featurep 'org)
684 (org-load-modules-maybe 'force)
685 (org-element-cache-reset 'all)))
687 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
688 "Modules that should always be loaded together with org.el.
690 If a description starts with <C>, the file is not part of Emacs
691 and loading it will require that you have downloaded and properly
692 installed the Org mode distribution.
694 You can also use this system to load external packages (i.e. neither Org
695 core modules, nor modules from the CONTRIB directory). Just add symbols
696 to the end of the list. If the package is called org-xyz.el, then you need
697 to add the symbol `xyz', and the package must have a call to:
699 (provide \\='org-xyz)
701 For export specific modules, see also `org-export-backends'."
702 :group 'org
703 :set 'org-set-modules
704 :version "24.4"
705 :package-version '(Org . "8.0")
706 :type
707 '(set :greedy t
708 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
709 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
710 (const :tag " crypt: Encryption of subtrees" org-crypt)
711 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
712 (const :tag " docview: Links to doc-view buffers" org-docview)
713 (const :tag " eww: Store link to url of eww" org-eww)
714 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
715 (const :tag " habit: Track your consistency with habits" org-habit)
716 (const :tag " id: Global IDs for identifying entries" org-id)
717 (const :tag " info: Links to Info nodes" org-info)
718 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
719 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
720 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
721 (const :tag " mouse: Additional mouse support" org-mouse)
722 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
723 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
724 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
726 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
727 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
728 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
729 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
730 (const :tag "C collector: Collect properties into tables" org-collector)
731 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
732 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
733 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
734 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
735 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
736 (const :tag "C eval: Include command output as text" org-eval)
737 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
738 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
739 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
740 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
741 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
742 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
743 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
744 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
745 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
746 (const :tag "C man: Support for links to manpages in Org mode" org-man)
747 (const :tag "C mew: Links to Mew folders/messages" org-mew)
748 (const :tag "C mtags: Support for muse-like tags" org-mtags)
749 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
750 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
751 (const :tag "C registry: A registry for Org links" org-registry)
752 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
753 (const :tag "C secretary: Team management with org-mode" org-secretary)
754 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
755 (const :tag "C toc: Table of contents for Org buffer" org-toc)
756 (const :tag "C track: Keep up with Org mode development" org-track)
757 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
758 (const :tag "C vm: Links to VM folders/messages" org-vm)
759 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
760 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
761 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
763 (defvar org-export-registered-backends) ; From ox.el.
764 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
765 (declare-function org-export-backend-name "ox" (backend) t)
766 (defcustom org-export-backends '(ascii html icalendar latex odt)
767 "List of export back-ends that should be always available.
769 If a description starts with <C>, the file is not part of Emacs
770 and loading it will require that you have downloaded and properly
771 installed the Org mode distribution.
773 Unlike to `org-modules', libraries in this list will not be
774 loaded along with Org, but only once the export framework is
775 needed.
777 This variable needs to be set before org.el is loaded. If you
778 need to make a change while Emacs is running, use the customize
779 interface or run the following code, where VAL stands for the new
780 value of the variable, after updating it:
782 (progn
783 (setq org-export-registered-backends
784 (cl-remove-if-not
785 (lambda (backend)
786 (let ((name (org-export-backend-name backend)))
787 (or (memq name val)
788 (catch \\='parentp
789 (dolist (b val)
790 (and (org-export-derived-backend-p b name)
791 (throw \\='parentp t)))))))
792 org-export-registered-backends))
793 (let ((new-list (mapcar #\\='org-export-backend-name
794 org-export-registered-backends)))
795 (dolist (backend val)
796 (cond
797 ((not (load (format \"ox-%s\" backend) t t))
798 (message \"Problems while trying to load export back-end \\=`%s\\='\"
799 backend))
800 ((not (memq backend new-list)) (push backend new-list))))
801 (set-default \\='org-export-backends new-list)))
803 Adding a back-end to this list will also pull the back-end it
804 depends on, if any."
805 :group 'org
806 :group 'org-export
807 :version "26.1"
808 :package-version '(Org . "9.0")
809 :initialize 'custom-initialize-set
810 :set (lambda (var val)
811 (if (not (featurep 'ox)) (set-default var val)
812 ;; Any back-end not required anymore (not present in VAL and not
813 ;; a parent of any back-end in the new value) is removed from the
814 ;; list of registered back-ends.
815 (setq org-export-registered-backends
816 (cl-remove-if-not
817 (lambda (backend)
818 (let ((name (org-export-backend-name backend)))
819 (or (memq name val)
820 (catch 'parentp
821 (dolist (b val)
822 (and (org-export-derived-backend-p b name)
823 (throw 'parentp t)))))))
824 org-export-registered-backends))
825 ;; Now build NEW-LIST of both new back-ends and required
826 ;; parents.
827 (let ((new-list (mapcar #'org-export-backend-name
828 org-export-registered-backends)))
829 (dolist (backend val)
830 (cond
831 ((not (load (format "ox-%s" backend) t t))
832 (message "Problems while trying to load export back-end `%s'"
833 backend))
834 ((not (memq backend new-list)) (push backend new-list))))
835 ;; Set VAR to that list with fixed dependencies.
836 (set-default var new-list))))
837 :type '(set :greedy t
838 (const :tag " ascii Export buffer to ASCII format" ascii)
839 (const :tag " beamer Export buffer to Beamer presentation" beamer)
840 (const :tag " html Export buffer to HTML format" html)
841 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
842 (const :tag " latex Export buffer to LaTeX format" latex)
843 (const :tag " man Export buffer to MAN format" man)
844 (const :tag " md Export buffer to Markdown format" md)
845 (const :tag " odt Export buffer to ODT format" odt)
846 (const :tag " org Export buffer to Org format" org)
847 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
848 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
849 (const :tag "C deck Export buffer to deck.js presentations" deck)
850 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
851 (const :tag "C groff Export buffer to Groff format" groff)
852 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
853 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
854 (const :tag "C s5 Export buffer to s5 presentations" s5)
855 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
857 (eval-after-load 'ox
858 '(dolist (backend org-export-backends)
859 (condition-case nil (require (intern (format "ox-%s" backend)))
860 (error (message "Problems while trying to load export back-end `%s'"
861 backend)))))
863 (defcustom org-support-shift-select nil
864 "Non-nil means make shift-cursor commands select text when possible.
865 \\<org-mode-map>\
867 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
868 start selecting a region, or enlarge regions started in this way.
869 In Org mode, in special contexts, these same keys are used for
870 other purposes, important enough to compete with shift selection.
871 Org tries to balance these needs by supporting `shift-select-mode'
872 outside these special contexts, under control of this variable.
874 The default of this variable is nil, to avoid confusing behavior. Shifted
875 cursor keys will then execute Org commands in the following contexts:
876 - on a headline, changing TODO state (left/right) and priority (up/down)
877 - on a time stamp, changing the time
878 - in a plain list item, changing the bullet type
879 - in a property definition line, switching between allowed values
880 - in the BEGIN line of a clock table (changing the time block).
881 Outside these contexts, the commands will throw an error.
883 When this variable is t and the cursor is not in a special
884 context, Org mode will support shift-selection for making and
885 enlarging regions. To make this more effective, the bullet
886 cycling will no longer happen anywhere in an item line, but only
887 if the cursor is exactly on the bullet.
889 If you set this variable to the symbol `always', then the keys
890 will not be special in headlines, property lines, and item lines,
891 to make shift selection work there as well. If this is what you
892 want, you can use the following alternative commands:
893 `\\[org-todo]' and `\\[org-priority]' \
894 to change TODO state and priority,
895 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
896 can be used to switch TODO sets,
897 `\\[org-ctrl-c-minus]' to cycle item bullet types,
898 and properties can be edited by hand or in column view.
900 However, when the cursor is on a timestamp, shift-cursor commands
901 will still edit the time stamp - this is just too good to give up."
902 :group 'org
903 :type '(choice
904 (const :tag "Never" nil)
905 (const :tag "When outside special context" t)
906 (const :tag "Everywhere except timestamps" always)))
908 (defcustom org-loop-over-headlines-in-active-region nil
909 "Shall some commands act upon headlines in the active region?
911 When set to t, some commands will be performed in all headlines
912 within the active region.
914 When set to `start-level', some commands will be performed in all
915 headlines within the active region, provided that these headlines
916 are of the same level than the first one.
918 When set to a string, those commands will be performed on the
919 matching headlines within the active region. Such string must be
920 a tags/property/todo match as it is used in the agenda tags view.
922 The list of commands is: `org-schedule', `org-deadline',
923 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
924 `org-archive-to-archive-sibling'. The archiving commands skip
925 already archived entries."
926 :type '(choice (const :tag "Don't loop" nil)
927 (const :tag "All headlines in active region" t)
928 (const :tag "In active region, headlines at the same level than the first one" start-level)
929 (string :tag "Tags/Property/Todo matcher"))
930 :version "24.1"
931 :group 'org-todo
932 :group 'org-archive)
934 (defgroup org-startup nil
935 "Options concerning startup of Org mode."
936 :tag "Org Startup"
937 :group 'org)
939 (defcustom org-startup-folded t
940 "Non-nil means entering Org mode will switch to OVERVIEW.
942 This can also be configured on a per-file basis by adding one of
943 the following lines anywhere in the buffer:
945 #+STARTUP: fold (or `overview', this is equivalent)
946 #+STARTUP: nofold (or `showall', this is equivalent)
947 #+STARTUP: content
948 #+STARTUP: showeverything
950 Set `org-agenda-inhibit-startup' to a non-nil value if you want
951 to ignore this option when Org opens agenda files for the first
952 time."
953 :group 'org-startup
954 :type '(choice
955 (const :tag "nofold: show all" nil)
956 (const :tag "fold: overview" t)
957 (const :tag "content: all headlines" content)
958 (const :tag "show everything, even drawers" showeverything)))
960 (defcustom org-startup-truncated t
961 "Non-nil means entering Org mode will set `truncate-lines'.
962 This is useful since some lines containing links can be very long and
963 uninteresting. Also tables look terrible when wrapped.
965 The variable `org-startup-truncated' allows to configure
966 truncation for Org mode different to the other modes that use the
967 variable `truncate-lines' and as a shortcut instead of putting
968 the variable `truncate-lines' into the `org-mode-hook'. If one
969 wants to configure truncation for Org mode not statically but
970 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
971 the variable `truncate-lines' has to be used because in such a
972 case it is too late to set the variable `org-startup-truncated'."
973 :group 'org-startup
974 :type 'boolean)
976 (defcustom org-startup-indented nil
977 "Non-nil means turn on `org-indent-mode' on startup.
978 This can also be configured on a per-file basis by adding one of
979 the following lines anywhere in the buffer:
981 #+STARTUP: indent
982 #+STARTUP: noindent"
983 :group 'org-structure
984 :type '(choice
985 (const :tag "Not" nil)
986 (const :tag "Globally (slow on startup in large files)" t)))
988 (defcustom org-use-sub-superscripts t
989 "Non-nil means interpret \"_\" and \"^\" for display.
991 If you want to control how Org exports those characters, see
992 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
993 used to be an alias for `org-export-with-sub-superscripts' in
994 Org <8.0, it is not anymore.
996 When this option is turned on, you can use TeX-like syntax for
997 sub- and superscripts within the buffer. Several characters after
998 \"_\" or \"^\" will be considered as a single item - so grouping
999 with {} is normally not needed. For example, the following things
1000 will be parsed as single sub- or superscripts:
1002 10^24 or 10^tau several digits will be considered 1 item.
1003 10^-12 or 10^-tau a leading sign with digits or a word
1004 x^2-y^3 will be read as x^2 - y^3, because items are
1005 terminated by almost any nonword/nondigit char.
1006 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1008 Still, ambiguity is possible. So when in doubt, use {} to enclose
1009 the sub/superscript. If you set this variable to the symbol `{}',
1010 the braces are *required* in order to trigger interpretations as
1011 sub/superscript. This can be helpful in documents that need \"_\"
1012 frequently in plain text."
1013 :group 'org-startup
1014 :version "24.4"
1015 :package-version '(Org . "8.0")
1016 :type '(choice
1017 (const :tag "Always interpret" t)
1018 (const :tag "Only with braces" {})
1019 (const :tag "Never interpret" nil)))
1021 (defcustom org-startup-with-beamer-mode nil
1022 "Non-nil means turn on `org-beamer-mode' on startup.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1026 #+STARTUP: beamer"
1027 :group 'org-startup
1028 :version "24.1"
1029 :type 'boolean)
1031 (defcustom org-startup-align-all-tables nil
1032 "Non-nil means align all tables when visiting a file.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: align
1036 #+STARTUP: noalign"
1037 :group 'org-startup
1038 :type 'boolean)
1040 (defcustom org-startup-shrink-all-tables nil
1041 "Non-nil means shrink all table columns with a width cookie.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: shrink"
1045 :group 'org-startup
1046 :type 'boolean
1047 :version "26.1"
1048 :package-version '(Org . "9.1")
1049 :safe #'booleanp)
1051 (defcustom org-startup-with-inline-images nil
1052 "Non-nil means show inline images when loading a new Org file.
1053 This can also be configured on a per-file basis by adding one of
1054 the following lines anywhere in the buffer:
1055 #+STARTUP: inlineimages
1056 #+STARTUP: noinlineimages"
1057 :group 'org-startup
1058 :version "24.1"
1059 :type 'boolean)
1061 (defcustom org-startup-with-latex-preview nil
1062 "Non-nil means preview LaTeX fragments when loading a new Org file.
1064 This can also be configured on a per-file basis by adding one of
1065 the following lines anywhere in the buffer:
1066 #+STARTUP: latexpreview
1067 #+STARTUP: nolatexpreview"
1068 :group 'org-startup
1069 :version "24.4"
1070 :package-version '(Org . "8.0")
1071 :type 'boolean)
1073 (defcustom org-insert-mode-line-in-empty-file nil
1074 "Non-nil means insert the first line setting Org mode in empty files.
1075 When the function `org-mode' is called interactively in an empty file, this
1076 normally means that the file name does not automatically trigger Org mode.
1077 To ensure that the file will always be in Org mode in the future, a
1078 line enforcing Org mode will be inserted into the buffer, if this option
1079 has been set."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (defcustom org-replace-disputed-keys nil
1084 "Non-nil means use alternative key bindings for some keys.
1085 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1086 These keys are also used by other packages like shift-selection-mode'
1087 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1088 If you want to use Org mode together with one of these other modes,
1089 or more generally if you would like to move some Org mode commands to
1090 other keys, set this variable and configure the keys with the variable
1091 `org-disputed-keys'.
1093 This option is only relevant at load-time of Org mode, and must be set
1094 *before* org.el is loaded. Changing it requires a restart of Emacs to
1095 become effective."
1096 :group 'org-startup
1097 :type 'boolean)
1099 (defcustom org-use-extra-keys nil
1100 "Non-nil means use extra key sequence definitions for certain commands.
1101 This happens automatically if `window-system' is nil. This
1102 variable lets you do the same manually. You must set it before
1103 loading Org."
1104 :group 'org-startup
1105 :type 'boolean)
1107 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1109 (defcustom org-disputed-keys
1110 '(([(shift up)] . [(meta p)])
1111 ([(shift down)] . [(meta n)])
1112 ([(shift left)] . [(meta -)])
1113 ([(shift right)] . [(meta +)])
1114 ([(control shift right)] . [(meta shift +)])
1115 ([(control shift left)] . [(meta shift -)]))
1116 "Keys for which Org mode and other modes compete.
1117 This is an alist, cars are the default keys, second element specifies
1118 the alternative to use when `org-replace-disputed-keys' is t.
1120 Keys can be specified in any syntax supported by `define-key'.
1121 The value of this option takes effect only at Org mode startup,
1122 therefore you'll have to restart Emacs to apply it after changing."
1123 :group 'org-startup
1124 :type 'alist)
1126 (defun org-key (key)
1127 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1128 Or return the original if not disputed."
1129 (when org-replace-disputed-keys
1130 (let* ((nkey (key-description key))
1131 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1132 org-disputed-keys)))
1133 (setq key (if x (cdr x) key))))
1134 key)
1136 (defun org-defkey (keymap key def)
1137 "Define a key, possibly translated, as returned by `org-key'."
1138 (define-key keymap (org-key key) def))
1140 (defcustom org-ellipsis nil
1141 "The ellipsis to use in the Org mode outline.
1143 When nil, just use the standard three dots. When a non-empty string,
1144 use that string instead.
1146 The change affects only Org mode (which will then use its own display table).
1147 Changing this requires executing `\\[org-mode]' in a buffer to become
1148 effective."
1149 :group 'org-startup
1150 :type '(choice (const :tag "Default" nil)
1151 (string :tag "String" :value "...#"))
1152 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1154 (defvar org-display-table nil
1155 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1157 (defgroup org-keywords nil
1158 "Keywords in Org mode."
1159 :tag "Org Keywords"
1160 :group 'org)
1162 (defcustom org-closed-keep-when-no-todo nil
1163 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1164 :group 'org-todo
1165 :group 'org-keywords
1166 :version "24.4"
1167 :package-version '(Org . "8.0")
1168 :type 'boolean)
1170 (defgroup org-structure nil
1171 "Options concerning the general structure of Org files."
1172 :tag "Org Structure"
1173 :group 'org)
1175 (defgroup org-reveal-location nil
1176 "Options about how to make context of a location visible."
1177 :tag "Org Reveal Location"
1178 :group 'org-structure)
1180 (defcustom org-show-context-detail '((agenda . local)
1181 (bookmark-jump . lineage)
1182 (isearch . lineage)
1183 (default . ancestors))
1184 "Alist between context and visibility span when revealing a location.
1186 \\<org-mode-map>Some actions may move point into invisible
1187 locations. As a consequence, Org always expose a neighborhood
1188 around point. How much is shown depends on the initial action,
1189 or context. Valid contexts are
1191 agenda when exposing an entry from the agenda
1192 org-goto when using the command `org-goto' (`\\[org-goto]')
1193 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1194 tags-tree when constructing a sparse tree based on tags matches
1195 link-search when exposing search matches associated with a link
1196 mark-goto when exposing the jump goal of a mark
1197 bookmark-jump when exposing a bookmark location
1198 isearch when exiting from an incremental search
1199 default default for all contexts not set explicitly
1201 Allowed visibility spans are
1203 minimal show current headline; if point is not on headline,
1204 also show entry
1206 local show current headline, entry and next headline
1208 ancestors show current headline and its direct ancestors; if
1209 point is not on headline, also show entry
1211 lineage show current headline, its direct ancestors and all
1212 their children; if point is not on headline, also show
1213 entry and first child
1215 tree show current headline, its direct ancestors and all
1216 their children; if point is not on headline, also show
1217 entry and all children
1219 canonical show current headline, its direct ancestors along with
1220 their entries and children; if point is not located on
1221 the headline, also show current entry and all children
1223 As special cases, a nil or t value means show all contexts in
1224 `minimal' or `canonical' view, respectively.
1226 Some views can make displayed information very compact, but also
1227 make it harder to edit the location of the match. In such
1228 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1229 more context."
1230 :group 'org-reveal-location
1231 :version "26.1"
1232 :package-version '(Org . "9.0")
1233 :type '(choice
1234 (const :tag "Canonical" t)
1235 (const :tag "Minimal" nil)
1236 (repeat :greedy t :tag "Individual contexts"
1237 (cons
1238 (choice :tag "Context"
1239 (const agenda)
1240 (const org-goto)
1241 (const occur-tree)
1242 (const tags-tree)
1243 (const link-search)
1244 (const mark-goto)
1245 (const bookmark-jump)
1246 (const isearch)
1247 (const default))
1248 (choice :tag "Detail level"
1249 (const minimal)
1250 (const local)
1251 (const ancestors)
1252 (const lineage)
1253 (const tree)
1254 (const canonical))))))
1256 (defcustom org-indirect-buffer-display 'other-window
1257 "How should indirect tree buffers be displayed?
1259 This applies to indirect buffers created with the commands
1260 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1262 Valid values are:
1263 current-window Display in the current window
1264 other-window Just display in another window.
1265 dedicated-frame Create one new frame, and re-use it each time.
1266 new-frame Make a new frame each time. Note that in this case
1267 previously-made indirect buffers are kept, and you need to
1268 kill these buffers yourself."
1269 :group 'org-structure
1270 :group 'org-agenda-windows
1271 :type '(choice
1272 (const :tag "In current window" current-window)
1273 (const :tag "In current frame, other window" other-window)
1274 (const :tag "Each time a new frame" new-frame)
1275 (const :tag "One dedicated frame" dedicated-frame)))
1277 (defcustom org-use-speed-commands nil
1278 "Non-nil means activate single letter commands at beginning of a headline.
1279 This may also be a function to test for appropriate locations where speed
1280 commands should be active.
1282 For example, to activate speed commands when the point is on any
1283 star at the beginning of the headline, you can do this:
1285 (setq org-use-speed-commands
1286 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1287 :group 'org-structure
1288 :type '(choice
1289 (const :tag "Never" nil)
1290 (const :tag "At beginning of headline stars" t)
1291 (function)))
1293 (defcustom org-speed-commands-user nil
1294 "Alist of additional speed commands.
1295 This list will be checked before `org-speed-commands-default'
1296 when the variable `org-use-speed-commands' is non-nil
1297 and when the cursor is at the beginning of a headline.
1298 The car if each entry is a string with a single letter, which must
1299 be assigned to `self-insert-command' in the global map.
1300 The cdr is either a command to be called interactively, a function
1301 to be called, or a form to be evaluated.
1302 An entry that is just a list with a single string will be interpreted
1303 as a descriptive headline that will be added when listing the speed
1304 commands in the Help buffer using the `?' speed command."
1305 :group 'org-structure
1306 :type '(repeat :value ("k" . ignore)
1307 (choice :value ("k" . ignore)
1308 (list :tag "Descriptive Headline" (string :tag "Headline"))
1309 (cons :tag "Letter and Command"
1310 (string :tag "Command letter")
1311 (choice
1312 (function)
1313 (sexp))))))
1315 (defcustom org-bookmark-names-plist
1316 '(:last-capture "org-capture-last-stored"
1317 :last-refile "org-refile-last-stored"
1318 :last-capture-marker "org-capture-last-stored-marker")
1319 "Names for bookmarks automatically set by some Org commands.
1320 This can provide strings as names for a number of bookmarks Org sets
1321 automatically. The following keys are currently implemented:
1322 :last-capture
1323 :last-capture-marker
1324 :last-refile
1325 When a key does not show up in the property list, the corresponding bookmark
1326 is not set."
1327 :group 'org-structure
1328 :type 'plist)
1330 (defgroup org-cycle nil
1331 "Options concerning visibility cycling in Org mode."
1332 :tag "Org Cycle"
1333 :group 'org-structure)
1335 (defcustom org-cycle-skip-children-state-if-no-children t
1336 "Non-nil means skip CHILDREN state in entries that don't have any."
1337 :group 'org-cycle
1338 :type 'boolean)
1340 (defcustom org-cycle-max-level nil
1341 "Maximum level which should still be subject to visibility cycling.
1342 Levels higher than this will, for cycling, be treated as text, not a headline.
1343 When `org-odd-levels-only' is set, a value of N in this variable actually
1344 means 2N-1 stars as the limiting headline.
1345 When nil, cycle all levels.
1346 Note that the limiting level of cycling is also influenced by
1347 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1348 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1349 than its value."
1350 :group 'org-cycle
1351 :type '(choice
1352 (const :tag "No limit" nil)
1353 (integer :tag "Maximum level")))
1355 (defcustom org-hide-block-startup nil
1356 "Non-nil means entering Org mode will fold all blocks.
1357 This can also be set in on a per-file basis with
1359 #+STARTUP: hideblocks
1360 #+STARTUP: showblocks"
1361 :group 'org-startup
1362 :group 'org-cycle
1363 :type 'boolean)
1365 (defcustom org-cycle-global-at-bob nil
1366 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1368 This makes it possible to do global cycling without having to use `S-TAB'
1369 or `\\[universal-argument] TAB'. For this special case to work, the first \
1370 line of the buffer
1371 must not be a headline -- it may be empty or some other text.
1373 When used in this way, `org-cycle-hook' is disabled temporarily to make
1374 sure the cursor stays at the beginning of the buffer.
1376 When this option is nil, don't do anything special at the beginning of
1377 the buffer."
1378 :group 'org-cycle
1379 :type 'boolean)
1381 (defcustom org-cycle-level-after-item/entry-creation t
1382 "Non-nil means cycle entry level or item indentation in new empty entries.
1384 When the cursor is at the end of an empty headline, i.e., with only stars
1385 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1386 and then all possible ancestor states, before returning to the original state.
1387 This makes data entry extremely fast: M-RET to create a new headline,
1388 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1390 When the cursor is at the end of an empty plain list item, one TAB will
1391 make it a subitem, two or more tabs will back up to make this an item
1392 higher up in the item hierarchy."
1393 :group 'org-cycle
1394 :type 'boolean)
1396 (defcustom org-cycle-emulate-tab t
1397 "Where should `org-cycle' emulate TAB.
1398 nil Never
1399 white Only in completely white lines
1400 whitestart Only at the beginning of lines, before the first non-white char
1401 t Everywhere except in headlines
1402 exc-hl-bol Everywhere except at the start of a headline
1403 If TAB is used in a place where it does not emulate TAB, the current subtree
1404 visibility is cycled."
1405 :group 'org-cycle
1406 :type '(choice (const :tag "Never" nil)
1407 (const :tag "Only in completely white lines" white)
1408 (const :tag "Before first char in a line" whitestart)
1409 (const :tag "Everywhere except in headlines" t)
1410 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1412 (defcustom org-cycle-separator-lines 2
1413 "Number of empty lines needed to keep an empty line between collapsed trees.
1414 If you leave an empty line between the end of a subtree and the following
1415 headline, this empty line is hidden when the subtree is folded.
1416 Org mode will leave (exactly) one empty line visible if the number of
1417 empty lines is equal or larger to the number given in this variable.
1418 So the default 2 means at least 2 empty lines after the end of a subtree
1419 are needed to produce free space between a collapsed subtree and the
1420 following headline.
1422 If the number is negative, and the number of empty lines is at least -N,
1423 all empty lines are shown.
1425 Special case: when 0, never leave empty lines in collapsed view."
1426 :group 'org-cycle
1427 :type 'integer)
1428 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1430 (defcustom org-pre-cycle-hook nil
1431 "Hook that is run before visibility cycling is happening.
1432 The function(s) in this hook must accept a single argument which indicates
1433 the new state that will be set right after running this hook. The
1434 argument is a symbol. Before a global state change, it can have the values
1435 `overview', `content', or `all'. Before a local state change, it can have
1436 the values `folded', `children', or `subtree'."
1437 :group 'org-cycle
1438 :type 'hook)
1440 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1441 org-cycle-hide-drawers
1442 org-cycle-show-empty-lines
1443 org-optimize-window-after-visibility-change)
1444 "Hook that is run after `org-cycle' has changed the buffer visibility.
1445 The function(s) in this hook must accept a single argument which indicates
1446 the new state that was set by the most recent `org-cycle' command. The
1447 argument is a symbol. After a global state change, it can have the values
1448 `overview', `contents', or `all'. After a local state change, it can have
1449 the values `folded', `children', or `subtree'."
1450 :group 'org-cycle
1451 :type 'hook
1452 :version "26.1"
1453 :package-version '(Org . "8.3"))
1455 (defgroup org-edit-structure nil
1456 "Options concerning structure editing in Org mode."
1457 :tag "Org Edit Structure"
1458 :group 'org-structure)
1460 (defcustom org-odd-levels-only nil
1461 "Non-nil means skip even levels and only use odd levels for the outline.
1462 This has the effect that two stars are being added/taken away in
1463 promotion/demotion commands. It also influences how levels are
1464 handled by the exporters.
1465 Changing it requires restart of `font-lock-mode' to become effective
1466 for fontification also in regions already fontified.
1467 You may also set this on a per-file basis by adding one of the following
1468 lines to the buffer:
1470 #+STARTUP: odd
1471 #+STARTUP: oddeven"
1472 :group 'org-edit-structure
1473 :group 'org-appearance
1474 :type 'boolean)
1476 (defcustom org-adapt-indentation t
1477 "Non-nil means adapt indentation to outline node level.
1479 When this variable is set, Org assumes that you write outlines by
1480 indenting text in each node to align with the headline (after the
1481 stars). The following issues are influenced by this variable:
1483 - The indentation is increased by one space in a demotion
1484 command, and decreased by one in a promotion command. However,
1485 in the latter case, if shifting some line in the entry body
1486 would alter document structure (e.g., insert a new headline),
1487 indentation is not changed at all.
1489 - Property drawers and planning information is inserted indented
1490 when this variable is set. When nil, they will not be indented.
1492 - TAB indents a line relative to current level. The lines below
1493 a headline will be indented when this variable is set.
1495 Note that this is all about true indentation, by adding and
1496 removing space characters. See also `org-indent.el' which does
1497 level-dependent indentation in a virtual way, i.e. at display
1498 time in Emacs."
1499 :group 'org-edit-structure
1500 :type 'boolean)
1502 (defcustom org-special-ctrl-a/e nil
1503 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1505 When t, `C-a' will bring back the cursor to the beginning of the
1506 headline text, i.e. after the stars and after a possible TODO
1507 keyword. In an item, this will be the position after bullet and
1508 check-box, if any. When the cursor is already at that position,
1509 another `C-a' will bring it to the beginning of the line.
1511 `C-e' will jump to the end of the headline, ignoring the presence
1512 of tags in the headline. A second `C-e' will then jump to the
1513 true end of the line, after any tags. This also means that, when
1514 this variable is non-nil, `C-e' also will never jump beyond the
1515 end of the heading of a folded section, i.e. not after the
1516 ellipses.
1518 When set to the symbol `reversed', the first `C-a' or `C-e' works
1519 normally, going to the true line boundary first. Only a directly
1520 following, identical keypress will bring the cursor to the
1521 special positions.
1523 This may also be a cons cell where the behavior for `C-a' and
1524 `C-e' is set separately."
1525 :group 'org-edit-structure
1526 :type '(choice
1527 (const :tag "off" nil)
1528 (const :tag "on: after stars/bullet and before tags first" t)
1529 (const :tag "reversed: true line boundary first" reversed)
1530 (cons :tag "Set C-a and C-e separately"
1531 (choice :tag "Special C-a"
1532 (const :tag "off" nil)
1533 (const :tag "on: after stars/bullet first" t)
1534 (const :tag "reversed: before stars/bullet first" reversed))
1535 (choice :tag "Special C-e"
1536 (const :tag "off" nil)
1537 (const :tag "on: before tags first" t)
1538 (const :tag "reversed: after tags first" reversed)))))
1539 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1541 (defcustom org-special-ctrl-k nil
1542 "Non-nil means `C-k' will behave specially in headlines.
1543 When nil, `C-k' will call the default `kill-line' command.
1544 When t, the following will happen while the cursor is in the headline:
1546 - When the cursor is at the beginning of a headline, kill the entire
1547 line and possible the folded subtree below the line.
1548 - When in the middle of the headline text, kill the headline up to the tags.
1549 - When after the headline text, kill the tags."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-ctrl-k-protect-subtree nil
1554 "Non-nil means, do not delete a hidden subtree with C-k.
1555 When set to the symbol `error', simply throw an error when C-k is
1556 used to kill (part-of) a headline that has hidden text behind it.
1557 Any other non-nil value will result in a query to the user, if it is
1558 OK to kill that hidden subtree. When nil, kill without remorse."
1559 :group 'org-edit-structure
1560 :version "24.1"
1561 :type '(choice
1562 (const :tag "Do not protect hidden subtrees" nil)
1563 (const :tag "Protect hidden subtrees with a security query" t)
1564 (const :tag "Never kill a hidden subtree with C-k" error)))
1566 (defcustom org-special-ctrl-o t
1567 "Non-nil means, make `C-o' insert a row in tables."
1568 :group 'org-edit-structure
1569 :type 'boolean)
1571 (defcustom org-catch-invisible-edits nil
1572 "Check if in invisible region before inserting or deleting a character.
1573 Valid values are:
1575 nil Do not check, so just do invisible edits.
1576 error Throw an error and do nothing.
1577 show Make point visible, and do the requested edit.
1578 show-and-error Make point visible, then throw an error and abort the edit.
1579 smart Make point visible, and do insertion/deletion if it is
1580 adjacent to visible text and the change feels predictable.
1581 Never delete a previously invisible character or add in the
1582 middle or right after an invisible region. Basically, this
1583 allows insertion and backward-delete right before ellipses.
1584 FIXME: maybe in this case we should not even show?"
1585 :group 'org-edit-structure
1586 :version "24.1"
1587 :type '(choice
1588 (const :tag "Do not check" nil)
1589 (const :tag "Throw error when trying to edit" error)
1590 (const :tag "Unhide, but do not do the edit" show-and-error)
1591 (const :tag "Show invisible part and do the edit" show)
1592 (const :tag "Be smart and do the right thing" smart)))
1594 (defcustom org-yank-folded-subtrees t
1595 "Non-nil means when yanking subtrees, fold them.
1596 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1597 it starts with a heading and all other headings in it are either children
1598 or siblings, then fold all the subtrees. However, do this only if no
1599 text after the yank would be swallowed into a folded tree by this action."
1600 :group 'org-edit-structure
1601 :type 'boolean)
1603 (defcustom org-yank-adjusted-subtrees nil
1604 "Non-nil means when yanking subtrees, adjust the level.
1605 With this setting, `org-paste-subtree' is used to insert the subtree, see
1606 this function for details."
1607 :group 'org-edit-structure
1608 :type 'boolean)
1610 (defcustom org-M-RET-may-split-line '((default . t))
1611 "Non-nil means M-RET will split the line at the cursor position.
1612 When nil, it will go to the end of the line before making a
1613 new line.
1614 You may also set this option in a different way for different
1615 contexts. Valid contexts are:
1617 headline when creating a new headline
1618 item when creating a new item
1619 table in a table field
1620 default the value to be used for all contexts not explicitly
1621 customized"
1622 :group 'org-structure
1623 :group 'org-table
1624 :type '(choice
1625 (const :tag "Always" t)
1626 (const :tag "Never" nil)
1627 (repeat :greedy t :tag "Individual contexts"
1628 (cons
1629 (choice :tag "Context"
1630 (const headline)
1631 (const item)
1632 (const table)
1633 (const default))
1634 (boolean)))))
1637 (defcustom org-insert-heading-respect-content nil
1638 "Non-nil means insert new headings after the current subtree.
1639 \\<org-mode-map>
1640 When nil, the new heading is created directly after the current line.
1641 The commands `\\[org-insert-heading-respect-content]' and \
1642 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1643 for the duration of the command."
1644 :group 'org-structure
1645 :type 'boolean)
1647 (defcustom org-blank-before-new-entry '((heading . auto)
1648 (plain-list-item . auto))
1649 "Should `org-insert-heading' leave a blank line before new heading/item?
1650 The value is an alist, with `heading' and `plain-list-item' as CAR,
1651 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1652 which case Org will look at the surrounding headings/items and try to
1653 make an intelligent decision whether to insert a blank line or not."
1654 :group 'org-edit-structure
1655 :type '(list
1656 (cons (const heading)
1657 (choice (const :tag "Never" nil)
1658 (const :tag "Always" t)
1659 (const :tag "Auto" auto)))
1660 (cons (const plain-list-item)
1661 (choice (const :tag "Never" nil)
1662 (const :tag "Always" t)
1663 (const :tag "Auto" auto)))))
1665 (defcustom org-insert-heading-hook nil
1666 "Hook being run after inserting a new heading."
1667 :group 'org-edit-structure
1668 :type 'hook)
1670 (defcustom org-enable-fixed-width-editor t
1671 "Non-nil means lines starting with \":\" are treated as fixed-width.
1672 This currently only means they are never auto-wrapped.
1673 When nil, such lines will be treated like ordinary lines."
1674 :group 'org-edit-structure
1675 :type 'boolean)
1677 (defcustom org-goto-auto-isearch t
1678 "Non-nil means typing characters in `org-goto' starts incremental search.
1679 When nil, you can use these keybindings to navigate the buffer:
1681 q Quit the org-goto interface
1682 n Go to the next visible heading
1683 p Go to the previous visible heading
1684 f Go one heading forward on same level
1685 b Go one heading backward on same level
1686 u Go one heading up"
1687 :group 'org-edit-structure
1688 :type 'boolean)
1690 (defgroup org-sparse-trees nil
1691 "Options concerning sparse trees in Org mode."
1692 :tag "Org Sparse Trees"
1693 :group 'org-structure)
1695 (defcustom org-highlight-sparse-tree-matches t
1696 "Non-nil means highlight all matches that define a sparse tree.
1697 The highlights will automatically disappear the next time the buffer is
1698 changed by an edit command."
1699 :group 'org-sparse-trees
1700 :type 'boolean)
1702 (defcustom org-remove-highlights-with-change t
1703 "Non-nil means any change to the buffer will remove temporary highlights.
1704 \\<org-mode-map>\
1705 Such highlights are created by `org-occur' and `org-clock-display'.
1706 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1707 to get rid of the highlights.
1708 The highlights created by `org-toggle-latex-fragment' always need
1709 `\\[org-toggle-latex-fragment]' to be removed."
1710 :group 'org-sparse-trees
1711 :group 'org-time
1712 :type 'boolean)
1714 (defcustom org-occur-case-fold-search t
1715 "Non-nil means `org-occur' should be case-insensitive.
1716 If set to `smart' the search will be case-insensitive only if it
1717 doesn't specify any upper case character."
1718 :group 'org-sparse-trees
1719 :version "26.1"
1720 :type '(choice
1721 (const :tag "Case-sensitive" nil)
1722 (const :tag "Case-insensitive" t)
1723 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1725 (defcustom org-occur-hook '(org-first-headline-recenter)
1726 "Hook that is run after `org-occur' has constructed a sparse tree.
1727 This can be used to recenter the window to show as much of the structure
1728 as possible."
1729 :group 'org-sparse-trees
1730 :type 'hook)
1732 (defgroup org-imenu-and-speedbar nil
1733 "Options concerning imenu and speedbar in Org mode."
1734 :tag "Org Imenu and Speedbar"
1735 :group 'org-structure)
1737 (defcustom org-imenu-depth 2
1738 "The maximum level for Imenu access to Org headlines.
1739 This also applied for speedbar access."
1740 :group 'org-imenu-and-speedbar
1741 :type 'integer)
1743 (defgroup org-table nil
1744 "Options concerning tables in Org mode."
1745 :tag "Org Table"
1746 :group 'org)
1748 (defcustom org-self-insert-cluster-for-undo nil
1749 "Non-nil means cluster self-insert commands for undo when possible.
1750 If this is set, then, like in the Emacs command loop, 20 consecutive
1751 characters will be undone together.
1752 This is configurable, because there is some impact on typing performance."
1753 :group 'org-table
1754 :type 'boolean)
1756 (defcustom org-table-tab-recognizes-table.el t
1757 "Non-nil means TAB will automatically notice a table.el table.
1758 When it sees such a table, it moves point into it and - if necessary -
1759 calls `table-recognize-table'."
1760 :group 'org-table-editing
1761 :type 'boolean)
1763 (defgroup org-link nil
1764 "Options concerning links in Org mode."
1765 :tag "Org Link"
1766 :group 'org)
1768 (defvar-local org-link-abbrev-alist-local nil
1769 "Buffer-local version of `org-link-abbrev-alist', which see.
1770 The value of this is taken from the #+LINK lines.")
1772 (defcustom org-link-parameters
1773 '(("doi" :follow org--open-doi-link)
1774 ("elisp" :follow org--open-elisp-link)
1775 ("file" :complete org-file-complete-link)
1776 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1777 ("help" :follow org--open-help-link)
1778 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1779 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1780 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1781 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1782 ("shell" :follow org--open-shell-link))
1783 "An alist of properties that defines all the links in Org mode.
1784 The key in each association is a string of the link type.
1785 Subsequent optional elements make up a p-list of link properties.
1787 :follow - A function that takes the link path as an argument.
1789 :export - A function that takes the link path, description and
1790 export-backend as arguments.
1792 :store - A function responsible for storing the link. See the
1793 function `org-store-link-functions'.
1795 :complete - A function that inserts a link with completion. The
1796 function takes one optional prefix arg.
1798 :face - A face for the link, or a function that returns a face.
1799 The function takes one argument which is the link path. The
1800 default face is `org-link'.
1802 :mouse-face - The mouse-face. The default is `highlight'.
1804 :display - `full' will not fold the link in descriptive
1805 display. Default is `org-link'.
1807 :help-echo - A string or function that takes (window object position)
1808 as arguments and returns a string.
1810 :keymap - A keymap that is active on the link. The default is
1811 `org-mouse-map'.
1813 :htmlize-link - A function for the htmlize-link. Defaults
1814 to (list :uri \"type:path\")
1816 :activate-func - A function to run at the end of font-lock
1817 activation. The function must accept (link-start link-end path bracketp)
1818 as arguments."
1819 :group 'org-link
1820 :type '(alist :tag "Link display parameters"
1821 :value-type plist)
1822 :version "26.1"
1823 :package-version '(Org . "9.1"))
1825 (defun org-link-get-parameter (type key)
1826 "Get TYPE link property for KEY.
1827 TYPE is a string and KEY is a plist keyword."
1828 (plist-get
1829 (cdr (assoc type org-link-parameters))
1830 key))
1832 (defun org-link-set-parameters (type &rest parameters)
1833 "Set link TYPE properties to PARAMETERS.
1834 PARAMETERS should be :key val pairs."
1835 (let ((data (assoc type org-link-parameters)))
1836 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1837 (push (cons type parameters) org-link-parameters)
1838 (org-make-link-regexps)
1839 (org-element-update-syntax))))
1841 (defun org-link-types ()
1842 "Return a list of known link types."
1843 (mapcar #'car org-link-parameters))
1845 (defcustom org-link-abbrev-alist nil
1846 "Alist of link abbreviations.
1847 The car of each element is a string, to be replaced at the start of a link.
1848 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1849 links in Org buffers can have an optional tag after a double colon, e.g.,
1851 [[linkkey:tag][description]]
1853 The `linkkey' must be a single word, starting with a letter, followed
1854 by letters, numbers, `-' or `_'.
1856 If REPLACE is a string, the tag will simply be appended to create the link.
1857 If the string contains \"%s\", the tag will be inserted there. If the string
1858 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1859 at that point (see the function `url-hexify-string'). If the string contains
1860 the specifier \"%(my-function)\", then the custom function `my-function' will
1861 be invoked: this function takes the tag as its only argument and must return
1862 a string.
1864 REPLACE may also be a function that will be called with the tag as the
1865 only argument to create the link, which should be returned as a string.
1867 See the manual for examples."
1868 :group 'org-link
1869 :type '(repeat
1870 (cons
1871 (string :tag "Protocol")
1872 (choice
1873 (string :tag "Format")
1874 (function)))))
1876 (defcustom org-descriptive-links t
1877 "Non-nil means Org will display descriptive links.
1878 E.g. [[http://orgmode.org][Org website]] will be displayed as
1879 \"Org Website\", hiding the link itself and just displaying its
1880 description. When set to nil, Org will display the full links
1881 literally.
1883 You can interactively set the value of this variable by calling
1884 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1885 :group 'org-link
1886 :type 'boolean)
1888 (defcustom org-link-file-path-type 'adaptive
1889 "How the path name in file links should be stored.
1890 Valid values are:
1892 relative Relative to the current directory, i.e. the directory of the file
1893 into which the link is being inserted.
1894 absolute Absolute path, if possible with ~ for home directory.
1895 noabbrev Absolute path, no abbreviation of home directory.
1896 adaptive Use relative path for files in the current directory and sub-
1897 directories of it. For other files, use an absolute path."
1898 :group 'org-link
1899 :type '(choice
1900 (const relative)
1901 (const absolute)
1902 (const noabbrev)
1903 (const adaptive)))
1905 (defvaralias 'org-activate-links 'org-highlight-links)
1906 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1907 "Types of links that should be highlighted in Org files.
1909 This is a list of symbols, each one of them leading to the
1910 highlighting of a certain link type.
1912 You can still open links that are not highlighted.
1914 In principle, it does not hurt to turn on highlighting for all
1915 link types. There may be a small gain when turning off unused
1916 link types. The types are:
1918 bracket The recommended [[link][description]] or [[link]] links with hiding.
1919 angle Links in angular brackets that may contain whitespace like
1920 <bbdb:Carsten Dominik>.
1921 plain Plain links in normal text, no whitespace, like http://google.com.
1922 radio Text that is matched by a radio target, see manual for details.
1923 tag Tag settings in a headline (link to tag search).
1924 date Time stamps (link to calendar).
1925 footnote Footnote labels.
1927 If you set this variable during an Emacs session, use `org-mode-restart'
1928 in the Org buffer so that the change takes effect."
1929 :group 'org-link
1930 :group 'org-appearance
1931 :type '(set :greedy t
1932 (const :tag "Double bracket links" bracket)
1933 (const :tag "Angular bracket links" angle)
1934 (const :tag "Plain text links" plain)
1935 (const :tag "Radio target matches" radio)
1936 (const :tag "Tags" tag)
1937 (const :tag "Timestamps" date)
1938 (const :tag "Footnotes" footnote)))
1940 (defcustom org-make-link-description-function nil
1941 "Function to use for generating link descriptions from links.
1942 This function must take two parameters: the first one is the
1943 link, the second one is the description generated by
1944 `org-insert-link'. The function should return the description to
1945 use."
1946 :group 'org-link
1947 :type '(choice (const nil) (function)))
1949 (defgroup org-link-store nil
1950 "Options concerning storing links in Org mode."
1951 :tag "Org Store Link"
1952 :group 'org-link)
1954 (defcustom org-url-hexify-p t
1955 "When non-nil, hexify URL when creating a link."
1956 :type 'boolean
1957 :version "24.3"
1958 :group 'org-link-store)
1960 (defcustom org-email-link-description-format "Email %c: %.30s"
1961 "Format of the description part of a link to an email or usenet message.
1962 The following %-escapes will be replaced by corresponding information:
1964 %F full \"From\" field
1965 %f name, taken from \"From\" field, address if no name
1966 %T full \"To\" field
1967 %t first name in \"To\" field, address if no name
1968 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1969 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1970 %s subject
1971 %d date
1972 %m message-id.
1974 You may use normal field width specification between the % and the letter.
1975 This is for example useful to limit the length of the subject.
1977 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1978 :group 'org-link-store
1979 :type 'string)
1981 (defcustom org-from-is-user-regexp
1982 (let (r1 r2)
1983 (when (and user-mail-address (not (string= user-mail-address "")))
1984 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1985 (when (and user-full-name (not (string= user-full-name "")))
1986 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1987 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1988 "Regexp matched against the \"From:\" header of an email or usenet message.
1989 It should match if the message is from the user him/herself."
1990 :group 'org-link-store
1991 :type 'regexp)
1993 (defcustom org-context-in-file-links t
1994 "Non-nil means file links from `org-store-link' contain context.
1995 \\<org-mode-map>
1996 A search string will be added to the file name with :: as separator
1997 and used to find the context when the link is activated by the command
1998 `org-open-at-point'. When this option is t, the entire active region
1999 will be placed in the search string of the file link. If set to a
2000 positive integer, only the first n lines of context will be stored.
2002 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2003 \\[org-store-link]')
2004 negates this setting for the duration of the command."
2005 :group 'org-link-store
2006 :type '(choice boolean integer))
2008 (defcustom org-keep-stored-link-after-insertion nil
2009 "Non-nil means keep link in list for entire session.
2010 \\<org-mode-map>
2011 The command `org-store-link' adds a link pointing to the current
2012 location to an internal list. These links accumulate during a session.
2013 The command `org-insert-link' can be used to insert links into any
2014 Org file (offering completion for all stored links).
2016 When this option is nil, every link which has been inserted once using
2017 `\\[org-insert-link]' will be removed from the list, to make completing the \
2018 unused
2019 links more efficient."
2020 :group 'org-link-store
2021 :type 'boolean)
2023 (defgroup org-link-follow nil
2024 "Options concerning following links in Org mode."
2025 :tag "Org Follow Link"
2026 :group 'org-link)
2028 (defcustom org-link-translation-function nil
2029 "Function to translate links with different syntax to Org syntax.
2030 This can be used to translate links created for example by the Planner
2031 or emacs-wiki packages to Org syntax.
2032 The function must accept two parameters, a TYPE containing the link
2033 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2034 which is everything after the link protocol. It should return a cons
2035 with possibly modified values of type and path.
2036 Org contains a function for this, so if you set this variable to
2037 `org-translate-link-from-planner', you should be able follow many
2038 links created by planner."
2039 :group 'org-link-follow
2040 :type '(choice (const nil) (function)))
2042 (defcustom org-follow-link-hook nil
2043 "Hook that is run after a link has been followed."
2044 :group 'org-link-follow
2045 :type 'hook)
2047 (defcustom org-tab-follows-link nil
2048 "Non-nil means on links TAB will follow the link.
2049 Needs to be set before org.el is loaded.
2050 This really should not be used, it does not make sense, and the
2051 implementation is bad."
2052 :group 'org-link-follow
2053 :type 'boolean)
2055 (defcustom org-return-follows-link nil
2056 "Non-nil means on links RET will follow the link.
2057 In tables, the special behavior of RET has precedence."
2058 :group 'org-link-follow
2059 :type 'boolean)
2061 (defcustom org-mouse-1-follows-link
2062 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2063 "Non-nil means mouse-1 on a link will follow the link.
2064 A longer mouse click will still set point. Needs to be set
2065 before org.el is loaded."
2066 :group 'org-link-follow
2067 :version "26.1"
2068 :package-version '(Org . "8.3")
2069 :type '(choice
2070 (const :tag "A double click follows the link" double)
2071 (const :tag "Unconditionally follow the link with mouse-1" t)
2072 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2074 (defcustom org-mark-ring-length 4
2075 "Number of different positions to be recorded in the ring.
2076 Changing this requires a restart of Emacs to work correctly."
2077 :group 'org-link-follow
2078 :type 'integer)
2080 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2081 "Non-nil means internal fuzzy links can only match headlines.
2083 When nil, the a fuzzy link may point to a target or a named
2084 construct in the document. When set to the special value
2085 `query-to-create', offer to create a new headline when none
2086 matched.
2088 Spaces and statistics cookies are ignored during heading searches."
2089 :group 'org-link-follow
2090 :version "24.1"
2091 :type '(choice
2092 (const :tag "Use fuzzy text search" nil)
2093 (const :tag "Match only exact headline" t)
2094 (const :tag "Match exact headline or query to create it"
2095 query-to-create))
2096 :safe #'symbolp)
2098 (defcustom org-link-frame-setup
2099 '((vm . vm-visit-folder-other-frame)
2100 (vm-imap . vm-visit-imap-folder-other-frame)
2101 (gnus . org-gnus-no-new-news)
2102 (file . find-file-other-window)
2103 (wl . wl-other-frame))
2104 "Setup the frame configuration for following links.
2105 When following a link with Emacs, it may often be useful to display
2106 this link in another window or frame. This variable can be used to
2107 set this up for the different types of links.
2108 For VM, use any of
2109 `vm-visit-folder'
2110 `vm-visit-folder-other-window'
2111 `vm-visit-folder-other-frame'
2112 For Gnus, use any of
2113 `gnus'
2114 `gnus-other-frame'
2115 `org-gnus-no-new-news'
2116 For FILE, use any of
2117 `find-file'
2118 `find-file-other-window'
2119 `find-file-other-frame'
2120 For Wanderlust use any of
2121 `wl'
2122 `wl-other-frame'
2123 For the calendar, use the variable `calendar-setup'.
2124 For BBDB, it is currently only possible to display the matches in
2125 another window."
2126 :group 'org-link-follow
2127 :type '(list
2128 (cons (const vm)
2129 (choice
2130 (const vm-visit-folder)
2131 (const vm-visit-folder-other-window)
2132 (const vm-visit-folder-other-frame)))
2133 (cons (const vm-imap)
2134 (choice
2135 (const vm-visit-imap-folder)
2136 (const vm-visit-imap-folder-other-window)
2137 (const vm-visit-imap-folder-other-frame)))
2138 (cons (const gnus)
2139 (choice
2140 (const gnus)
2141 (const gnus-other-frame)
2142 (const org-gnus-no-new-news)))
2143 (cons (const file)
2144 (choice
2145 (const find-file)
2146 (const find-file-other-window)
2147 (const find-file-other-frame)))
2148 (cons (const wl)
2149 (choice
2150 (const wl)
2151 (const wl-other-frame)))))
2153 (defcustom org-display-internal-link-with-indirect-buffer nil
2154 "Non-nil means use indirect buffer to display infile links.
2155 Activating internal links (from one location in a file to another location
2156 in the same file) normally just jumps to the location. When the link is
2157 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2158 is displayed in
2159 another window. When this option is set, the other window actually displays
2160 an indirect buffer clone of the current buffer, to avoid any visibility
2161 changes to the current buffer."
2162 :group 'org-link-follow
2163 :type 'boolean)
2165 (defcustom org-open-non-existing-files nil
2166 "Non-nil means `org-open-file' will open non-existing files.
2167 When nil, an error will be generated.
2168 This variable applies only to external applications because they
2169 might choke on non-existing files. If the link is to a file that
2170 will be opened in Emacs, the variable is ignored."
2171 :group 'org-link-follow
2172 :type 'boolean)
2174 (defcustom org-open-directory-means-index-dot-org nil
2175 "Non-nil means a link to a directory really means to index.org.
2176 When nil, following a directory link will run dired or open a finder/explorer
2177 window on that directory."
2178 :group 'org-link-follow
2179 :type 'boolean)
2181 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2182 "Non-nil means ask for confirmation before executing shell links.
2183 Shell links can be dangerous: just think about a link
2185 [[shell:rm -rf ~/*][Google Search]]
2187 This link would show up in your Org document as \"Google Search\",
2188 but really it would remove your entire home directory.
2189 Therefore we advise against setting this variable to nil.
2190 Just change it to `y-or-n-p' if you want to confirm with a
2191 single keystroke rather than having to type \"yes\"."
2192 :group 'org-link-follow
2193 :type '(choice
2194 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2195 (const :tag "with y-or-n (faster)" y-or-n-p)
2196 (const :tag "no confirmation (dangerous)" nil)))
2197 (put 'org-confirm-shell-link-function
2198 'safe-local-variable
2199 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2201 (defcustom org-confirm-shell-link-not-regexp ""
2202 "A regexp to skip confirmation for shell links."
2203 :group 'org-link-follow
2204 :version "24.1"
2205 :type 'regexp)
2207 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2208 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2209 Elisp links can be dangerous: just think about a link
2211 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2213 This link would show up in your Org document as \"Google Search\",
2214 but really it would remove your entire home directory.
2215 Therefore we advise against setting this variable to nil.
2216 Just change it to `y-or-n-p' if you want to confirm with a
2217 single keystroke rather than having to type \"yes\"."
2218 :group 'org-link-follow
2219 :type '(choice
2220 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2221 (const :tag "with y-or-n (faster)" y-or-n-p)
2222 (const :tag "no confirmation (dangerous)" nil)))
2223 (put 'org-confirm-shell-link-function
2224 'safe-local-variable
2225 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2227 (defcustom org-confirm-elisp-link-not-regexp ""
2228 "A regexp to skip confirmation for Elisp links."
2229 :group 'org-link-follow
2230 :version "24.1"
2231 :type 'regexp)
2233 (defconst org-file-apps-defaults-gnu
2234 '((remote . emacs)
2235 (system . mailcap)
2236 (t . mailcap))
2237 "Default file applications on a UNIX or GNU/Linux system.
2238 See `org-file-apps'.")
2240 (defconst org-file-apps-defaults-macosx
2241 '((remote . emacs)
2242 (system . "open %s")
2243 ("ps.gz" . "gv %s")
2244 ("eps.gz" . "gv %s")
2245 ("dvi" . "xdvi %s")
2246 ("fig" . "xfig %s")
2247 (t . "open %s"))
2248 "Default file applications on a macOS system.
2249 The system \"open\" is known as a default, but we use X11 applications
2250 for some files for which the OS does not have a good default.
2251 See `org-file-apps'.")
2253 (defconst org-file-apps-defaults-windowsnt
2254 (list '(remote . emacs)
2255 (cons 'system (lambda (file _path)
2256 (with-no-warnings (w32-shell-execute "open" file))))
2257 (cons t (lambda (file _path)
2258 (with-no-warnings (w32-shell-execute "open" file)))))
2259 "Default file applications on a Windows NT system.
2260 The system \"open\" is used for most files.
2261 See `org-file-apps'.")
2263 (defcustom org-file-apps
2264 '((auto-mode . emacs)
2265 ("\\.mm\\'" . default)
2266 ("\\.x?html?\\'" . default)
2267 ("\\.pdf\\'" . default))
2268 "External applications for opening `file:path' items in a document.
2269 \\<org-mode-map>\
2271 Org mode uses system defaults for different file types, but
2272 you can use this variable to set the application for a given file
2273 extension. The entries in this list are cons cells where the car identifies
2274 files and the cdr the corresponding command.
2276 Possible values for the file identifier are:
2278 \"string\" A string as a file identifier can be interpreted in different
2279 ways, depending on its contents:
2281 - Alphanumeric characters only:
2282 Match links with this file extension.
2283 Example: (\"pdf\" . \"evince %s\")
2284 to open PDFs with evince.
2286 - Regular expression: Match links where the
2287 filename matches the regexp. If you want to
2288 use groups here, use shy groups.
2290 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2291 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2292 to open *.html and *.xhtml with firefox.
2294 - Regular expression which contains (non-shy) groups:
2295 Match links where the whole link, including \"::\", and
2296 anything after that, matches the regexp.
2297 In a custom command string, %1, %2, etc. are replaced with
2298 the parts of the link that were matched by the groups.
2299 For backwards compatibility, if a command string is given
2300 that does not use any of the group matches, this case is
2301 handled identically to the second one (i.e. match against
2302 file name only).
2303 In a custom function, you can access the group matches with
2304 (match-string n link).
2306 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2307 \"evince -p %1 %s\")
2308 to open [[file:document.pdf::5]] with evince at page 5.
2310 `directory' Matches a directory
2311 `remote' Matches a remote file, accessible through tramp or efs.
2312 Remote files most likely should be visited through Emacs
2313 because external applications cannot handle such paths.
2314 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2315 so all files Emacs knows how to handle. Using this with
2316 command `emacs' will open most files in Emacs. Beware that this
2317 will also open html files inside Emacs, unless you add
2318 (\"html\" . default) to the list as well.
2319 `system' The system command to open files, like `open' on Windows
2320 and macOS, and mailcap under GNU/Linux. This is the command
2321 that will be selected if you call `org-open-at-point' with a
2322 double prefix argument (`\\[universal-argument] \
2323 \\[universal-argument] \\[org-open-at-point]').
2324 t Default for files not matched by any of the other options.
2326 Possible values for the command are:
2328 `emacs' The file will be visited by the current Emacs process.
2329 `default' Use the default application for this file type, which is the
2330 association for t in the list, most likely in the system-specific
2331 part. This can be used to overrule an unwanted setting in the
2332 system-specific variable.
2333 `system' Use the system command for opening files, like \"open\".
2334 This command is specified by the entry whose car is `system'.
2335 Most likely, the system-specific version of this variable
2336 does define this command, but you can overrule/replace it
2337 here.
2338 `mailcap' Use command specified in the mailcaps.
2339 string A command to be executed by a shell; %s will be replaced
2340 by the path to the file.
2341 function A Lisp function, which will be called with two arguments:
2342 the file path and the original link string, without the
2343 \"file:\" prefix.
2345 For more examples, see the system specific constants
2346 `org-file-apps-defaults-macosx'
2347 `org-file-apps-defaults-windowsnt'
2348 `org-file-apps-defaults-gnu'."
2349 :group 'org-link-follow
2350 :type '(repeat
2351 (cons (choice :value ""
2352 (string :tag "Extension")
2353 (const :tag "System command to open files" system)
2354 (const :tag "Default for unrecognized files" t)
2355 (const :tag "Remote file" remote)
2356 (const :tag "Links to a directory" directory)
2357 (const :tag "Any files that have Emacs modes"
2358 auto-mode))
2359 (choice :value ""
2360 (const :tag "Visit with Emacs" emacs)
2361 (const :tag "Use default" default)
2362 (const :tag "Use the system command" system)
2363 (string :tag "Command")
2364 (function :tag "Function")))))
2366 (defcustom org-doi-server-url "http://dx.doi.org/"
2367 "The URL of the DOI server."
2368 :type 'string
2369 :version "24.3"
2370 :group 'org-link-follow)
2372 (defgroup org-refile nil
2373 "Options concerning refiling entries in Org mode."
2374 :tag "Org Refile"
2375 :group 'org)
2377 (defcustom org-directory "~/org"
2378 "Directory with Org files.
2379 This is just a default location to look for Org files. There is no need
2380 at all to put your files into this directory. It is used in the
2381 following situations:
2383 1. When a capture template specifies a target file that is not an
2384 absolute path. The path will then be interpreted relative to
2385 `org-directory'
2386 2. When the value of variable `org-agenda-files' is a single file, any
2387 relative paths in this file will be taken as relative to
2388 `org-directory'."
2389 :group 'org-refile
2390 :group 'org-capture
2391 :type 'directory)
2393 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2394 "Default target for storing notes.
2395 Used as a fall back file for org-capture.el, for templates that
2396 do not specify a target file."
2397 :group 'org-refile
2398 :group 'org-capture
2399 :type 'file)
2401 (defcustom org-goto-interface 'outline
2402 "The default interface to be used for `org-goto'.
2403 Allowed values are:
2404 outline The interface shows an outline of the relevant file
2405 and the correct heading is found by moving through
2406 the outline or by searching with incremental search.
2407 outline-path-completion Headlines in the current buffer are offered via
2408 completion. This is the interface also used by
2409 the refile command."
2410 :group 'org-refile
2411 :type '(choice
2412 (const :tag "Outline" outline)
2413 (const :tag "Outline-path-completion" outline-path-completion)))
2415 (defcustom org-goto-max-level 5
2416 "Maximum target level when running `org-goto' with refile interface."
2417 :group 'org-refile
2418 :type 'integer)
2420 (defcustom org-reverse-note-order nil
2421 "Non-nil means store new notes at the beginning of a file or entry.
2422 When nil, new notes will be filed to the end of a file or entry.
2423 This can also be a list with cons cells of regular expressions that
2424 are matched against file names, and values."
2425 :group 'org-capture
2426 :group 'org-refile
2427 :type '(choice
2428 (const :tag "Reverse always" t)
2429 (const :tag "Reverse never" nil)
2430 (repeat :tag "By file name regexp"
2431 (cons regexp boolean))))
2433 (defcustom org-log-refile nil
2434 "Information to record when a task is refiled.
2436 Possible values are:
2438 nil Don't add anything
2439 time Add a time stamp to the task
2440 note Prompt for a note and add it with template `org-log-note-headings'
2442 This option can also be set with on a per-file-basis with
2444 #+STARTUP: nologrefile
2445 #+STARTUP: logrefile
2446 #+STARTUP: lognoterefile
2448 You can have local logging settings for a subtree by setting the LOGGING
2449 property to one or more of these keywords.
2451 When bulk-refiling from the agenda, the value `note' is forbidden and
2452 will temporarily be changed to `time'."
2453 :group 'org-refile
2454 :group 'org-progress
2455 :version "24.1"
2456 :type '(choice
2457 (const :tag "No logging" nil)
2458 (const :tag "Record timestamp" time)
2459 (const :tag "Record timestamp with note." note)))
2461 (defcustom org-refile-targets nil
2462 "Targets for refiling entries with `\\[org-refile]'.
2463 This is a list of cons cells. Each cell contains:
2464 - a specification of the files to be considered, either a list of files,
2465 or a symbol whose function or variable value will be used to retrieve
2466 a file name or a list of file names. If you use `org-agenda-files' for
2467 that, all agenda files will be scanned for targets. Nil means consider
2468 headings in the current buffer.
2469 - A specification of how to find candidate refile targets. This may be
2470 any of:
2471 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2472 This tag has to be present in all target headlines, inheritance will
2473 not be considered.
2474 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2475 todo keyword.
2476 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2477 headlines that are refiling targets.
2478 - a cons cell (:level . N). Any headline of level N is considered a target.
2479 Note that, when `org-odd-levels-only' is set, level corresponds to
2480 order in hierarchy, not to the number of stars.
2481 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2482 Note that, when `org-odd-levels-only' is set, level corresponds to
2483 order in hierarchy, not to the number of stars.
2485 Each element of this list generates a set of possible targets.
2486 The union of these sets is presented (with completion) to
2487 the user by `org-refile'.
2489 You can set the variable `org-refile-target-verify-function' to a function
2490 to verify each headline found by the simple criteria above.
2492 When this variable is nil, all top-level headlines in the current buffer
2493 are used, equivalent to the value `((nil . (:level . 1))'."
2494 :group 'org-refile
2495 :type '(repeat
2496 (cons
2497 (choice :value org-agenda-files
2498 (const :tag "All agenda files" org-agenda-files)
2499 (const :tag "Current buffer" nil)
2500 (function) (variable) (file))
2501 (choice :tag "Identify target headline by"
2502 (cons :tag "Specific tag" (const :value :tag) (string))
2503 (cons :tag "TODO keyword" (const :value :todo) (string))
2504 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2505 (cons :tag "Level number" (const :value :level) (integer))
2506 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2508 (defcustom org-refile-target-verify-function nil
2509 "Function to verify if the headline at point should be a refile target.
2510 The function will be called without arguments, with point at the
2511 beginning of the headline. It should return t and leave point
2512 where it is if the headline is a valid target for refiling.
2514 If the target should not be selected, the function must return nil.
2515 In addition to this, it may move point to a place from where the search
2516 should be continued. For example, the function may decide that the entire
2517 subtree of the current entry should be excluded and move point to the end
2518 of the subtree."
2519 :group 'org-refile
2520 :type '(choice
2521 (const nil)
2522 (function)))
2524 (defcustom org-refile-use-cache nil
2525 "Non-nil means cache refile targets to speed up the process.
2526 \\<org-mode-map>\
2527 The cache for a particular file will be updated automatically when
2528 the buffer has been killed, or when any of the marker used for flagging
2529 refile targets no longer points at a live buffer.
2530 If you have added new entries to a buffer that might themselves be targets,
2531 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2532 if you find that easier, \
2533 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2534 \\[org-refile]'."
2535 :group 'org-refile
2536 :version "24.1"
2537 :type 'boolean)
2539 (defcustom org-refile-use-outline-path nil
2540 "Non-nil means provide refile targets as paths.
2541 So a level 3 headline will be available as level1/level2/level3.
2543 When the value is `file', also include the file name (without directory)
2544 into the path. In this case, you can also stop the completion after
2545 the file name, to get entries inserted as top level in the file.
2547 When `full-file-path', include the full file path.
2549 When `buffer-name', use the buffer name."
2550 :group 'org-refile
2551 :type '(choice
2552 (const :tag "Not" nil)
2553 (const :tag "Yes" t)
2554 (const :tag "Start with file name" file)
2555 (const :tag "Start with full file path" full-file-path)
2556 (const :tag "Start with buffer name" buffer-name)))
2558 (defcustom org-outline-path-complete-in-steps t
2559 "Non-nil means complete the outline path in hierarchical steps.
2560 When Org uses the refile interface to select an outline path (see
2561 `org-refile-use-outline-path'), the completion of the path can be
2562 done in a single go, or it can be done in steps down the headline
2563 hierarchy. Going in steps is probably the best if you do not use
2564 a special completion package like `ido' or `icicles'. However,
2565 when using these packages, going in one step can be very fast,
2566 while still showing the whole path to the entry."
2567 :group 'org-refile
2568 :type 'boolean)
2570 (defcustom org-refile-allow-creating-parent-nodes nil
2571 "Non-nil means allow the creation of new nodes as refile targets.
2572 New nodes are then created by adding \"/new node name\" to the completion
2573 of an existing node. When the value of this variable is `confirm',
2574 new node creation must be confirmed by the user (recommended).
2575 When nil, the completion must match an existing entry.
2577 Note that, if the new heading is not seen by the criteria
2578 listed in `org-refile-targets', multiple instances of the same
2579 heading would be created by trying again to file under the new
2580 heading."
2581 :group 'org-refile
2582 :type '(choice
2583 (const :tag "Never" nil)
2584 (const :tag "Always" t)
2585 (const :tag "Prompt for confirmation" confirm)))
2587 (defcustom org-refile-active-region-within-subtree nil
2588 "Non-nil means also refile active region within a subtree.
2590 By default `org-refile' doesn't allow refiling regions if they
2591 don't contain a set of subtrees, but it might be convenient to
2592 do so sometimes: in that case, the first line of the region is
2593 converted to a headline before refiling."
2594 :group 'org-refile
2595 :version "24.1"
2596 :type 'boolean)
2598 (defgroup org-todo nil
2599 "Options concerning TODO items in Org mode."
2600 :tag "Org TODO"
2601 :group 'org)
2603 (defgroup org-progress nil
2604 "Options concerning Progress logging in Org mode."
2605 :tag "Org Progress"
2606 :group 'org-time)
2608 (defvar org-todo-interpretation-widgets
2609 '((:tag "Sequence (cycling hits every state)" sequence)
2610 (:tag "Type (cycling directly to DONE)" type))
2611 "The available interpretation symbols for customizing `org-todo-keywords'.
2612 Interested libraries should add to this list.")
2614 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2615 "List of TODO entry keyword sequences and their interpretation.
2616 \\<org-mode-map>This is a list of sequences.
2618 Each sequence starts with a symbol, either `sequence' or `type',
2619 indicating if the keywords should be interpreted as a sequence of
2620 action steps, or as different types of TODO items. The first
2621 keywords are states requiring action - these states will select a headline
2622 for inclusion into the global TODO list Org produces. If one of the
2623 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2624 signify that no further action is necessary. If \"|\" is not found,
2625 the last keyword is treated as the only DONE state of the sequence.
2627 The command `\\[org-todo]' cycles an entry through these states, and one
2628 additional state where no keyword is present. For details about this
2629 cycling, see the manual.
2631 TODO keywords and interpretation can also be set on a per-file basis with
2632 the special #+SEQ_TODO and #+TYP_TODO lines.
2634 Each keyword can optionally specify a character for fast state selection
2635 \(in combination with the variable `org-use-fast-todo-selection')
2636 and specifiers for state change logging, using the same syntax that
2637 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2638 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2639 indicates to record a time stamp each time this state is selected.
2641 Each keyword may also specify if a timestamp or a note should be
2642 recorded when entering or leaving the state, by adding additional
2643 characters in the parenthesis after the keyword. This looks like this:
2644 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2645 record only the time of the state change. With X and Y being either
2646 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2647 Y when leaving the state if and only if the *target* state does not
2648 define X. You may omit any of the fast-selection key or X or /Y,
2649 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2651 For backward compatibility, this variable may also be just a list
2652 of keywords. In this case the interpretation (sequence or type) will be
2653 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2654 :group 'org-todo
2655 :group 'org-keywords
2656 :type '(choice
2657 (repeat :tag "Old syntax, just keywords"
2658 (string :tag "Keyword"))
2659 (repeat :tag "New syntax"
2660 (cons
2661 (choice
2662 :tag "Interpretation"
2663 ;;Quick and dirty way to see
2664 ;;`org-todo-interpretations'. This takes the
2665 ;;place of item arguments
2666 :convert-widget
2667 (lambda (widget)
2668 (widget-put widget
2669 :args (mapcar
2670 (lambda (x)
2671 (widget-convert
2672 (cons 'const x)))
2673 org-todo-interpretation-widgets))
2674 widget))
2675 (repeat
2676 (string :tag "Keyword"))))))
2678 (defvar-local org-todo-keywords-1 nil
2679 "All TODO and DONE keywords active in a buffer.")
2680 (defvar org-todo-keywords-for-agenda nil)
2681 (defvar org-done-keywords-for-agenda nil)
2682 (defvar org-todo-keyword-alist-for-agenda nil)
2683 (defvar org-tag-alist-for-agenda nil
2684 "Alist of all tags from all agenda files.")
2685 (defvar org-tag-groups-alist-for-agenda nil
2686 "Alist of all groups tags from all current agenda files.")
2687 (defvar-local org-tag-groups-alist nil)
2688 (defvar org-agenda-contributing-files nil)
2689 (defvar-local org-current-tag-alist nil
2690 "Alist of all tag groups in current buffer.
2691 This variable takes into consideration `org-tag-alist',
2692 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2693 (defvar-local org-not-done-keywords nil)
2694 (defvar-local org-done-keywords nil)
2695 (defvar-local org-todo-heads nil)
2696 (defvar-local org-todo-sets nil)
2697 (defvar-local org-todo-log-states nil)
2698 (defvar-local org-todo-kwd-alist nil)
2699 (defvar-local org-todo-key-alist nil)
2700 (defvar-local org-todo-key-trigger nil)
2702 (defcustom org-todo-interpretation 'sequence
2703 "Controls how TODO keywords are interpreted.
2704 This variable is in principle obsolete and is only used for
2705 backward compatibility, if the interpretation of todo keywords is
2706 not given already in `org-todo-keywords'. See that variable for
2707 more information."
2708 :group 'org-todo
2709 :group 'org-keywords
2710 :type '(choice (const sequence)
2711 (const type)))
2713 (defcustom org-use-fast-todo-selection t
2714 "\\<org-mode-map>\
2715 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2716 This variable describes if and under what circumstances the cycling
2717 mechanism for TODO keywords will be replaced by a single-key, direct
2718 selection scheme.
2720 When nil, fast selection is never used.
2722 When the symbol `prefix', it will be used when `org-todo' is called
2723 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2724 in an Org buffer, and
2725 `\\[universal-argument] t' in an agenda buffer.
2727 When t, fast selection is used by default. In this case, the prefix
2728 argument forces cycling instead.
2730 In all cases, the special interface is only used if access keys have
2731 actually been assigned by the user, i.e. if keywords in the configuration
2732 are followed by a letter in parenthesis, like TODO(t)."
2733 :group 'org-todo
2734 :type '(choice
2735 (const :tag "Never" nil)
2736 (const :tag "By default" t)
2737 (const :tag "Only with C-u C-c C-t" prefix)))
2739 (defcustom org-provide-todo-statistics t
2740 "Non-nil means update todo statistics after insert and toggle.
2741 ALL-HEADLINES means update todo statistics by including headlines
2742 with no TODO keyword as well, counting them as not done.
2743 A list of TODO keywords means the same, but skip keywords that are
2744 not in this list.
2745 When set to a list of two lists, the first list contains keywords
2746 to consider as TODO keywords, the second list contains keywords
2747 to consider as DONE keywords.
2749 When this is set, todo statistics is updated in the parent of the
2750 current entry each time a todo state is changed."
2751 :group 'org-todo
2752 :type '(choice
2753 (const :tag "Yes, only for TODO entries" t)
2754 (const :tag "Yes, including all entries" all-headlines)
2755 (repeat :tag "Yes, for TODOs in this list"
2756 (string :tag "TODO keyword"))
2757 (list :tag "Yes, for TODOs and DONEs in these lists"
2758 (repeat (string :tag "TODO keyword"))
2759 (repeat (string :tag "DONE keyword")))
2760 (other :tag "No TODO statistics" nil)))
2762 (defcustom org-hierarchical-todo-statistics t
2763 "Non-nil means TODO statistics covers just direct children.
2764 When nil, all entries in the subtree are considered.
2765 This has only an effect if `org-provide-todo-statistics' is set.
2766 To set this to nil for only a single subtree, use a COOKIE_DATA
2767 property and include the word \"recursive\" into the value."
2768 :group 'org-todo
2769 :type 'boolean)
2771 (defcustom org-after-todo-state-change-hook nil
2772 "Hook which is run after the state of a TODO item was changed.
2773 The new state (a string with a TODO keyword, or nil) is available in the
2774 Lisp variable `org-state'."
2775 :group 'org-todo
2776 :type 'hook)
2778 (defvar org-blocker-hook nil
2779 "Hook for functions that are allowed to block a state change.
2781 Functions in this hook should not modify the buffer.
2782 Each function gets as its single argument a property list,
2783 see `org-trigger-hook' for more information about this list.
2785 If any of the functions in this hook returns nil, the state change
2786 is blocked.")
2788 (defvar org-trigger-hook nil
2789 "Hook for functions that are triggered by a state change.
2791 Each function gets as its single argument a property list with at
2792 least the following elements:
2794 (:type type-of-change :position pos-at-entry-start
2795 :from old-state :to new-state)
2797 Depending on the type, more properties may be present.
2799 This mechanism is currently implemented for:
2801 TODO state changes
2802 ------------------
2803 :type todo-state-change
2804 :from previous state (keyword as a string), or nil, or a symbol
2805 `todo' or `done', to indicate the general type of state.
2806 :to new state, like in :from")
2808 (defcustom org-enforce-todo-dependencies nil
2809 "Non-nil means undone TODO entries will block switching the parent to DONE.
2810 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2811 be blocked if any prior sibling is not yet done.
2812 Finally, if the parent is blocked because of ordered siblings of its own,
2813 the child will also be blocked."
2814 :set (lambda (var val)
2815 (set var val)
2816 (if val
2817 (add-hook 'org-blocker-hook
2818 'org-block-todo-from-children-or-siblings-or-parent)
2819 (remove-hook 'org-blocker-hook
2820 'org-block-todo-from-children-or-siblings-or-parent)))
2821 :group 'org-todo
2822 :type 'boolean)
2824 (defcustom org-enforce-todo-checkbox-dependencies nil
2825 "Non-nil means unchecked boxes will block switching the parent to DONE.
2826 When this is nil, checkboxes have no influence on switching TODO states.
2827 When non-nil, you first need to check off all check boxes before the TODO
2828 entry can be switched to DONE.
2829 This variable needs to be set before org.el is loaded, and you need to
2830 restart Emacs after a change to make the change effective. The only way
2831 to change is while Emacs is running is through the customize interface."
2832 :set (lambda (var val)
2833 (set var val)
2834 (if val
2835 (add-hook 'org-blocker-hook
2836 'org-block-todo-from-checkboxes)
2837 (remove-hook 'org-blocker-hook
2838 'org-block-todo-from-checkboxes)))
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-treat-insert-todo-heading-as-state-change nil
2843 "Non-nil means inserting a TODO heading is treated as state change.
2844 So when the command `\\[org-insert-todo-heading]' is used, state change
2845 logging will apply if appropriate. When nil, the new TODO item will
2846 be inserted directly, and no logging will take place."
2847 :group 'org-todo
2848 :type 'boolean)
2850 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2851 "Non-nil means switching TODO states with S-cursor counts as state change.
2852 This is the default behavior. However, setting this to nil allows a
2853 convenient way to select a TODO state and bypass any logging associated
2854 with that."
2855 :group 'org-todo
2856 :type 'boolean)
2858 (defcustom org-todo-state-tags-triggers nil
2859 "Tag changes that should be triggered by TODO state changes.
2860 This is a list. Each entry is
2862 (state-change (tag . flag) .......)
2864 State-change can be a string with a state, and empty string to indicate the
2865 state that has no TODO keyword, or it can be one of the symbols `todo'
2866 or `done', meaning any not-done or done state, respectively."
2867 :group 'org-todo
2868 :group 'org-tags
2869 :type '(repeat
2870 (cons (choice :tag "When changing to"
2871 (const :tag "Not-done state" todo)
2872 (const :tag "Done state" done)
2873 (string :tag "State"))
2874 (repeat
2875 (cons :tag "Tag action"
2876 (string :tag "Tag")
2877 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2879 (defcustom org-log-done nil
2880 "Information to record when a task moves to the DONE state.
2882 Possible values are:
2884 nil Don't add anything, just change the keyword
2885 time Add a time stamp to the task
2886 note Prompt for a note and add it with template `org-log-note-headings'
2888 This option can also be set with on a per-file-basis with
2890 #+STARTUP: nologdone
2891 #+STARTUP: logdone
2892 #+STARTUP: lognotedone
2894 You can have local logging settings for a subtree by setting the LOGGING
2895 property to one or more of these keywords."
2896 :group 'org-todo
2897 :group 'org-progress
2898 :type '(choice
2899 (const :tag "No logging" nil)
2900 (const :tag "Record CLOSED timestamp" time)
2901 (const :tag "Record CLOSED timestamp with note." note)))
2903 ;; Normalize old uses of org-log-done.
2904 (cond
2905 ((eq org-log-done t) (setq org-log-done 'time))
2906 ((and (listp org-log-done) (memq 'done org-log-done))
2907 (setq org-log-done 'note)))
2909 (defcustom org-log-reschedule nil
2910 "Information to record when the scheduling date of a tasks is modified.
2912 Possible values are:
2914 nil Don't add anything, just change the date
2915 time Add a time stamp to the task
2916 note Prompt for a note and add it with template `org-log-note-headings'
2918 This option can also be set with on a per-file-basis with
2920 #+STARTUP: nologreschedule
2921 #+STARTUP: logreschedule
2922 #+STARTUP: lognotereschedule"
2923 :group 'org-todo
2924 :group 'org-progress
2925 :type '(choice
2926 (const :tag "No logging" nil)
2927 (const :tag "Record timestamp" time)
2928 (const :tag "Record timestamp with note." note)))
2930 (defcustom org-log-redeadline nil
2931 "Information to record when the deadline date of a tasks is modified.
2933 Possible values are:
2935 nil Don't add anything, just change the date
2936 time Add a time stamp to the task
2937 note Prompt for a note and add it with template `org-log-note-headings'
2939 This option can also be set with on a per-file-basis with
2941 #+STARTUP: nologredeadline
2942 #+STARTUP: logredeadline
2943 #+STARTUP: lognoteredeadline
2945 You can have local logging settings for a subtree by setting the LOGGING
2946 property to one or more of these keywords."
2947 :group 'org-todo
2948 :group 'org-progress
2949 :type '(choice
2950 (const :tag "No logging" nil)
2951 (const :tag "Record timestamp" time)
2952 (const :tag "Record timestamp with note." note)))
2954 (defcustom org-log-note-clock-out nil
2955 "Non-nil means record a note when clocking out of an item.
2956 This can also be configured on a per-file basis by adding one of
2957 the following lines anywhere in the buffer:
2959 #+STARTUP: lognoteclock-out
2960 #+STARTUP: nolognoteclock-out"
2961 :group 'org-todo
2962 :group 'org-progress
2963 :type 'boolean)
2965 (defcustom org-log-done-with-time t
2966 "Non-nil means the CLOSED time stamp will contain date and time.
2967 When nil, only the date will be recorded."
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-note-headings
2972 '((done . "CLOSING NOTE %t")
2973 (state . "State %-12s from %-12S %t")
2974 (note . "Note taken on %t")
2975 (reschedule . "Rescheduled from %S on %t")
2976 (delschedule . "Not scheduled, was %S on %t")
2977 (redeadline . "New deadline from %S on %t")
2978 (deldeadline . "Removed deadline, was %S on %t")
2979 (refile . "Refiled on %t")
2980 (clock-out . ""))
2981 "Headings for notes added to entries.
2983 The value is an alist, with the car being a symbol indicating the
2984 note context, and the cdr is the heading to be used. The heading
2985 may also be the empty string. The following placeholders can be
2986 used:
2988 %t a time stamp.
2989 %T an active time stamp instead the default inactive one
2990 %d a short-format time stamp.
2991 %D an active short-format time stamp.
2992 %s the new TODO state or time stamp (inactive), in double quotes.
2993 %S the old TODO state or time stamp (inactive), in double quotes.
2994 %u the user name.
2995 %U full user name.
2997 In fact, it is not a good idea to change the `state' entry,
2998 because Agenda Log mode depends on the format of these entries."
2999 :group 'org-todo
3000 :group 'org-progress
3001 :type '(list :greedy t
3002 (cons (const :tag "Heading when closing an item" done) string)
3003 (cons (const :tag
3004 "Heading when changing todo state (todo sequence only)"
3005 state) string)
3006 (cons (const :tag "Heading when just taking a note" note) string)
3007 (cons (const :tag "Heading when rescheduling" reschedule) string)
3008 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3009 (cons (const :tag "Heading when changing deadline" redeadline) string)
3010 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3011 (cons (const :tag "Heading when refiling" refile) string)
3012 (cons (const :tag "Heading when clocking out" clock-out) string)))
3014 (unless (assq 'note org-log-note-headings)
3015 (push '(note . "%t") org-log-note-headings))
3017 (defcustom org-log-into-drawer nil
3018 "Non-nil means insert state change notes and time stamps into a drawer.
3019 When nil, state changes notes will be inserted after the headline and
3020 any scheduling and clock lines, but not inside a drawer.
3022 The value of this variable should be the name of the drawer to use.
3023 LOGBOOK is proposed as the default drawer for this purpose, you can
3024 also set this to a string to define the drawer of your choice.
3026 A value of t is also allowed, representing \"LOGBOOK\".
3028 A value of t or nil can also be set with on a per-file-basis with
3030 #+STARTUP: logdrawer
3031 #+STARTUP: nologdrawer
3033 If this variable is set, `org-log-state-notes-insert-after-drawers'
3034 will be ignored.
3036 You can set the property LOG_INTO_DRAWER to overrule this setting for
3037 a subtree.
3039 Do not check directly this variable in a Lisp program. Call
3040 function `org-log-into-drawer' instead."
3041 :group 'org-todo
3042 :group 'org-progress
3043 :type '(choice
3044 (const :tag "Not into a drawer" nil)
3045 (const :tag "LOGBOOK" t)
3046 (string :tag "Other")))
3048 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3050 (defun org-log-into-drawer ()
3051 "Name of the log drawer, as a string, or nil.
3052 This is the value of `org-log-into-drawer'. However, if the
3053 current entry has or inherits a LOG_INTO_DRAWER property, it will
3054 be used instead of the default value."
3055 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3056 (cond ((equal p "nil") nil)
3057 ((equal p "t") "LOGBOOK")
3058 ((stringp p) p)
3059 (p "LOGBOOK")
3060 ((stringp org-log-into-drawer) org-log-into-drawer)
3061 (org-log-into-drawer "LOGBOOK"))))
3063 (defcustom org-log-state-notes-insert-after-drawers nil
3064 "Non-nil means insert state change notes after any drawers in entry.
3065 Only the drawers that *immediately* follow the headline and the
3066 deadline/scheduled line are skipped.
3067 When nil, insert notes right after the heading and perhaps the line
3068 with deadline/scheduling if present.
3070 This variable will have no effect if `org-log-into-drawer' is
3071 set."
3072 :group 'org-todo
3073 :group 'org-progress
3074 :type 'boolean)
3076 (defcustom org-log-states-order-reversed t
3077 "Non-nil means the latest state note will be directly after heading.
3078 When nil, the state change notes will be ordered according to time.
3080 This option can also be set with on a per-file-basis with
3082 #+STARTUP: logstatesreversed
3083 #+STARTUP: nologstatesreversed"
3084 :group 'org-todo
3085 :group 'org-progress
3086 :type 'boolean)
3088 (defcustom org-todo-repeat-to-state nil
3089 "The TODO state to which a repeater should return the repeating task.
3090 By default this is the first task in a TODO sequence, or the previous state
3091 in a TODO_TYP set. But you can specify another task here.
3092 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3093 :group 'org-todo
3094 :version "24.1"
3095 :type '(choice (const :tag "Head of sequence" nil)
3096 (string :tag "Specific state")))
3098 (defcustom org-log-repeat 'time
3099 "Non-nil means record moving through the DONE state when triggering repeat.
3100 An auto-repeating task is immediately switched back to TODO when
3101 marked DONE. If you are not logging state changes (by adding \"@\"
3102 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3103 record a closing note, there will be no record of the task moving
3104 through DONE. This variable forces taking a note anyway.
3106 nil Don't force a record
3107 time Record a time stamp
3108 note Prompt for a note and add it with template `org-log-note-headings'
3110 This option can also be set with on a per-file-basis with
3112 #+STARTUP: nologrepeat
3113 #+STARTUP: logrepeat
3114 #+STARTUP: lognoterepeat
3116 You can have local logging settings for a subtree by setting the LOGGING
3117 property to one or more of these keywords."
3118 :group 'org-todo
3119 :group 'org-progress
3120 :type '(choice
3121 (const :tag "Don't force a record" nil)
3122 (const :tag "Force recording the DONE state" time)
3123 (const :tag "Force recording a note with the DONE state" note)))
3126 (defgroup org-priorities nil
3127 "Priorities in Org mode."
3128 :tag "Org Priorities"
3129 :group 'org-todo)
3131 (defcustom org-enable-priority-commands t
3132 "Non-nil means priority commands are active.
3133 When nil, these commands will be disabled, so that you never accidentally
3134 set a priority."
3135 :group 'org-priorities
3136 :type 'boolean)
3138 (defcustom org-highest-priority ?A
3139 "The highest priority of TODO items. A character like ?A, ?B etc.
3140 Must have a smaller ASCII number than `org-lowest-priority'."
3141 :group 'org-priorities
3142 :type 'character)
3144 (defcustom org-lowest-priority ?C
3145 "The lowest priority of TODO items. A character like ?A, ?B etc.
3146 Must have a larger ASCII number than `org-highest-priority'."
3147 :group 'org-priorities
3148 :type 'character)
3150 (defcustom org-default-priority ?B
3151 "The default priority of TODO items.
3152 This is the priority an item gets if no explicit priority is given.
3153 When starting to cycle on an empty priority the first step in the cycle
3154 depends on `org-priority-start-cycle-with-default'. The resulting first
3155 step priority must not exceed the range from `org-highest-priority' to
3156 `org-lowest-priority' which means that `org-default-priority' has to be
3157 in this range exclusive or inclusive the range boundaries. Else the
3158 first step refuses to set the default and the second will fall back
3159 to (depending on the command used) the highest or lowest priority."
3160 :group 'org-priorities
3161 :type 'character)
3163 (defcustom org-priority-start-cycle-with-default t
3164 "Non-nil means start with default priority when starting to cycle.
3165 When this is nil, the first step in the cycle will be (depending on the
3166 command used) one higher or lower than the default priority.
3167 See also `org-default-priority'."
3168 :group 'org-priorities
3169 :type 'boolean)
3171 (defcustom org-get-priority-function nil
3172 "Function to extract the priority from a string.
3173 The string is normally the headline. If this is nil Org computes the
3174 priority from the priority cookie like [#A] in the headline. It returns
3175 an integer, increasing by 1000 for each priority level.
3176 The user can set a different function here, which should take a string
3177 as an argument and return the numeric priority."
3178 :group 'org-priorities
3179 :version "24.1"
3180 :type '(choice
3181 (const nil)
3182 (function)))
3184 (defgroup org-time nil
3185 "Options concerning time stamps and deadlines in Org mode."
3186 :tag "Org Time"
3187 :group 'org)
3189 (defcustom org-time-stamp-rounding-minutes '(0 5)
3190 "Number of minutes to round time stamps to.
3191 \\<org-mode-map>\
3192 These are two values, the first applies when first creating a time stamp.
3193 The second applies when changing it with the commands `S-up' and `S-down'.
3194 When changing the time stamp, this means that it will change in steps
3195 of N minutes, as given by the second value.
3197 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3198 numbers should be factors of 60, so for example 5, 10, 15.
3200 When this is larger than 1, you can still force an exact time stamp by using
3201 a double prefix argument to a time stamp command like \
3202 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3203 and by using a prefix arg to `S-up/down' to specify the exact number
3204 of minutes to shift."
3205 :group 'org-time
3206 :get (lambda (var) ; Make sure both elements are there
3207 (if (integerp (default-value var))
3208 (list (default-value var) 5)
3209 (default-value var)))
3210 :type '(list
3211 (integer :tag "when inserting times")
3212 (integer :tag "when modifying times")))
3214 ;; Normalize old customizations of this variable.
3215 (when (integerp org-time-stamp-rounding-minutes)
3216 (setq org-time-stamp-rounding-minutes
3217 (list org-time-stamp-rounding-minutes
3218 org-time-stamp-rounding-minutes)))
3220 (defcustom org-display-custom-times nil
3221 "Non-nil means overlay custom formats over all time stamps.
3222 The formats are defined through the variable `org-time-stamp-custom-formats'.
3223 To turn this on on a per-file basis, insert anywhere in the file:
3224 #+STARTUP: customtime"
3225 :group 'org-time
3226 :set 'set-default
3227 :type 'sexp)
3228 (make-variable-buffer-local 'org-display-custom-times)
3230 (defcustom org-time-stamp-custom-formats
3231 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3232 "Custom formats for time stamps. See `format-time-string' for the syntax.
3233 These are overlaid over the default ISO format if the variable
3234 `org-display-custom-times' is set. Time like %H:%M should be at the
3235 end of the second format. The custom formats are also honored by export
3236 commands, if custom time display is turned on at the time of export."
3237 :group 'org-time
3238 :type 'sexp)
3240 (defun org-time-stamp-format (&optional long inactive)
3241 "Get the right format for a time string."
3242 (let ((f (if long (cdr org-time-stamp-formats)
3243 (car org-time-stamp-formats))))
3244 (if inactive
3245 (concat "[" (substring f 1 -1) "]")
3246 f)))
3248 (defcustom org-deadline-warning-days 14
3249 "Number of days before expiration during which a deadline becomes active.
3250 This variable governs the display in sparse trees and in the agenda.
3251 When 0 or negative, it means use this number (the absolute value of it)
3252 even if a deadline has a different individual lead time specified.
3254 Custom commands can set this variable in the options section."
3255 :group 'org-time
3256 :group 'org-agenda-daily/weekly
3257 :type 'integer)
3259 (defcustom org-scheduled-delay-days 0
3260 "Number of days before a scheduled item becomes active.
3261 This variable governs the display in sparse trees and in the agenda.
3262 The default value (i.e. 0) means: don't delay scheduled item.
3263 When negative, it means use this number (the absolute value of it)
3264 even if a scheduled item has a different individual delay time
3265 specified.
3267 Custom commands can set this variable in the options section."
3268 :group 'org-time
3269 :group 'org-agenda-daily/weekly
3270 :version "24.4"
3271 :package-version '(Org . "8.0")
3272 :type 'integer)
3274 (defcustom org-read-date-prefer-future t
3275 "Non-nil means assume future for incomplete date input from user.
3276 This affects the following situations:
3277 1. The user gives a month but not a year.
3278 For example, if it is April and you enter \"feb 2\", this will be read
3279 as Feb 2, *next* year. \"May 5\", however, will be this year.
3280 2. The user gives a day, but no month.
3281 For example, if today is the 15th, and you enter \"3\", Org will read
3282 this as the third of *next* month. However, if you enter \"17\",
3283 it will be considered as *this* month.
3285 If you set this variable to the symbol `time', then also the following
3286 will work:
3288 3. If the user gives a time.
3289 If the time is before now, it will be interpreted as tomorrow.
3291 Currently none of this works for ISO week specifications.
3293 When this option is nil, the current day, month and year will always be
3294 used as defaults.
3296 See also `org-agenda-jump-prefer-future'."
3297 :group 'org-time
3298 :type '(choice
3299 (const :tag "Never" nil)
3300 (const :tag "Check month and day" t)
3301 (const :tag "Check month, day, and time" time)))
3303 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3304 "Should the agenda jump command prefer the future for incomplete dates?
3305 The default is to do the same as configured in `org-read-date-prefer-future'.
3306 But you can also set a deviating value here.
3307 This may t or nil, or the symbol `org-read-date-prefer-future'."
3308 :group 'org-agenda
3309 :group 'org-time
3310 :version "24.1"
3311 :type '(choice
3312 (const :tag "Use org-read-date-prefer-future"
3313 org-read-date-prefer-future)
3314 (const :tag "Never" nil)
3315 (const :tag "Always" t)))
3317 (defcustom org-read-date-force-compatible-dates t
3318 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3320 Depending on the system Emacs is running on, certain dates cannot
3321 be represented with the type used internally to represent time.
3322 Dates between 1970-1-1 and 2038-1-1 can always be represented
3323 correctly. Some systems allow for earlier dates, some for later,
3324 some for both. One way to find out it to insert any date into an
3325 Org buffer, putting the cursor on the year and hitting S-up and
3326 S-down to test the range.
3328 When this variable is set to t, the date/time prompt will not let
3329 you specify dates outside the 1970-2037 range, so it is certain that
3330 these dates will work in whatever version of Emacs you are
3331 running, and also that you can move a file from one Emacs implementation
3332 to another. WHenever Org is forcing the year for you, it will display
3333 a message and beep.
3335 When this variable is nil, Org will check if the date is
3336 representable in the specific Emacs implementation you are using.
3337 If not, it will force a year, usually the current year, and beep
3338 to remind you. Currently this setting is not recommended because
3339 the likelihood that you will open your Org files in an Emacs that
3340 has limited date range is not negligible.
3342 A workaround for this problem is to use diary sexp dates for time
3343 stamps outside of this range."
3344 :group 'org-time
3345 :version "24.1"
3346 :type 'boolean)
3348 (defcustom org-read-date-display-live t
3349 "Non-nil means display current interpretation of date prompt live.
3350 This display will be in an overlay, in the minibuffer."
3351 :group 'org-time
3352 :type 'boolean)
3354 (defcustom org-read-date-popup-calendar t
3355 "Non-nil means pop up a calendar when prompting for a date.
3356 In the calendar, the date can be selected with mouse-1. However, the
3357 minibuffer will also be active, and you can simply enter the date as well.
3358 When nil, only the minibuffer will be available."
3359 :group 'org-time
3360 :type 'boolean)
3361 (defvaralias 'org-popup-calendar-for-date-prompt
3362 'org-read-date-popup-calendar)
3364 (defcustom org-extend-today-until 0
3365 "The hour when your day really ends. Must be an integer.
3366 This has influence for the following applications:
3367 - When switching the agenda to \"today\". It it is still earlier than
3368 the time given here, the day recognized as TODAY is actually yesterday.
3369 - When a date is read from the user and it is still before the time given
3370 here, the current date and time will be assumed to be yesterday, 23:59.
3371 Also, timestamps inserted in capture templates follow this rule.
3373 IMPORTANT: This is a feature whose implementation is and likely will
3374 remain incomplete. Really, it is only here because past midnight seems to
3375 be the favorite working time of John Wiegley :-)"
3376 :group 'org-time
3377 :type 'integer)
3379 (defcustom org-use-effective-time nil
3380 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3381 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3382 \"effective time\" of any timestamps between midnight and 8am will be
3383 23:59 of the previous day."
3384 :group 'org-time
3385 :version "24.1"
3386 :type 'boolean)
3388 (defcustom org-use-last-clock-out-time-as-effective-time nil
3389 "When non-nil, use the last clock out time for `org-todo'.
3390 Note that this option has precedence over the combined use of
3391 `org-use-effective-time' and `org-extend-today-until'."
3392 :group 'org-time
3393 :version "24.4"
3394 :package-version '(Org . "8.0")
3395 :type 'boolean)
3397 (defcustom org-edit-timestamp-down-means-later nil
3398 "Non-nil means S-down will increase the time in a time stamp.
3399 When nil, S-up will increase."
3400 :group 'org-time
3401 :type 'boolean)
3403 (defcustom org-calendar-follow-timestamp-change t
3404 "Non-nil means make the calendar window follow timestamp changes.
3405 When a timestamp is modified and the calendar window is visible, it will be
3406 moved to the new date."
3407 :group 'org-time
3408 :type 'boolean)
3410 (defgroup org-tags nil
3411 "Options concerning tags in Org mode."
3412 :tag "Org Tags"
3413 :group 'org)
3415 (defcustom org-tag-alist nil
3416 "Default tags available in Org files.
3418 The value of this variable is an alist. Associations either:
3420 (TAG)
3421 (TAG . SELECT)
3422 (SPECIAL)
3424 where TAG is a tag as a string, SELECT is character, used to
3425 select that tag through the fast tag selection interface, and
3426 SPECIAL is one of the following keywords: `:startgroup',
3427 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3428 `:newline'. These keywords are used to define a hierarchy of
3429 tags. See manual for details.
3431 When this variable is nil, Org mode bases tag input on what is
3432 already in the buffer. The value can be overridden locally by
3433 using a TAGS keyword, e.g.,
3435 #+TAGS: tag1 tag2
3437 See also `org-tag-persistent-alist' to sidestep this behavior."
3438 :group 'org-tags
3439 :type '(repeat
3440 (choice
3441 (cons :tag "Tag with key"
3442 (string :tag "Tag name")
3443 (character :tag "Access char"))
3444 (list :tag "Tag" (string :tag "Tag name"))
3445 (const :tag "Start radio group" (:startgroup))
3446 (const :tag "Start tag group, non distinct" (:startgrouptag))
3447 (const :tag "Group tags delimiter" (:grouptags))
3448 (const :tag "End radio group" (:endgroup))
3449 (const :tag "End tag group, non distinct" (:endgrouptag))
3450 (const :tag "New line" (:newline)))))
3452 (defcustom org-tag-persistent-alist nil
3453 "Tags always available in Org files.
3455 The value of this variable is an alist. Associations either:
3457 (TAG)
3458 (TAG . SELECT)
3459 (SPECIAL)
3461 where TAG is a tag as a string, SELECT is a character, used to
3462 select that tag through the fast tag selection interface, and
3463 SPECIAL is one of the following keywords: `:startgroup',
3464 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3465 `:newline'. These keywords are used to define a hierarchy of
3466 tags. See manual for details.
3468 Unlike to `org-tag-alist', tags defined in this variable do not
3469 depend on a local TAGS keyword. Instead, to disable these tags
3470 on a per-file basis, insert anywhere in the file:
3472 #+STARTUP: noptag"
3473 :group 'org-tags
3474 :type '(repeat
3475 (choice
3476 (cons :tag "Tag with key"
3477 (string :tag "Tag name")
3478 (character :tag "Access char"))
3479 (list :tag "Tag" (string :tag "Tag name"))
3480 (const :tag "Start radio group" (:startgroup))
3481 (const :tag "Start tag group, non distinct" (:startgrouptag))
3482 (const :tag "Group tags delimiter" (:grouptags))
3483 (const :tag "End radio group" (:endgroup))
3484 (const :tag "End tag group, non distinct" (:endgrouptag))
3485 (const :tag "New line" (:newline)))))
3487 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3488 "If non-nil, always offer completion for all tags of all agenda files.
3489 Instead of customizing this variable directly, you might want to
3490 set it locally for capture buffers, because there no list of
3491 tags in that file can be created dynamically (there are none).
3493 (add-hook \\='org-capture-mode-hook
3494 (lambda ()
3495 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3496 :group 'org-tags
3497 :version "24.1"
3498 :type 'boolean)
3500 (defvar org-file-tags nil
3501 "List of tags that can be inherited by all entries in the file.
3502 The tags will be inherited if the variable `org-use-tag-inheritance'
3503 says they should be.
3504 This variable is populated from #+FILETAGS lines.")
3506 (defcustom org-use-fast-tag-selection 'auto
3507 "Non-nil means use fast tag selection scheme.
3508 This is a special interface to select and deselect tags with single keys.
3509 When nil, fast selection is never used.
3510 When the symbol `auto', fast selection is used if and only if selection
3511 characters for tags have been configured, either through the variable
3512 `org-tag-alist' or through a #+TAGS line in the buffer.
3513 When t, fast selection is always used and selection keys are assigned
3514 automatically if necessary."
3515 :group 'org-tags
3516 :type '(choice
3517 (const :tag "Always" t)
3518 (const :tag "Never" nil)
3519 (const :tag "When selection characters are configured" auto)))
3521 (defcustom org-fast-tag-selection-single-key nil
3522 "Non-nil means fast tag selection exits after first change.
3523 When nil, you have to press RET to exit it.
3524 During fast tag selection, you can toggle this flag with `C-c'.
3525 This variable can also have the value `expert'. In this case, the window
3526 displaying the tags menu is not even shown, until you press C-c again."
3527 :group 'org-tags
3528 :type '(choice
3529 (const :tag "No" nil)
3530 (const :tag "Yes" t)
3531 (const :tag "Expert" expert)))
3533 (defvar org-fast-tag-selection-include-todo nil
3534 "Non-nil means fast tags selection interface will also offer TODO states.
3535 This is an undocumented feature, you should not rely on it.")
3537 (defcustom org-tags-column -77
3538 "The column to which tags should be indented in a headline.
3539 If this number is positive, it specifies the column. If it is negative,
3540 it means that the tags should be flushright to that column. For example,
3541 -80 works well for a normal 80 character screen.
3542 When 0, place tags directly after headline text, with only one space in
3543 between."
3544 :group 'org-tags
3545 :type 'integer)
3547 (defcustom org-auto-align-tags t
3548 "Non-nil keeps tags aligned when modifying headlines.
3549 Some operations (i.e. demoting) change the length of a headline and
3550 therefore shift the tags around. With this option turned on, after
3551 each such operation the tags are again aligned to `org-tags-column'."
3552 :group 'org-tags
3553 :type 'boolean)
3555 (defcustom org-use-tag-inheritance t
3556 "Non-nil means tags in levels apply also for sublevels.
3557 When nil, only the tags directly given in a specific line apply there.
3558 This may also be a list of tags that should be inherited, or a regexp that
3559 matches tags that should be inherited. Additional control is possible
3560 with the variable `org-tags-exclude-from-inheritance' which gives an
3561 explicit list of tags to be excluded from inheritance, even if the value of
3562 `org-use-tag-inheritance' would select it for inheritance.
3564 If this option is t, a match early-on in a tree can lead to a large
3565 number of matches in the subtree when constructing the agenda or creating
3566 a sparse tree. If you only want to see the first match in a tree during
3567 a search, check out the variable `org-tags-match-list-sublevels'."
3568 :group 'org-tags
3569 :type '(choice
3570 (const :tag "Not" nil)
3571 (const :tag "Always" t)
3572 (repeat :tag "Specific tags" (string :tag "Tag"))
3573 (regexp :tag "Tags matched by regexp")))
3575 (defcustom org-tags-exclude-from-inheritance nil
3576 "List of tags that should never be inherited.
3577 This is a way to exclude a few tags from inheritance. For way to do
3578 the opposite, to actively allow inheritance for selected tags,
3579 see the variable `org-use-tag-inheritance'."
3580 :group 'org-tags
3581 :type '(repeat (string :tag "Tag")))
3583 (defun org-tag-inherit-p (tag)
3584 "Check if TAG is one that should be inherited."
3585 (cond
3586 ((member tag org-tags-exclude-from-inheritance) nil)
3587 ((eq org-use-tag-inheritance t) t)
3588 ((not org-use-tag-inheritance) nil)
3589 ((stringp org-use-tag-inheritance)
3590 (string-match org-use-tag-inheritance tag))
3591 ((listp org-use-tag-inheritance)
3592 (member tag org-use-tag-inheritance))
3593 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3595 (defcustom org-tags-match-list-sublevels t
3596 "Non-nil means list also sublevels of headlines matching a search.
3597 This variable applies to tags/property searches, and also to stuck
3598 projects because this search is based on a tags match as well.
3600 When set to the symbol `indented', sublevels are indented with
3601 leading dots.
3603 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3604 the sublevels of a headline matching a tag search often also match
3605 the same search. Listing all of them can create very long lists.
3606 Setting this variable to nil causes subtrees of a match to be skipped.
3608 This variable is semi-obsolete and probably should always be true. It
3609 is better to limit inheritance to certain tags using the variables
3610 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3611 :group 'org-tags
3612 :type '(choice
3613 (const :tag "No, don't list them" nil)
3614 (const :tag "Yes, do list them" t)
3615 (const :tag "List them, indented with leading dots" indented)))
3617 (defcustom org-tags-sort-function nil
3618 "When set, tags are sorted using this function as a comparator."
3619 :group 'org-tags
3620 :type '(choice
3621 (const :tag "No sorting" nil)
3622 (const :tag "Alphabetical" string<)
3623 (const :tag "Reverse alphabetical" string>)
3624 (function :tag "Custom function" nil)))
3626 (defvar org-tags-history nil
3627 "History of minibuffer reads for tags.")
3628 (defvar org-last-tags-completion-table nil
3629 "The last used completion table for tags.")
3630 (defvar org-after-tags-change-hook nil
3631 "Hook that is run after the tags in a line have changed.")
3633 (defgroup org-properties nil
3634 "Options concerning properties in Org mode."
3635 :tag "Org Properties"
3636 :group 'org)
3638 (defcustom org-property-format "%-10s %s"
3639 "How property key/value pairs should be formatted by `indent-line'.
3640 When `indent-line' hits a property definition, it will format the line
3641 according to this format, mainly to make sure that the values are
3642 lined-up with respect to each other."
3643 :group 'org-properties
3644 :type 'string)
3646 (defcustom org-properties-postprocess-alist nil
3647 "Alist of properties and functions to adjust inserted values.
3648 Elements of this alist must be of the form
3650 ([string] [function])
3652 where [string] must be a property name and [function] must be a
3653 lambda expression: this lambda expression must take one argument,
3654 the value to adjust, and return the new value as a string.
3656 For example, this element will allow the property \"Remaining\"
3657 to be updated wrt the relation between the \"Effort\" property
3658 and the clock summary:
3660 ((\"Remaining\" (lambda(value)
3661 (let ((clocksum (org-clock-sum-current-item))
3662 (effort (org-duration-to-minutes
3663 (org-entry-get (point) \"Effort\"))))
3664 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3665 :group 'org-properties
3666 :version "24.1"
3667 :type '(alist :key-type (string :tag "Property")
3668 :value-type (function :tag "Function")))
3670 (defcustom org-use-property-inheritance nil
3671 "Non-nil means properties apply also for sublevels.
3673 This setting is chiefly used during property searches. Turning it on can
3674 cause significant overhead when doing a search, which is why it is not
3675 on by default.
3677 When nil, only the properties directly given in the current entry count.
3678 When t, every property is inherited. The value may also be a list of
3679 properties that should have inheritance, or a regular expression matching
3680 properties that should be inherited.
3682 However, note that some special properties use inheritance under special
3683 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3684 and the properties ending in \"_ALL\" when they are used as descriptor
3685 for valid values of a property.
3687 Note for programmers:
3688 When querying an entry with `org-entry-get', you can control if inheritance
3689 should be used. By default, `org-entry-get' looks only at the local
3690 properties. You can request inheritance by setting the inherit argument
3691 to t (to force inheritance) or to `selective' (to respect the setting
3692 in this variable)."
3693 :group 'org-properties
3694 :type '(choice
3695 (const :tag "Not" nil)
3696 (const :tag "Always" t)
3697 (repeat :tag "Specific properties" (string :tag "Property"))
3698 (regexp :tag "Properties matched by regexp")))
3700 (defun org-property-inherit-p (property)
3701 "Return a non-nil value if PROPERTY should be inherited."
3702 (cond
3703 ((eq org-use-property-inheritance t) t)
3704 ((not org-use-property-inheritance) nil)
3705 ((stringp org-use-property-inheritance)
3706 (string-match org-use-property-inheritance property))
3707 ((listp org-use-property-inheritance)
3708 (member-ignore-case property org-use-property-inheritance))
3709 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3711 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3712 "The default column format, if no other format has been defined.
3713 This variable can be set on the per-file basis by inserting a line
3715 #+COLUMNS: %25ITEM ....."
3716 :group 'org-properties
3717 :type 'string)
3719 (defcustom org-columns-ellipses ".."
3720 "The ellipses to be used when a field in column view is truncated.
3721 When this is the empty string, as many characters as possible are shown,
3722 but then there will be no visual indication that the field has been truncated.
3723 When this is a string of length N, the last N characters of a truncated
3724 field are replaced by this string. If the column is narrower than the
3725 ellipses string, only part of the ellipses string will be shown."
3726 :group 'org-properties
3727 :type 'string)
3729 (defconst org-global-properties-fixed
3730 '(("VISIBILITY_ALL" . "folded children content all")
3731 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3732 "List of property/value pairs that can be inherited by any entry.
3734 These are fixed values, for the preset properties. The user variable
3735 that can be used to add to this list is `org-global-properties'.
3737 The entries in this list are cons cells where the car is a property
3738 name and cdr is a string with the value. If the value represents
3739 multiple items like an \"_ALL\" property, separate the items by
3740 spaces.")
3742 (defcustom org-global-properties nil
3743 "List of property/value pairs that can be inherited by any entry.
3745 This list will be combined with the constant `org-global-properties-fixed'.
3747 The entries in this list are cons cells where the car is a property
3748 name and cdr is a string with the value.
3750 You can set buffer-local values for the same purpose in the variable
3751 `org-file-properties' this by adding lines like
3753 #+PROPERTY: NAME VALUE"
3754 :group 'org-properties
3755 :type '(repeat
3756 (cons (string :tag "Property")
3757 (string :tag "Value"))))
3759 (defvar-local org-file-properties nil
3760 "List of property/value pairs that can be inherited by any entry.
3761 Valid for the current buffer.
3762 This variable is populated from #+PROPERTY lines.")
3764 (defgroup org-agenda nil
3765 "Options concerning agenda views in Org mode."
3766 :tag "Org Agenda"
3767 :group 'org)
3769 (defvar-local org-category nil
3770 "Variable used by org files to set a category for agenda display.
3771 Such files should use a file variable to set it, for example
3773 # -*- mode: org; org-category: \"ELisp\"
3775 or contain a special line
3777 #+CATEGORY: ELisp
3779 If the file does not specify a category, then file's base name
3780 is used instead.")
3781 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3783 (defcustom org-agenda-files nil
3784 "The files to be used for agenda display.
3786 If an entry is a directory, all files in that directory that are matched
3787 by `org-agenda-file-regexp' will be part of the file list.
3789 If the value of the variable is not a list but a single file name, then
3790 the list of agenda files is actually stored and maintained in that file,
3791 one agenda file per line. In this file paths can be given relative to
3792 `org-directory'. Tilde expansion and environment variable substitution
3793 are also made.
3795 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3796 and removed with `\\[org-remove-file]'."
3797 :group 'org-agenda
3798 :type '(choice
3799 (repeat :tag "List of files and directories" file)
3800 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3802 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3803 "Regular expression to match files for `org-agenda-files'.
3804 If any element in the list in that variable contains a directory instead
3805 of a normal file, all files in that directory that are matched by this
3806 regular expression will be included."
3807 :group 'org-agenda
3808 :type 'regexp)
3810 (defcustom org-agenda-text-search-extra-files nil
3811 "List of extra files to be searched by text search commands.
3812 These files will be searched in addition to the agenda files by the
3813 commands `org-search-view' (`\\[org-agenda] s') \
3814 and `org-occur-in-agenda-files'.
3815 Note that these files will only be searched for text search commands,
3816 not for the other agenda views like todo lists, tag searches or the weekly
3817 agenda. This variable is intended to list notes and possibly archive files
3818 that should also be searched by these two commands.
3819 In fact, if the first element in the list is the symbol `agenda-archives',
3820 then all archive files of all agenda files will be added to the search
3821 scope."
3822 :group 'org-agenda
3823 :type '(set :greedy t
3824 (const :tag "Agenda Archives" agenda-archives)
3825 (repeat :inline t (file))))
3827 (defvaralias 'org-agenda-multi-occur-extra-files
3828 'org-agenda-text-search-extra-files)
3830 (defcustom org-agenda-skip-unavailable-files nil
3831 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3832 A nil value means to remove them, after a query, from the list."
3833 :group 'org-agenda
3834 :type 'boolean)
3836 (defcustom org-calendar-to-agenda-key [?c]
3837 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3838 The command `org-calendar-goto-agenda' will be bound to this key. The
3839 default is the character `c' because then `c' can be used to switch back and
3840 forth between agenda and calendar."
3841 :group 'org-agenda
3842 :type 'sexp)
3844 (defcustom org-calendar-insert-diary-entry-key [?i]
3845 "The key to be installed in `calendar-mode-map' for adding diary entries.
3846 This option is irrelevant until `org-agenda-diary-file' has been configured
3847 to point to an Org file. When that is the case, the command
3848 `org-agenda-diary-entry' will be bound to the key given here, by default
3849 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3850 if you want to continue doing this, you need to change this to a different
3851 key."
3852 :group 'org-agenda
3853 :type 'sexp)
3855 (defcustom org-agenda-diary-file 'diary-file
3856 "File to which to add new entries with the `i' key in agenda and calendar.
3857 When this is the symbol `diary-file', the functionality in the Emacs
3858 calendar will be used to add entries to the `diary-file'. But when this
3859 points to a file, `org-agenda-diary-entry' will be used instead."
3860 :group 'org-agenda
3861 :type '(choice
3862 (const :tag "The standard Emacs diary file" diary-file)
3863 (file :tag "Special Org file diary entries")))
3865 (eval-after-load "calendar"
3866 '(progn
3867 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3868 'org-calendar-goto-agenda)
3869 (add-hook 'calendar-mode-hook
3870 (lambda ()
3871 (unless (eq org-agenda-diary-file 'diary-file)
3872 (define-key calendar-mode-map
3873 org-calendar-insert-diary-entry-key
3874 'org-agenda-diary-entry))))))
3876 (defgroup org-latex nil
3877 "Options for embedding LaTeX code into Org mode."
3878 :tag "Org LaTeX"
3879 :group 'org)
3881 (defcustom org-format-latex-options
3882 '(:foreground default :background default :scale 1.0
3883 :html-foreground "Black" :html-background "Transparent"
3884 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3885 "Options for creating images from LaTeX fragments.
3886 This is a property list with the following properties:
3887 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3888 `default' means use the foreground of the default face.
3889 `auto' means use the foreground from the text face.
3890 :background the background color, or \"Transparent\".
3891 `default' means use the background of the default face.
3892 `auto' means use the background from the text face.
3893 :scale a scaling factor for the size of the images, to get more pixels
3894 :html-foreground, :html-background, :html-scale
3895 the same numbers for HTML export.
3896 :matchers a list indicating which matchers should be used to
3897 find LaTeX fragments. Valid members of this list are:
3898 \"begin\" find environments
3899 \"$1\" find single characters surrounded by $.$
3900 \"$\" find math expressions surrounded by $...$
3901 \"$$\" find math expressions surrounded by $$....$$
3902 \"\\(\" find math expressions surrounded by \\(...\\)
3903 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3904 :group 'org-latex
3905 :type 'plist)
3907 (defcustom org-format-latex-signal-error t
3908 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3909 When nil, just push out a message."
3910 :group 'org-latex
3911 :version "24.1"
3912 :type 'boolean)
3914 (defcustom org-latex-to-mathml-jar-file nil
3915 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3916 Use this to specify additional executable file say a jar file.
3918 When using MathToWeb as the converter, specify the full-path to
3919 your mathtoweb.jar file."
3920 :group 'org-latex
3921 :version "24.1"
3922 :type '(choice
3923 (const :tag "None" nil)
3924 (file :tag "JAR file" :must-match t)))
3926 (defcustom org-latex-to-mathml-convert-command nil
3927 "Command to convert LaTeX fragments to MathML.
3928 Replace format-specifiers in the command as noted below and use
3929 `shell-command' to convert LaTeX to MathML.
3930 %j: Executable file in fully expanded form as specified by
3931 `org-latex-to-mathml-jar-file'.
3932 %I: Input LaTeX file in fully expanded form.
3933 %i: The latex fragment to be converted.
3934 %o: Output MathML file.
3936 This command is used by `org-create-math-formula'.
3938 When using MathToWeb as the converter, set this option to
3939 \"java -jar %j -unicode -force -df %o %I\".
3941 When using LaTeXML set this option to
3942 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3943 :group 'org-latex
3944 :version "24.1"
3945 :type '(choice
3946 (const :tag "None" nil)
3947 (string :tag "\nShell command")))
3949 (defcustom org-preview-latex-default-process 'dvipng
3950 "The default process to convert LaTeX fragments to image files.
3951 All available processes and theirs documents can be found in
3952 `org-preview-latex-process-alist', which see."
3953 :group 'org-latex
3954 :version "26.1"
3955 :package-version '(Org . "9.0")
3956 :type 'symbol)
3958 (defcustom org-preview-latex-process-alist
3959 '((dvipng
3960 :programs ("latex" "dvipng")
3961 :description "dvi > png"
3962 :message "you need to install the programs: latex and dvipng."
3963 :image-input-type "dvi"
3964 :image-output-type "png"
3965 :image-size-adjust (1.0 . 1.0)
3966 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3967 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3968 (dvisvgm
3969 :programs ("latex" "dvisvgm")
3970 :description "dvi > svg"
3971 :message "you need to install the programs: latex and dvisvgm."
3972 :use-xcolor t
3973 :image-input-type "dvi"
3974 :image-output-type "svg"
3975 :image-size-adjust (1.7 . 1.5)
3976 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3977 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3978 (imagemagick
3979 :programs ("latex" "convert")
3980 :description "pdf > png"
3981 :message "you need to install the programs: latex and imagemagick."
3982 :use-xcolor t
3983 :image-input-type "pdf"
3984 :image-output-type "png"
3985 :image-size-adjust (1.0 . 1.0)
3986 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3987 :image-converter
3988 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3989 "Definitions of external processes for LaTeX previewing.
3990 Org mode can use some external commands to generate TeX snippet's images for
3991 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3992 `org-create-formula-image' how to call them.
3994 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3995 PROPERTIES accepts the following attributes:
3997 :programs list of strings, required programs.
3998 :description string, describe the process.
3999 :message string, message it when required programs cannot be found.
4000 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4001 :image-output-type string, output file type of image converter (e.g., \"png\").
4002 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4003 deal with background and foreground color of image.
4004 Otherwise, dvipng style background and foreground color
4005 format are generated. You may then refer to them in
4006 command options with \"%F\" and \"%B\".
4007 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4008 image size showed in buffer and the cdr element is for
4009 HTML file. This option is only useful for process
4010 developers, users should use variable
4011 `org-format-latex-options' instead.
4012 :post-clean list of strings, files matched are to be cleaned up once
4013 the image is generated. When nil, the files with \".dvi\",
4014 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4015 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4016 be cleaned up.
4017 :latex-header list of strings, the LaTeX header of the snippet file.
4018 When nil, the fallback value is used instead, which is
4019 controlled by `org-format-latex-header',
4020 `org-latex-default-packages-alist' and
4021 `org-latex-packages-alist', which see.
4022 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4023 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4024 replaced with values defined below.
4025 :image-converter list of image converter commands strings. Each of them is
4026 given to the shell and supports any of the following
4027 place-holders defined below.
4029 Place-holders used by `:image-converter' and `:latex-compiler':
4031 %f input file name
4032 %b base name of input file
4033 %o base directory of input file
4034 %O absolute output file name
4036 Place-holders only used by `:image-converter':
4038 %F foreground of image
4039 %B background of image
4040 %D dpi, which is used to adjust image size by some processing commands.
4041 %S the image size scale ratio, which is used to adjust image size by some
4042 processing commands."
4043 :group 'org-latex
4044 :version "26.1"
4045 :package-version '(Org . "9.0")
4046 :type '(alist :tag "LaTeX to image backends"
4047 :value-type (plist)))
4049 (defcustom org-preview-latex-image-directory "ltximg/"
4050 "Path to store latex preview images.
4051 A relative path here creates many directories relative to the
4052 processed org files paths. An absolute path puts all preview
4053 images at the same place."
4054 :group 'org-latex
4055 :version "26.1"
4056 :package-version '(Org . "9.0")
4057 :type 'string)
4059 (defun org-format-latex-mathml-available-p ()
4060 "Return t if `org-latex-to-mathml-convert-command' is usable."
4061 (save-match-data
4062 (when (and (boundp 'org-latex-to-mathml-convert-command)
4063 org-latex-to-mathml-convert-command)
4064 (let ((executable (car (split-string
4065 org-latex-to-mathml-convert-command))))
4066 (when (executable-find executable)
4067 (if (string-match
4068 "%j" org-latex-to-mathml-convert-command)
4069 (file-readable-p org-latex-to-mathml-jar-file)
4070 t))))))
4072 (defcustom org-format-latex-header "\\documentclass{article}
4073 \\usepackage[usenames]{color}
4074 \[PACKAGES]
4075 \[DEFAULT-PACKAGES]
4076 \\pagestyle{empty} % do not remove
4077 % The settings below are copied from fullpage.sty
4078 \\setlength{\\textwidth}{\\paperwidth}
4079 \\addtolength{\\textwidth}{-3cm}
4080 \\setlength{\\oddsidemargin}{1.5cm}
4081 \\addtolength{\\oddsidemargin}{-2.54cm}
4082 \\setlength{\\evensidemargin}{\\oddsidemargin}
4083 \\setlength{\\textheight}{\\paperheight}
4084 \\addtolength{\\textheight}{-\\headheight}
4085 \\addtolength{\\textheight}{-\\headsep}
4086 \\addtolength{\\textheight}{-\\footskip}
4087 \\addtolength{\\textheight}{-3cm}
4088 \\setlength{\\topmargin}{1.5cm}
4089 \\addtolength{\\topmargin}{-2.54cm}"
4090 "The document header used for processing LaTeX fragments.
4091 It is imperative that this header make sure that no page number
4092 appears on the page. The package defined in the variables
4093 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4094 will either replace the placeholder \"[PACKAGES]\" in this
4095 header, or they will be appended."
4096 :group 'org-latex
4097 :type 'string)
4099 (defun org-set-packages-alist (var val)
4100 "Set the packages alist and make sure it has 3 elements per entry."
4101 (set var (mapcar (lambda (x)
4102 (if (and (consp x) (= (length x) 2))
4103 (list (car x) (nth 1 x) t)
4105 val)))
4107 (defun org-get-packages-alist (var)
4108 "Get the packages alist and make sure it has 3 elements per entry."
4109 (mapcar (lambda (x)
4110 (if (and (consp x) (= (length x) 2))
4111 (list (car x) (nth 1 x) t)
4113 (default-value var)))
4115 (defcustom org-latex-default-packages-alist
4116 '(("AUTO" "inputenc" t ("pdflatex"))
4117 ("T1" "fontenc" t ("pdflatex"))
4118 ("" "graphicx" t)
4119 ("" "grffile" t)
4120 ("" "longtable" nil)
4121 ("" "wrapfig" nil)
4122 ("" "rotating" nil)
4123 ("normalem" "ulem" t)
4124 ("" "amsmath" t)
4125 ("" "textcomp" t)
4126 ("" "amssymb" t)
4127 ("" "capt-of" nil)
4128 ("" "hyperref" nil))
4129 "Alist of default packages to be inserted in the header.
4131 Change this only if one of the packages here causes an
4132 incompatibility with another package you are using.
4134 The packages in this list are needed by one part or another of
4135 Org mode to function properly:
4137 - inputenc, fontenc: for basic font and character selection
4138 - graphicx: for including images
4139 - grffile: allow periods and spaces in graphics file names
4140 - longtable: For multipage tables
4141 - wrapfig: for figure placement
4142 - rotating: for sideways figures and tables
4143 - ulem: for underline and strike-through
4144 - amsmath: for subscript and superscript and math environments
4145 - textcomp, amssymb: for various symbols used
4146 for interpreting the entities in `org-entities'. You can skip
4147 some of these packages if you don't use any of their symbols.
4148 - capt-of: for captions outside of floats
4149 - hyperref: for cross references
4151 Therefore you should not modify this variable unless you know
4152 what you are doing. The one reason to change it anyway is that
4153 you might be loading some other package that conflicts with one
4154 of the default packages. Each element is either a cell or
4155 a string.
4157 A cell is of the format
4159 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4161 If SNIPPET-FLAG is non-nil, the package also needs to be included
4162 when compiling LaTeX snippets into images for inclusion into
4163 non-LaTeX output. COMPILERS is a list of compilers that should
4164 include the package, see `org-latex-compiler'. If the document
4165 compiler is not in the list, and the list is non-nil, the package
4166 will not be inserted in the final document.
4168 A string will be inserted as-is in the header of the document."
4169 :group 'org-latex
4170 :group 'org-export-latex
4171 :set 'org-set-packages-alist
4172 :get 'org-get-packages-alist
4173 :version "26.1"
4174 :package-version '(Org . "8.3")
4175 :type '(repeat
4176 (choice
4177 (list :tag "options/package pair"
4178 (string :tag "options")
4179 (string :tag "package")
4180 (boolean :tag "Snippet"))
4181 (string :tag "A line of LaTeX"))))
4183 (defcustom org-latex-packages-alist nil
4184 "Alist of packages to be inserted in every LaTeX header.
4186 These will be inserted after `org-latex-default-packages-alist'.
4187 Each element is either a cell or a string.
4189 A cell is of the format:
4191 (\"options\" \"package\" SNIPPET-FLAG)
4193 SNIPPET-FLAG, when non-nil, indicates that this package is also
4194 needed when turning LaTeX snippets into images for inclusion into
4195 non-LaTeX output.
4197 A string will be inserted as-is in the header of the document.
4199 Make sure that you only list packages here which:
4201 - you want in every file;
4202 - do not conflict with the setup in `org-format-latex-header';
4203 - do not conflict with the default packages in
4204 `org-latex-default-packages-alist'."
4205 :group 'org-latex
4206 :group 'org-export-latex
4207 :set 'org-set-packages-alist
4208 :get 'org-get-packages-alist
4209 :type '(repeat
4210 (choice
4211 (list :tag "options/package pair"
4212 (string :tag "options")
4213 (string :tag "package")
4214 (boolean :tag "Snippet"))
4215 (string :tag "A line of LaTeX"))))
4217 (defgroup org-appearance nil
4218 "Settings for Org mode appearance."
4219 :tag "Org Appearance"
4220 :group 'org)
4222 (defcustom org-level-color-stars-only nil
4223 "Non-nil means fontify only the stars in each headline.
4224 When nil, the entire headline is fontified.
4225 Changing it requires restart of `font-lock-mode' to become effective
4226 also in regions already fontified."
4227 :group 'org-appearance
4228 :type 'boolean)
4230 (defcustom org-hide-leading-stars nil
4231 "Non-nil means hide the first N-1 stars in a headline.
4232 This works by using the face `org-hide' for these stars. This
4233 face is white for a light background, and black for a dark
4234 background. You may have to customize the face `org-hide' to
4235 make this work.
4236 Changing it requires restart of `font-lock-mode' to become effective
4237 also in regions already fontified.
4238 You may also set this on a per-file basis by adding one of the following
4239 lines to the buffer:
4241 #+STARTUP: hidestars
4242 #+STARTUP: showstars"
4243 :group 'org-appearance
4244 :type 'boolean)
4246 (defcustom org-hidden-keywords nil
4247 "List of symbols corresponding to keywords to be hidden the org buffer.
4248 For example, a value \\='(title) for this list will make the document's title
4249 appear in the buffer without the initial #+TITLE: keyword."
4250 :group 'org-appearance
4251 :version "24.1"
4252 :type '(set (const :tag "#+AUTHOR" author)
4253 (const :tag "#+DATE" date)
4254 (const :tag "#+EMAIL" email)
4255 (const :tag "#+TITLE" title)))
4257 (defcustom org-custom-properties nil
4258 "List of properties (as strings) with a special meaning.
4259 The default use of these custom properties is to let the user
4260 hide them with `org-toggle-custom-properties-visibility'."
4261 :group 'org-properties
4262 :group 'org-appearance
4263 :version "24.3"
4264 :type '(repeat (string :tag "Property Name")))
4266 (defcustom org-fontify-done-headline nil
4267 "Non-nil means change the face of a headline if it is marked DONE.
4268 Normally, only the TODO/DONE keyword indicates the state of a headline.
4269 When this is non-nil, the headline after the keyword is set to the
4270 `org-headline-done' as an additional indication."
4271 :group 'org-appearance
4272 :type 'boolean)
4274 (defcustom org-fontify-emphasized-text t
4275 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4276 Changing this variable requires a restart of Emacs to take effect."
4277 :group 'org-appearance
4278 :type 'boolean)
4280 (defcustom org-fontify-whole-heading-line nil
4281 "Non-nil means fontify the whole line for headings.
4282 This is useful when setting a background color for the
4283 org-level-* faces."
4284 :group 'org-appearance
4285 :type 'boolean)
4287 (defcustom org-highlight-latex-and-related nil
4288 "Non-nil means highlight LaTeX related syntax in the buffer.
4289 When non nil, the value should be a list containing any of the
4290 following symbols:
4291 `latex' Highlight LaTeX snippets and environments.
4292 `script' Highlight subscript and superscript.
4293 `entities' Highlight entities."
4294 :group 'org-appearance
4295 :version "24.4"
4296 :package-version '(Org . "8.0")
4297 :type '(choice
4298 (const :tag "No highlighting" nil)
4299 (set :greedy t :tag "Highlight"
4300 (const :tag "LaTeX snippets and environments" latex)
4301 (const :tag "Subscript and superscript" script)
4302 (const :tag "Entities" entities))))
4304 (defcustom org-hide-emphasis-markers nil
4305 "Non-nil mean font-lock should hide the emphasis marker characters."
4306 :group 'org-appearance
4307 :type 'boolean)
4309 (defcustom org-hide-macro-markers nil
4310 "Non-nil mean font-lock should hide the brackets marking macro calls."
4311 :group 'org-appearance
4312 :type 'boolean)
4314 (defcustom org-pretty-entities nil
4315 "Non-nil means show entities as UTF8 characters.
4316 When nil, the \\name form remains in the buffer."
4317 :group 'org-appearance
4318 :version "24.1"
4319 :type 'boolean)
4321 (defcustom org-pretty-entities-include-sub-superscripts t
4322 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4323 :group 'org-appearance
4324 :version "24.1"
4325 :type 'boolean)
4327 (defvar org-emph-re nil
4328 "Regular expression for matching emphasis.
4329 After a match, the match groups contain these elements:
4330 0 The match of the full regular expression, including the characters
4331 before and after the proper match
4332 1 The character before the proper match, or empty at beginning of line
4333 2 The proper match, including the leading and trailing markers
4334 3 The leading marker like * or /, indicating the type of highlighting
4335 4 The text between the emphasis markers, not including the markers
4336 5 The character after the match, empty at the end of a line")
4338 (defvar org-verbatim-re nil
4339 "Regular expression for matching verbatim text.")
4341 (defvar org-emphasis-regexp-components) ; defined just below
4342 (defvar org-emphasis-alist) ; defined just below
4343 (defun org-set-emph-re (var val)
4344 "Set variable and compute the emphasis regular expression."
4345 (set var val)
4346 (when (and (boundp 'org-emphasis-alist)
4347 (boundp 'org-emphasis-regexp-components)
4348 org-emphasis-alist org-emphasis-regexp-components)
4349 (pcase-let*
4350 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4351 (body (if (<= nl 0) body
4352 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4353 (template
4354 (format (concat "\\([%s]\\|^\\)" ;before markers
4355 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4356 "\\([%s]\\|$\\)") ;after markers
4357 pre border border body border post)))
4358 (setq org-emph-re (format template "*/_+"))
4359 (setq org-verbatim-re (format template "=~")))))
4361 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4362 ;; set this option proved cumbersome. See this message/thread:
4363 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4364 (defvar org-emphasis-regexp-components
4365 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4366 "Components used to build the regular expression for emphasis.
4367 This is a list with five entries. Terminology: In an emphasis string
4368 like \" *strong word* \", we call the initial space PREMATCH, the final
4369 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4370 and \"trong wor\" is the body. The different components in this variable
4371 specify what is allowed/forbidden in each part:
4373 pre Chars allowed as prematch. Beginning of line will be allowed too.
4374 post Chars allowed as postmatch. End of line will be allowed too.
4375 border The chars *forbidden* as border characters.
4376 body-regexp A regexp like \".\" to match a body character. Don't use
4377 non-shy groups here, and don't allow newline here.
4378 newline The maximum number of newlines allowed in an emphasis exp.
4380 You need to reload Org or to restart Emacs after setting this.")
4382 (defcustom org-emphasis-alist
4383 '(("*" bold)
4384 ("/" italic)
4385 ("_" underline)
4386 ("=" org-verbatim verbatim)
4387 ("~" org-code verbatim)
4388 ("+" (:strike-through t)))
4389 "Alist of characters and faces to emphasize text.
4390 Text starting and ending with a special character will be emphasized,
4391 for example *bold*, _underlined_ and /italic/. This variable sets the
4392 marker characters and the face to be used by font-lock for highlighting
4393 in Org buffers.
4395 You need to reload Org or to restart Emacs after customizing this."
4396 :group 'org-appearance
4397 :set 'org-set-emph-re
4398 :version "24.4"
4399 :package-version '(Org . "8.0")
4400 :type '(repeat
4401 (list
4402 (string :tag "Marker character")
4403 (choice
4404 (face :tag "Font-lock-face")
4405 (plist :tag "Face property list"))
4406 (option (const verbatim)))))
4408 (defvar org-protecting-blocks '("src" "example" "export")
4409 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4410 This is needed for font-lock setup.")
4412 ;;; Functions and variables from their packages
4413 ;; Declared here to avoid compiler warnings
4414 (defvar mark-active)
4416 ;; Various packages
4417 (declare-function calc-eval "calc" (str &optional separator &rest args))
4418 (declare-function calendar-forward-day "cal-move" (arg))
4419 (declare-function calendar-goto-date "cal-move" (date))
4420 (declare-function calendar-goto-today "cal-move" ())
4421 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4422 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4423 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4424 (declare-function cdlatex-tab "ext:cdlatex" ())
4425 (declare-function dired-get-filename
4426 "dired"
4427 (&optional localp no-error-if-not-filep))
4428 (declare-function iswitchb-read-buffer
4429 "iswitchb"
4430 (prompt &optional
4431 default require-match _predicate start matches-set))
4432 (declare-function org-agenda-change-all-lines
4433 "org-agenda"
4434 (newhead hdmarker &optional fixface just-this))
4435 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4436 "org-agenda"
4437 (&optional end))
4438 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4439 (declare-function org-agenda-format-item
4440 "org-agenda"
4441 (extra txt &optional level category tags dotime
4442 remove-re habitp))
4443 (declare-function org-agenda-maybe-redo "org-agenda" ())
4444 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4445 (declare-function org-agenda-save-markers-for-cut-and-paste
4446 "org-agenda"
4447 (beg end))
4448 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4449 (declare-function org-agenda-skip "org-agenda" ())
4450 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4451 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4452 (declare-function org-indent-mode "org-indent" (&optional arg))
4453 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4454 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4455 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4456 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4457 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4458 (declare-function parse-time-string "parse-time" (string))
4459 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4461 (defvar align-mode-rules-list)
4462 (defvar calc-embedded-close-formula)
4463 (defvar calc-embedded-open-formula)
4464 (defvar calc-embedded-open-mode)
4465 (defvar font-lock-unfontify-region-function)
4466 (defvar iswitchb-temp-buflist)
4467 (defvar org-agenda-tags-todo-honor-ignore-options)
4468 (defvar remember-data-file)
4469 (defvar texmathp-why)
4471 ;;;###autoload
4472 (defun turn-on-orgtbl ()
4473 "Unconditionally turn on `orgtbl-mode'."
4474 (require 'org-table)
4475 (orgtbl-mode 1))
4477 (defun org-at-table-p (&optional table-type)
4478 "Non-nil if the cursor is inside an Org table.
4479 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4480 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4481 (or (not (derived-mode-p 'org-mode))
4482 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4483 (and e (or table-type
4484 (eq 'org (org-element-property :type e))))))))
4486 (defun org-at-table.el-p ()
4487 "Non-nil when point is at a table.el table."
4488 (and (org-match-line "[ \t]*[|+]")
4489 (let ((element (org-element-at-point)))
4490 (and (eq (org-element-type element) 'table)
4491 (eq (org-element-property :type element) 'table.el)))))
4493 (defun org-at-table-hline-p ()
4494 "Non-nil when point is inside a hline in a table.
4495 Assume point is already in a table."
4496 (org-match-line org-table-hline-regexp))
4498 (defun org-table-map-tables (function &optional quietly)
4499 "Apply FUNCTION to the start of all tables in the buffer."
4500 (org-with-wide-buffer
4501 (goto-char (point-min))
4502 (while (re-search-forward org-table-any-line-regexp nil t)
4503 (unless quietly
4504 (message "Mapping tables: %d%%"
4505 (floor (* 100.0 (point)) (buffer-size))))
4506 (beginning-of-line 1)
4507 (when (and (looking-at org-table-line-regexp)
4508 ;; Exclude tables in src/example/verbatim/clocktable blocks
4509 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4510 (save-excursion (funcall function))
4511 (or (looking-at org-table-line-regexp)
4512 (forward-char 1)))
4513 (re-search-forward org-table-any-border-regexp nil 1)))
4514 (unless quietly (message "Mapping tables: done")))
4516 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4517 (declare-function org-clock-update-mode-line "org-clock" ())
4518 (declare-function org-resolve-clocks "org-clock"
4519 (&optional also-non-dangling-p prompt last-valid))
4521 (defun org-at-TBLFM-p (&optional pos)
4522 "Non-nil when point (or POS) is in #+TBLFM line."
4523 (save-excursion
4524 (goto-char (or pos (point)))
4525 (beginning-of-line)
4526 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4527 (eq (org-element-type (org-element-at-point)) 'table))))
4529 (defvar org-clock-start-time)
4530 (defvar org-clock-marker (make-marker)
4531 "Marker recording the last clock-in.")
4532 (defvar org-clock-hd-marker (make-marker)
4533 "Marker recording the last clock-in, but the headline position.")
4534 (defvar org-clock-heading ""
4535 "The heading of the current clock entry.")
4536 (defun org-clock-is-active ()
4537 "Return the buffer where the clock is currently running.
4538 Return nil if no clock is running."
4539 (marker-buffer org-clock-marker))
4541 (defun org-check-running-clock ()
4542 "Check if the current buffer contains the running clock.
4543 If yes, offer to stop it and to save the buffer with the changes."
4544 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4545 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4546 (buffer-name))))
4547 (org-clock-out)
4548 (when (y-or-n-p "Save changed buffer?")
4549 (save-buffer))))
4551 (defun org-clocktable-try-shift (dir n)
4552 "Check if this line starts a clock table, if yes, shift the time block."
4553 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4554 (org-clocktable-shift dir n)))
4556 ;;;###autoload
4557 (defun org-clock-persistence-insinuate ()
4558 "Set up hooks for clock persistence."
4559 (require 'org-clock)
4560 (add-hook 'org-mode-hook 'org-clock-load)
4561 (add-hook 'kill-emacs-hook 'org-clock-save))
4563 (defgroup org-archive nil
4564 "Options concerning archiving in Org mode."
4565 :tag "Org Archive"
4566 :group 'org-structure)
4568 (defcustom org-archive-location "%s_archive::"
4569 "The location where subtrees should be archived.
4571 The value of this variable is a string, consisting of two parts,
4572 separated by a double-colon. The first part is a filename and
4573 the second part is a headline.
4575 When the filename is omitted, archiving happens in the same file.
4576 %s in the filename will be replaced by the current file
4577 name (without the directory part). Archiving to a different file
4578 is useful to keep archived entries from contributing to the
4579 Org Agenda.
4581 The archived entries will be filed as subtrees of the specified
4582 headline. When the headline is omitted, the subtrees are simply
4583 filed away at the end of the file, as top-level entries. Also in
4584 the heading you can use %s to represent the file name, this can be
4585 useful when using the same archive for a number of different files.
4587 Here are a few examples:
4588 \"%s_archive::\"
4589 If the current file is Projects.org, archive in file
4590 Projects.org_archive, as top-level trees. This is the default.
4592 \"::* Archived Tasks\"
4593 Archive in the current file, under the top-level headline
4594 \"* Archived Tasks\".
4596 \"~/org/archive.org::\"
4597 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4599 \"~/org/archive.org::* From %s\"
4600 Archive in file ~/org/archive.org (absolute path), under headlines
4601 \"From FILENAME\" where file name is the current file name.
4603 \"~/org/datetree.org::datetree/* Finished Tasks\"
4604 The \"datetree/\" string is special, signifying to archive
4605 items to the datetree. Items are placed in either the CLOSED
4606 date of the item, or the current date if there is no CLOSED date.
4607 The heading will be a subentry to the current date. There doesn't
4608 need to be a heading, but there always needs to be a slash after
4609 datetree. For example, to store archived items directly in the
4610 datetree, use \"~/org/datetree.org::datetree/\".
4612 \"basement::** Finished Tasks\"
4613 Archive in file ./basement (relative path), as level 3 trees
4614 below the level 2 heading \"** Finished Tasks\".
4616 You may set this option on a per-file basis by adding to the buffer a
4617 line like
4619 #+ARCHIVE: basement::** Finished Tasks
4621 You may also define it locally for a subtree by setting an ARCHIVE property
4622 in the entry. If such a property is found in an entry, or anywhere up
4623 the hierarchy, it will be used."
4624 :group 'org-archive
4625 :type 'string)
4627 (defcustom org-agenda-skip-archived-trees t
4628 "Non-nil means the agenda will skip any items located in archived trees.
4629 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4630 variable is no longer recommended, you should leave it at the value t.
4631 Instead, use the key `v' to cycle the archives-mode in the agenda."
4632 :group 'org-archive
4633 :group 'org-agenda-skip
4634 :type 'boolean)
4636 (defcustom org-columns-skip-archived-trees t
4637 "Non-nil means ignore archived trees when creating column view."
4638 :group 'org-archive
4639 :group 'org-properties
4640 :type 'boolean)
4642 (defcustom org-cycle-open-archived-trees nil
4643 "Non-nil means `org-cycle' will open archived trees.
4644 An archived tree is a tree marked with the tag ARCHIVE.
4645 When nil, archived trees will stay folded. You can still open them with
4646 normal outline commands like `show-all', but not with the cycling commands."
4647 :group 'org-archive
4648 :group 'org-cycle
4649 :type 'boolean)
4651 (defcustom org-sparse-tree-open-archived-trees nil
4652 "Non-nil means sparse tree construction shows matches in archived trees.
4653 When nil, matches in these trees are highlighted, but the trees are kept in
4654 collapsed state."
4655 :group 'org-archive
4656 :group 'org-sparse-trees
4657 :type 'boolean)
4659 (defcustom org-sparse-tree-default-date-type nil
4660 "The default date type when building a sparse tree.
4661 When this is nil, a date is a scheduled or a deadline timestamp.
4662 Otherwise, these types are allowed:
4664 all: all timestamps
4665 active: only active timestamps (<...>)
4666 inactive: only inactive timestamps ([...])
4667 scheduled: only scheduled timestamps
4668 deadline: only deadline timestamps"
4669 :type '(choice (const :tag "Scheduled or deadline" nil)
4670 (const :tag "All timestamps" all)
4671 (const :tag "Only active timestamps" active)
4672 (const :tag "Only inactive timestamps" inactive)
4673 (const :tag "Only scheduled timestamps" scheduled)
4674 (const :tag "Only deadline timestamps" deadline)
4675 (const :tag "Only closed timestamps" closed))
4676 :version "26.1"
4677 :package-version '(Org . "8.3")
4678 :group 'org-sparse-trees)
4680 (defun org-cycle-hide-archived-subtrees (state)
4681 "Re-hide all archived subtrees after a visibility state change.
4682 STATE should be one of the symbols listed in the docstring of
4683 `org-cycle-hook'."
4684 (when (and (not org-cycle-open-archived-trees)
4685 (not (memq state '(overview folded))))
4686 (save-excursion
4687 (let* ((globalp (memq state '(contents all)))
4688 (beg (if globalp (point-min) (point)))
4689 (end (if globalp (point-max) (org-end-of-subtree t))))
4690 (org-hide-archived-subtrees beg end)
4691 (goto-char beg)
4692 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4693 (message "%s" (substitute-command-keys
4694 "Subtree is archived and stays closed. Use \
4695 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4697 (defun org-force-cycle-archived ()
4698 "Cycle subtree even if it is archived."
4699 (interactive)
4700 (setq this-command 'org-cycle)
4701 (let ((org-cycle-open-archived-trees t))
4702 (call-interactively 'org-cycle)))
4704 (defun org-hide-archived-subtrees (beg end)
4705 "Re-hide all archived subtrees after a visibility state change."
4706 (org-with-wide-buffer
4707 (let ((case-fold-search nil)
4708 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4709 (goto-char beg)
4710 ;; Include headline point is currently on.
4711 (beginning-of-line)
4712 (while (and (< (point) end) (re-search-forward re end t))
4713 (when (member org-archive-tag (org-get-tags))
4714 (org-flag-subtree t)
4715 (org-end-of-subtree t))))))
4717 (declare-function outline-end-of-heading "outline" ())
4718 (declare-function outline-flag-region "outline" (from to flag))
4719 (defun org-flag-subtree (flag)
4720 (save-excursion
4721 (org-back-to-heading t)
4722 (outline-end-of-heading)
4723 (outline-flag-region (point)
4724 (progn (org-end-of-subtree t) (point))
4725 flag)))
4727 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4729 ;; Declare Column View Code
4731 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4732 (declare-function org-columns-compute "org-colview" (property))
4734 ;; Declare ID code
4736 (declare-function org-id-store-link "org-id")
4737 (declare-function org-id-locations-load "org-id")
4738 (declare-function org-id-locations-save "org-id")
4739 (defvar org-id-track-globally)
4741 ;;; Variables for pre-computed regular expressions, all buffer local
4743 (defvar-local org-todo-regexp nil
4744 "Matches any of the TODO state keywords.
4745 Since TODO keywords are case-sensitive, `case-fold-search' is
4746 expected to be bound to nil when matching against this regexp.")
4748 (defvar-local org-not-done-regexp nil
4749 "Matches any of the TODO state keywords except the last one.
4750 Since TODO keywords are case-sensitive, `case-fold-search' is
4751 expected to be bound to nil when matching against this regexp.")
4753 (defvar-local org-not-done-heading-regexp nil
4754 "Matches a TODO headline that is not done.
4755 Since TODO keywords are case-sensitive, `case-fold-search' is
4756 expected to be bound to nil when matching against this regexp.")
4758 (defvar-local org-todo-line-regexp nil
4759 "Matches a headline and puts TODO state into group 2 if present.
4760 Since TODO keywords are case-sensitive, `case-fold-search' is
4761 expected to be bound to nil when matching against this regexp.")
4763 (defvar-local org-complex-heading-regexp nil
4764 "Matches a headline and puts everything into groups:
4766 group 1: Stars
4767 group 2: The TODO keyword, maybe
4768 group 3: Priority cookie
4769 group 4: True headline
4770 group 5: Tags
4772 Since TODO keywords are case-sensitive, `case-fold-search' is
4773 expected to be bound to nil when matching against this regexp.")
4775 (defvar-local org-complex-heading-regexp-format nil
4776 "Printf format to make regexp to match an exact headline.
4777 This regexp will match the headline of any node which has the
4778 exact headline text that is put into the format, but may have any
4779 TODO state, priority and tags.")
4781 (defvar-local org-todo-line-tags-regexp nil
4782 "Matches a headline and puts TODO state into group 2 if present.
4783 Also put tags into group 4 if tags are present.")
4785 (defconst org-plain-time-of-day-regexp
4786 (concat
4787 "\\(\\<[012]?[0-9]"
4788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4789 "\\(--?"
4790 "\\(\\<[012]?[0-9]"
4791 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4792 "\\)?")
4793 "Regular expression to match a plain time or time range.
4794 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4795 groups carry important information:
4796 0 the full match
4797 1 the first time, range or not
4798 8 the second time, if it is a range.")
4800 (defconst org-plain-time-extension-regexp
4801 (concat
4802 "\\(\\<[012]?[0-9]"
4803 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4804 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4805 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4806 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4807 groups carry important information:
4808 0 the full match
4809 7 hours of duration
4810 9 minutes of duration")
4812 (defconst org-stamp-time-of-day-regexp
4813 (concat
4814 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4815 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4816 "\\(--?"
4817 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4818 "Regular expression to match a timestamp time or time range.
4819 After a match, the following groups carry important information:
4820 0 the full match
4821 1 date plus weekday, for back referencing to make sure both times are on the same day
4822 2 the first time, range or not
4823 4 the second time, if it is a range.")
4825 (defconst org-startup-options
4826 '(("fold" org-startup-folded t)
4827 ("overview" org-startup-folded t)
4828 ("nofold" org-startup-folded nil)
4829 ("showall" org-startup-folded nil)
4830 ("showeverything" org-startup-folded showeverything)
4831 ("content" org-startup-folded content)
4832 ("indent" org-startup-indented t)
4833 ("noindent" org-startup-indented nil)
4834 ("hidestars" org-hide-leading-stars t)
4835 ("showstars" org-hide-leading-stars nil)
4836 ("odd" org-odd-levels-only t)
4837 ("oddeven" org-odd-levels-only nil)
4838 ("align" org-startup-align-all-tables t)
4839 ("noalign" org-startup-align-all-tables nil)
4840 ("shrink" org-startup-shrink-all-tables t)
4841 ("inlineimages" org-startup-with-inline-images t)
4842 ("noinlineimages" org-startup-with-inline-images nil)
4843 ("latexpreview" org-startup-with-latex-preview t)
4844 ("nolatexpreview" org-startup-with-latex-preview nil)
4845 ("customtime" org-display-custom-times t)
4846 ("logdone" org-log-done time)
4847 ("lognotedone" org-log-done note)
4848 ("nologdone" org-log-done nil)
4849 ("lognoteclock-out" org-log-note-clock-out t)
4850 ("nolognoteclock-out" org-log-note-clock-out nil)
4851 ("logrepeat" org-log-repeat state)
4852 ("lognoterepeat" org-log-repeat note)
4853 ("logdrawer" org-log-into-drawer t)
4854 ("nologdrawer" org-log-into-drawer nil)
4855 ("logstatesreversed" org-log-states-order-reversed t)
4856 ("nologstatesreversed" org-log-states-order-reversed nil)
4857 ("nologrepeat" org-log-repeat nil)
4858 ("logreschedule" org-log-reschedule time)
4859 ("lognotereschedule" org-log-reschedule note)
4860 ("nologreschedule" org-log-reschedule nil)
4861 ("logredeadline" org-log-redeadline time)
4862 ("lognoteredeadline" org-log-redeadline note)
4863 ("nologredeadline" org-log-redeadline nil)
4864 ("logrefile" org-log-refile time)
4865 ("lognoterefile" org-log-refile note)
4866 ("nologrefile" org-log-refile nil)
4867 ("fninline" org-footnote-define-inline t)
4868 ("nofninline" org-footnote-define-inline nil)
4869 ("fnlocal" org-footnote-section nil)
4870 ("fnauto" org-footnote-auto-label t)
4871 ("fnprompt" org-footnote-auto-label nil)
4872 ("fnconfirm" org-footnote-auto-label confirm)
4873 ("fnplain" org-footnote-auto-label plain)
4874 ("fnadjust" org-footnote-auto-adjust t)
4875 ("nofnadjust" org-footnote-auto-adjust nil)
4876 ("constcgs" constants-unit-system cgs)
4877 ("constSI" constants-unit-system SI)
4878 ("noptag" org-tag-persistent-alist nil)
4879 ("hideblocks" org-hide-block-startup t)
4880 ("nohideblocks" org-hide-block-startup nil)
4881 ("beamer" org-startup-with-beamer-mode t)
4882 ("entitiespretty" org-pretty-entities t)
4883 ("entitiesplain" org-pretty-entities nil))
4884 "Variable associated with STARTUP options for org-mode.
4885 Each element is a list of three items: the startup options (as written
4886 in the #+STARTUP line), the corresponding variable, and the value to set
4887 this variable to if the option is found. An optional forth element PUSH
4888 means to push this value onto the list in the variable.")
4890 (defcustom org-group-tags t
4891 "When non-nil (the default), use group tags.
4892 This can be turned on/off through `org-toggle-tags-groups'."
4893 :group 'org-tags
4894 :group 'org-startup
4895 :type 'boolean)
4897 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4899 (defun org-toggle-tags-groups ()
4900 "Toggle support for group tags.
4901 Support for group tags is controlled by the option
4902 `org-group-tags', which is non-nil by default."
4903 (interactive)
4904 (setq org-group-tags (not org-group-tags))
4905 (cond ((and (derived-mode-p 'org-agenda-mode)
4906 org-group-tags)
4907 (org-agenda-redo))
4908 ((derived-mode-p 'org-mode)
4909 (let ((org-inhibit-startup t)) (org-mode))))
4910 (message "Groups tags support has been turned %s"
4911 (if org-group-tags "on" "off")))
4913 (defun org-set-regexps-and-options (&optional tags-only)
4914 "Precompute regular expressions used in the current buffer.
4915 When optional argument TAGS-ONLY is non-nil, only compute tags
4916 related expressions."
4917 (when (derived-mode-p 'org-mode)
4918 (let ((alist (org--setup-collect-keywords
4919 (org-make-options-regexp
4920 (append '("FILETAGS" "TAGS" "SETUPFILE")
4921 (and (not tags-only)
4922 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4923 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4924 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4925 ;; Startup options. Get this early since it does change
4926 ;; behavior for other options (e.g., tags).
4927 (let ((startup (cdr (assq 'startup alist))))
4928 (dolist (option startup)
4929 (let ((entry (assoc-string option org-startup-options t)))
4930 (when entry
4931 (let ((var (nth 1 entry))
4932 (val (nth 2 entry)))
4933 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4934 (unless (listp (symbol-value var))
4935 (set (make-local-variable var) nil))
4936 (add-to-list var val)))))))
4937 (setq-local org-file-tags
4938 (mapcar #'org-add-prop-inherited
4939 (cdr (assq 'filetags alist))))
4940 (setq org-current-tag-alist
4941 (append org-tag-persistent-alist
4942 (let ((tags (cdr (assq 'tags alist))))
4943 (if tags (org-tag-string-to-alist tags)
4944 org-tag-alist))))
4945 (setq org-tag-groups-alist
4946 (org-tag-alist-to-groups org-current-tag-alist))
4947 (unless tags-only
4948 ;; File properties.
4949 (setq-local org-file-properties (cdr (assq 'property alist)))
4950 ;; Archive location.
4951 (let ((archive (cdr (assq 'archive alist))))
4952 (when archive (setq-local org-archive-location archive)))
4953 ;; Category.
4954 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4955 (when cat
4956 (setq-local org-category (intern cat))
4957 (setq-local org-file-properties
4958 (org--update-property-plist
4959 "CATEGORY" cat org-file-properties))))
4960 ;; Columns.
4961 (let ((column (cdr (assq 'columns alist))))
4962 (when column (setq-local org-columns-default-format column)))
4963 ;; Constants.
4964 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4965 ;; Link abbreviations.
4966 (let ((links (cdr (assq 'link alist))))
4967 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4968 ;; Priorities.
4969 (let ((priorities (cdr (assq 'priorities alist))))
4970 (when priorities
4971 (setq-local org-highest-priority (nth 0 priorities))
4972 (setq-local org-lowest-priority (nth 1 priorities))
4973 (setq-local org-default-priority (nth 2 priorities))))
4974 ;; Scripts.
4975 (let ((scripts (assq 'scripts alist)))
4976 (when scripts
4977 (setq-local org-use-sub-superscripts (cdr scripts))))
4978 ;; TODO keywords.
4979 (setq-local org-todo-kwd-alist nil)
4980 (setq-local org-todo-key-alist nil)
4981 (setq-local org-todo-key-trigger nil)
4982 (setq-local org-todo-keywords-1 nil)
4983 (setq-local org-done-keywords nil)
4984 (setq-local org-todo-heads nil)
4985 (setq-local org-todo-sets nil)
4986 (setq-local org-todo-log-states nil)
4987 (let ((todo-sequences
4988 (or (nreverse (cdr (assq 'todo alist)))
4989 (let ((d (default-value 'org-todo-keywords)))
4990 (if (not (stringp (car d))) d
4991 ;; XXX: Backward compatibility code.
4992 (list (cons org-todo-interpretation d)))))))
4993 (dolist (sequence todo-sequences)
4994 (let* ((sequence (or (run-hook-with-args-until-success
4995 'org-todo-setup-filter-hook sequence)
4996 sequence))
4997 (sequence-type (car sequence))
4998 (keywords (cdr sequence))
4999 (sep (member "|" keywords))
5000 names alist)
5001 (dolist (k (remove "|" keywords))
5002 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5004 (error "Invalid TODO keyword %s" k))
5005 (let ((name (match-string 1 k))
5006 (key (match-string 2 k))
5007 (log (org-extract-log-state-settings k)))
5008 (push name names)
5009 (push (cons name (and key (string-to-char key))) alist)
5010 (when log (push log org-todo-log-states))))
5011 (let* ((names (nreverse names))
5012 (done (if sep (org-remove-keyword-keys (cdr sep))
5013 (last names)))
5014 (head (car names))
5015 (tail (list sequence-type head (car done) (org-last done))))
5016 (add-to-list 'org-todo-heads head 'append)
5017 (push names org-todo-sets)
5018 (setq org-done-keywords (append org-done-keywords done nil))
5019 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5020 (setq org-todo-key-alist
5021 (append org-todo-key-alist
5022 (and alist
5023 (append '((:startgroup))
5024 (nreverse alist)
5025 '((:endgroup))))))
5026 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5027 (setq org-todo-sets (nreverse org-todo-sets)
5028 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5029 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5030 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5031 ;; Compute the regular expressions and other local variables.
5032 ;; Using `org-outline-regexp-bol' would complicate them much,
5033 ;; because of the fixed white space at the end of that string.
5034 (unless org-done-keywords
5035 (setq org-done-keywords
5036 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5037 (setq org-not-done-keywords
5038 (org-delete-all org-done-keywords
5039 (copy-sequence org-todo-keywords-1))
5040 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5041 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5042 org-not-done-heading-regexp
5043 (format org-heading-keyword-regexp-format org-not-done-regexp)
5044 org-todo-line-regexp
5045 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5046 org-complex-heading-regexp
5047 (concat "^\\(\\*+\\)"
5048 "\\(?: +" org-todo-regexp "\\)?"
5049 "\\(?: +\\(\\[#.\\]\\)\\)?"
5050 "\\(?: +\\(.*?\\)\\)??"
5051 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5052 "[ \t]*$")
5053 org-complex-heading-regexp-format
5054 (concat "^\\(\\*+\\)"
5055 "\\(?: +" org-todo-regexp "\\)?"
5056 "\\(?: +\\(\\[#.\\]\\)\\)?"
5057 "\\(?: +"
5058 ;; Stats cookies can be stuck to body.
5059 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5060 "\\(%s\\)"
5061 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5062 "\\)"
5063 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5064 "[ \t]*$")
5065 org-todo-line-tags-regexp
5066 (concat "^\\(\\*+\\)"
5067 "\\(?: +" org-todo-regexp "\\)?"
5068 "\\(?: +\\(.*?\\)\\)??"
5069 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5070 "[ \t]*$"))
5071 (org-compute-latex-and-related-regexp)))))
5073 (defun org--setup-collect-keywords (regexp &optional files alist)
5074 "Return setup keywords values as an alist.
5076 REGEXP matches a subset of setup keywords. FILES is a list of
5077 file names already visited. It is used to avoid circular setup
5078 files. ALIST, when non-nil, is the alist computed so far.
5080 Return value contains the following keys: `archive', `category',
5081 `columns', `constants', `filetags', `link', `priorities',
5082 `property', `scripts', `startup', `tags' and `todo'."
5083 (org-with-wide-buffer
5084 (goto-char (point-min))
5085 (let ((case-fold-search t))
5086 (while (re-search-forward regexp nil t)
5087 (let ((element (org-element-at-point)))
5088 (when (eq (org-element-type element) 'keyword)
5089 (let ((key (org-element-property :key element))
5090 (value (org-element-property :value element)))
5091 (cond
5092 ((equal key "ARCHIVE")
5093 (when (org-string-nw-p value)
5094 (push (cons 'archive value) alist)))
5095 ((equal key "CATEGORY") (push (cons 'category value) alist))
5096 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5097 ((equal key "CONSTANTS")
5098 (let* ((constants (assq 'constants alist))
5099 (store (cdr constants)))
5100 (dolist (pair (split-string value))
5101 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5102 pair)
5103 (let* ((name (match-string 1 pair))
5104 (value (match-string 2 pair))
5105 (old (assoc name store)))
5106 (if old (setcdr old value)
5107 (push (cons name value) store)))))
5108 (if constants (setcdr constants store)
5109 (push (cons 'constants store) alist))))
5110 ((equal key "FILETAGS")
5111 (when (org-string-nw-p value)
5112 (let ((old (assq 'filetags alist))
5113 (new (apply #'nconc
5114 (mapcar (lambda (x) (org-split-string x ":"))
5115 (split-string value)))))
5116 (if old (setcdr old (append new (cdr old)))
5117 (push (cons 'filetags new) alist)))))
5118 ((equal key "LINK")
5119 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5120 (let ((links (assq 'link alist))
5121 (pair (cons (match-string-no-properties 1 value)
5122 (match-string-no-properties 2 value))))
5123 (if links (push pair (cdr links))
5124 (push (list 'link pair) alist)))))
5125 ((equal key "OPTIONS")
5126 (when (and (org-string-nw-p value)
5127 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5128 (push (cons 'scripts (read (match-string 1 value))) alist)))
5129 ((equal key "PRIORITIES")
5130 (push (cons 'priorities
5131 (let ((prio (split-string value)))
5132 (if (< (length prio) 3) '(?A ?C ?B)
5133 (mapcar #'string-to-char prio))))
5134 alist))
5135 ((equal key "PROPERTY")
5136 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5137 (let* ((property (assq 'property alist))
5138 (value (org--update-property-plist
5139 (match-string-no-properties 1 value)
5140 (match-string-no-properties 2 value)
5141 (cdr property))))
5142 (if property (setcdr property value)
5143 (push (cons 'property value) alist)))))
5144 ((equal key "STARTUP")
5145 (let ((startup (assq 'startup alist)))
5146 (if startup
5147 (setcdr startup
5148 (append (cdr startup) (split-string value)))
5149 (push (cons 'startup (split-string value)) alist))))
5150 ((equal key "TAGS")
5151 (let ((tag-cell (assq 'tags alist)))
5152 (if tag-cell
5153 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5154 (push (cons 'tags value) alist))))
5155 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5156 (let ((todo (assq 'todo alist))
5157 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5158 (split-string value))))
5159 (if todo (push value (cdr todo))
5160 (push (list 'todo value) alist))))
5161 ((equal key "SETUPFILE")
5162 (unless buffer-read-only ; Do not check in Gnus messages.
5163 (let ((f (and (org-string-nw-p value)
5164 (expand-file-name
5165 (org-unbracket-string "\"" "\"" value)))))
5166 (when (and f (file-readable-p f) (not (member f files)))
5167 (with-temp-buffer
5168 (setq default-directory (file-name-directory f))
5169 (insert-file-contents f)
5170 (setq alist
5171 ;; Fake Org mode to benefit from cache
5172 ;; without recurring needlessly.
5173 (let ((major-mode 'org-mode))
5174 (org--setup-collect-keywords
5175 regexp (cons f files) alist)))))))))))))))
5176 alist)
5178 (defun org-tag-string-to-alist (s)
5179 "Return tag alist associated to string S.
5180 S is a value for TAGS keyword or produced with
5181 `org-tag-alist-to-string'. Return value is an alist suitable for
5182 `org-tag-alist' or `org-tag-persistent-alist'."
5183 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5184 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5185 "\\|{.+?}\\)" ; regular expression
5186 "\\(?:(\\(.\\))\\)?\\'"))
5187 alist group-flag)
5188 (dolist (tokens lines (cdr (nreverse alist)))
5189 (push '(:newline) alist)
5190 (while tokens
5191 (let ((token (pop tokens)))
5192 (pcase token
5193 ("{"
5194 (push '(:startgroup) alist)
5195 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5196 ("}"
5197 (push '(:endgroup) alist)
5198 (setq group-flag nil))
5199 ("["
5200 (push '(:startgrouptag) alist)
5201 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5202 ("]"
5203 (push '(:endgrouptag) alist)
5204 (setq group-flag nil))
5205 (":"
5206 (push '(:grouptags) alist))
5207 ((guard (string-match tag-re token))
5208 (let ((tag (match-string 1 token))
5209 (key (and (match-beginning 2)
5210 (string-to-char (match-string 2 token)))))
5211 ;; Push all tags in groups, no matter if they already
5212 ;; appear somewhere else in the list.
5213 (when (or group-flag (not (assoc tag alist)))
5214 (push (cons tag key) alist))))))))))
5216 (defun org-tag-alist-to-string (alist &optional skip-key)
5217 "Return tag string associated to ALIST.
5219 ALIST is an alist, as defined in `org-tag-alist' or
5220 `org-tag-persistent-alist', or produced with
5221 `org-tag-string-to-alist'.
5223 Return value is a string suitable as a value for \"TAGS\"
5224 keyword.
5226 When optional argument SKIP-KEY is non-nil, skip selection keys
5227 next to tags."
5228 (mapconcat (lambda (token)
5229 (pcase token
5230 (`(:startgroup) "{")
5231 (`(:endgroup) "}")
5232 (`(:startgrouptag) "[")
5233 (`(:endgrouptag) "]")
5234 (`(:grouptags) ":")
5235 (`(:newline) "\\n")
5236 ((and
5237 (guard (not skip-key))
5238 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5239 (format "%s(%c)" tag key))
5240 (`(,(and tag (pred stringp)) . ,_) tag)
5241 (_ (user-error "Invalid tag token: %S" token))))
5242 alist
5243 " "))
5245 (defun org-tag-alist-to-groups (alist)
5246 "Return group alist from tag ALIST.
5247 ALIST is an alist, as defined in `org-tag-alist' or
5248 `org-tag-persistent-alist', or produced with
5249 `org-tag-string-to-alist'. Return value is an alist following
5250 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5251 a string, summarizing TAGS, as a list of strings."
5252 (let (groups group-status current-group)
5253 (dolist (token alist (nreverse groups))
5254 (pcase token
5255 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5256 (`(,(or :endgroup :endgrouptag))
5257 (when (eq group-status 'append)
5258 (push (nreverse current-group) groups))
5259 (setq group-status nil))
5260 (`(:grouptags) (setq group-status 'append))
5261 ((and `(,tag . ,_) (guard group-status))
5262 (if (eq group-status 'append) (push tag current-group)
5263 (setq current-group (list tag))))
5264 (_ nil)))))
5266 (defvar org--file-cache (make-hash-table :test #'equal)
5267 "Hash table to store contents of files referenced via a URL.
5268 This is the cache of file URLs read using `org-file-contents'.")
5270 (defun org-reset-file-cache ()
5271 "Reset the cache of files downloaded by `org-file-contents'."
5272 (clrhash org--file-cache))
5274 (defun org-file-url-p (file)
5275 "Non-nil if FILE is a URL."
5276 (require 'ffap)
5277 (string-match-p ffap-url-regexp file))
5279 (defun org-file-contents (file &optional noerror nocache)
5280 "Return the contents of FILE, as a string.
5282 FILE can be a file name or URL.
5284 If FILE is a URL, download the contents. If the URL contents are
5285 already cached in the `org--file-cache' hash table, the download step
5286 is skipped.
5288 If NOERROR is non-nil, ignore the error when unable to read the FILE
5289 from file or URL.
5291 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5292 is available. This option applies only if FILE is a URL."
5293 (let* ((is-url (org-file-url-p file))
5294 (cache (and is-url
5295 (not nocache)
5296 (gethash file org--file-cache))))
5297 (cond
5298 (cache)
5299 (is-url
5300 (with-current-buffer (url-retrieve-synchronously file)
5301 (goto-char (point-min))
5302 ;; Move point to after the url-retrieve header.
5303 (search-forward "\n\n" nil :move)
5304 ;; Search for the success code only in the url-retrieve header.
5305 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5306 ;; Update the cache `org--file-cache' and return contents.
5307 (puthash file
5308 (buffer-substring-no-properties (point) (point-max))
5309 org--file-cache)
5310 (funcall (if noerror #'message #'user-error)
5311 "Unable to fetch file from %S"
5312 file))))
5314 (with-temp-buffer
5315 (condition-case err
5316 (progn
5317 (insert-file-contents file)
5318 (buffer-string))
5319 (file-error
5320 (funcall (if noerror #'message #'user-error)
5321 (error-message-string err)))))))))
5323 (defun org-extract-log-state-settings (x)
5324 "Extract the log state setting from a TODO keyword string.
5325 This will extract info from a string like \"WAIT(w@/!)\"."
5326 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5327 (let ((kw (match-string 1 x))
5328 (log1 (and (match-end 3) (match-string 3 x)))
5329 (log2 (and (match-end 4) (match-string 4 x))))
5330 (and (or log1 log2)
5331 (list kw
5332 (and log1 (if (equal log1 "!") 'time 'note))
5333 (and log2 (if (equal log2 "!") 'time 'note)))))))
5335 (defun org-remove-keyword-keys (list)
5336 "Remove a pair of parenthesis at the end of each string in LIST."
5337 (mapcar (lambda (x)
5338 (if (string-match "(.*)$" x)
5339 (substring x 0 (match-beginning 0))
5341 list))
5343 (defun org-assign-fast-keys (alist)
5344 "Assign fast keys to a keyword-key alist.
5345 Respect keys that are already there."
5346 (let (new e (alt ?0))
5347 (while (setq e (pop alist))
5348 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5349 (cdr e)) ;; Key already assigned.
5350 (push e new)
5351 (let ((clist (string-to-list (downcase (car e))))
5352 (used (append new alist)))
5353 (when (= (car clist) ?@)
5354 (pop clist))
5355 (while (and clist (rassoc (car clist) used))
5356 (pop clist))
5357 (unless clist
5358 (while (rassoc alt used)
5359 (cl-incf alt)))
5360 (push (cons (car e) (or (car clist) alt)) new))))
5361 (nreverse new)))
5363 ;;; Some variables used in various places
5365 (defvar org-window-configuration nil
5366 "Used in various places to store a window configuration.")
5367 (defvar org-selected-window nil
5368 "Used in various places to store a window configuration.")
5369 (defvar org-finish-function nil
5370 "Function to be called when `C-c C-c' is used.
5371 This is for getting out of special buffers like capture.")
5372 (defvar org-last-state)
5374 ;; Defined somewhere in this file, but used before definition.
5375 (defvar org-entities) ;; defined in org-entities.el
5376 (defvar org-struct-menu)
5377 (defvar org-org-menu)
5378 (defvar org-tbl-menu)
5380 ;;;; Define the Org mode
5382 ;; We use a before-change function to check if a table might need
5383 ;; an update.
5384 (defvar org-table-may-need-update t
5385 "Indicates that a table might need an update.
5386 This variable is set by `org-before-change-function'.
5387 `org-table-align' sets it back to nil.")
5388 (defun org-before-change-function (_beg _end)
5389 "Every change indicates that a table might need an update."
5390 (setq org-table-may-need-update t))
5391 (defvar org-mode-map)
5392 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5393 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5394 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5395 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5396 (defvar org-table-buffer-is-an nil)
5398 (defvar bidi-paragraph-direction)
5399 (defvar buffer-face-mode-face)
5401 (require 'outline)
5403 ;; Other stuff we need.
5404 (require 'time-date)
5405 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5406 (require 'easymenu)
5407 (autoload 'easy-menu-add "easymenu")
5408 (require 'overlay)
5410 ;; (require 'org-macs) moved higher up in the file before it is first used
5411 (require 'org-entities)
5412 ;; (require 'org-compat) moved higher up in the file before it is first used
5413 (require 'org-faces)
5414 (require 'org-list)
5415 (require 'org-pcomplete)
5416 (require 'org-src)
5417 (require 'org-footnote)
5418 (require 'org-macro)
5420 ;; babel
5421 (require 'ob)
5423 ;;;###autoload
5424 (define-derived-mode org-mode outline-mode "Org"
5425 "Outline-based notes management and organizer, alias
5426 \"Carsten's outline-mode for keeping track of everything.\"
5428 Org mode develops organizational tasks around a NOTES file which
5429 contains information about projects as plain text. Org mode is
5430 implemented on top of Outline mode, which is ideal to keep the content
5431 of large files well structured. It supports ToDo items, deadlines and
5432 time stamps, which magically appear in the diary listing of the Emacs
5433 calendar. Tables are easily created with a built-in table editor.
5434 Plain text URL-like links connect to websites, emails (VM), Usenet
5435 messages (Gnus), BBDB entries, and any files related to the project.
5436 For printing and sharing of notes, an Org file (or a part of it)
5437 can be exported as a structured ASCII or HTML file.
5439 The following commands are available:
5441 \\{org-mode-map}"
5443 ;; Get rid of Outline menus, they are not needed
5444 ;; Need to do this here because define-derived-mode sets up
5445 ;; the keymap so late. Still, it is a waste to call this each time
5446 ;; we switch another buffer into Org mode.
5447 (define-key org-mode-map [menu-bar headings] 'undefined)
5448 (define-key org-mode-map [menu-bar hide] 'undefined)
5449 (define-key org-mode-map [menu-bar show] 'undefined)
5451 (org-load-modules-maybe)
5452 (org-install-agenda-files-menu)
5453 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5454 (add-to-invisibility-spec '(org-hide-block . t))
5455 (setq-local outline-regexp org-outline-regexp)
5456 (setq-local outline-level 'org-outline-level)
5457 (setq bidi-paragraph-direction 'left-to-right)
5458 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5459 (unless org-display-table
5460 (setq org-display-table (make-display-table)))
5461 (set-display-table-slot
5462 org-display-table 4
5463 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5464 org-ellipsis)))
5465 (setq buffer-display-table org-display-table))
5466 (org-set-regexps-and-options)
5467 (org-set-font-lock-defaults)
5468 (when (and org-tag-faces (not org-tags-special-faces-re))
5469 ;; tag faces set outside customize.... force initialization.
5470 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5471 ;; Calc embedded
5472 (setq-local calc-embedded-open-mode "# ")
5473 ;; Modify a few syntax entries
5474 (modify-syntax-entry ?@ "w")
5475 (modify-syntax-entry ?\" "\"")
5476 (modify-syntax-entry ?\\ "_")
5477 (modify-syntax-entry ?~ "_")
5478 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5479 ;; Activate before-change-function
5480 (setq-local org-table-may-need-update t)
5481 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5482 ;; Check for running clock before killing a buffer
5483 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5484 ;; Initialize macros templates.
5485 (org-macro-initialize-templates)
5486 ;; Initialize radio targets.
5487 (org-update-radio-target-regexp)
5488 ;; Indentation.
5489 (setq-local indent-line-function 'org-indent-line)
5490 (setq-local indent-region-function 'org-indent-region)
5491 ;; Filling and auto-filling.
5492 (org-setup-filling)
5493 ;; Comments.
5494 (org-setup-comments-handling)
5495 ;; Initialize cache.
5496 (org-element-cache-reset)
5497 ;; Beginning/end of defun
5498 (setq-local beginning-of-defun-function 'org-backward-element)
5499 (setq-local end-of-defun-function
5500 (lambda ()
5501 (if (not (org-at-heading-p))
5502 (org-forward-element)
5503 (org-forward-element)
5504 (forward-char -1))))
5505 ;; Next error for sparse trees
5506 (setq-local next-error-function 'org-occur-next-match)
5507 ;; Make sure dependence stuff works reliably, even for users who set it
5508 ;; too late :-(
5509 (if org-enforce-todo-dependencies
5510 (add-hook 'org-blocker-hook
5511 'org-block-todo-from-children-or-siblings-or-parent)
5512 (remove-hook 'org-blocker-hook
5513 'org-block-todo-from-children-or-siblings-or-parent))
5514 (if org-enforce-todo-checkbox-dependencies
5515 (add-hook 'org-blocker-hook
5516 'org-block-todo-from-checkboxes)
5517 (remove-hook 'org-blocker-hook
5518 'org-block-todo-from-checkboxes))
5520 ;; Align options lines
5521 (setq-local
5522 align-mode-rules-list
5523 '((org-in-buffer-settings
5524 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5525 (modes . '(org-mode)))))
5527 ;; Imenu
5528 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5530 ;; Make isearch reveal context
5531 (setq-local outline-isearch-open-invisible-function
5532 (lambda (&rest _) (org-show-context 'isearch)))
5534 ;; Setup the pcomplete hooks
5535 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5536 (setq-local pcomplete-command-name-function 'org-command-at-point)
5537 (setq-local pcomplete-default-completion-function 'ignore)
5538 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5539 (setq-local pcomplete-termination-string "")
5540 (setq-local buffer-face-mode-face 'org-default)
5542 ;; If empty file that did not turn on Org mode automatically, make
5543 ;; it to.
5544 (when (and org-insert-mode-line-in-empty-file
5545 (called-interactively-p 'any)
5546 (= (point-min) (point-max)))
5547 (insert "# -*- mode: org -*-\n\n"))
5548 (unless org-inhibit-startup
5549 (org-unmodified
5550 (when org-startup-with-beamer-mode (org-beamer-mode))
5551 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5552 (org-table-map-tables
5553 (cond ((and org-startup-align-all-tables
5554 org-startup-shrink-all-tables)
5555 (lambda () (org-table-align) (org-table-shrink)))
5556 (org-startup-align-all-tables #'org-table-align)
5557 (t #'org-table-shrink))
5559 (when org-startup-with-inline-images (org-display-inline-images))
5560 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5561 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5562 (when org-startup-truncated (setq truncate-lines t))
5563 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5564 (org-refresh-effort-properties)))
5565 ;; Try to set `org-hide' face correctly.
5566 (let ((foreground (org-find-invisible-foreground)))
5567 (when foreground
5568 (set-face-foreground 'org-hide foreground))))
5570 ;; Update `customize-package-emacs-version-alist'
5571 (add-to-list 'customize-package-emacs-version-alist
5572 '(Org ("8.0" . "24.4")
5573 ("8.1" . "24.4")
5574 ("8.2" . "24.4")
5575 ("8.2.7" . "24.4")
5576 ("8.3" . "26.1")
5577 ("9.0" . "26.1")
5578 ("9.1" . "26.1")))
5580 (defvar org-mode-transpose-word-syntax-table
5581 (let ((st (make-syntax-table text-mode-syntax-table)))
5582 (dolist (c org-emphasis-alist st)
5583 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5585 (when (fboundp 'abbrev-table-put)
5586 (abbrev-table-put org-mode-abbrev-table
5587 :parents (list text-mode-abbrev-table)))
5589 (defun org-find-invisible-foreground ()
5590 (let ((candidates (remove
5591 "unspecified-bg"
5592 (nconc
5593 (list (face-background 'default)
5594 (face-background 'org-default))
5595 (mapcar
5596 (lambda (alist)
5597 (when (boundp alist)
5598 (cdr (assq 'background-color (symbol-value alist)))))
5599 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5600 (list (face-foreground 'org-hide))))))
5601 (car (remove nil candidates))))
5603 (defun org-current-time (&optional rounding-minutes past)
5604 "Current time, possibly rounded to ROUNDING-MINUTES.
5605 When ROUNDING-MINUTES is not an integer, fall back on the car of
5606 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5607 the rounding returns a past time."
5608 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5609 (car org-time-stamp-rounding-minutes)))
5610 (time (decode-time)) res)
5611 (if (< r 1)
5612 (current-time)
5613 (setq res
5614 (apply 'encode-time
5615 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5616 (nthcdr 2 time))))
5617 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5618 (seconds-to-time (- (float-time res) (* r 60)))
5619 res))))
5621 (defun org-today ()
5622 "Return today date, considering `org-extend-today-until'."
5623 (time-to-days
5624 (time-subtract (current-time)
5625 (list 0 (* 3600 org-extend-today-until) 0))))
5627 ;;;; Font-Lock stuff, including the activators
5629 (defvar org-mouse-map (make-sparse-keymap))
5630 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5631 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5632 (when org-mouse-1-follows-link
5633 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5634 (when org-tab-follows-link
5635 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5636 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5638 (require 'font-lock)
5640 (defconst org-non-link-chars "]\t\n\r<>")
5641 (defvar org-link-types-re nil
5642 "Matches a link that has a url-like prefix like \"http:\"")
5643 (defvar org-link-re-with-space nil
5644 "Matches a link with spaces, optional angular brackets around it.")
5645 (defvar org-link-re-with-space2 nil
5646 "Matches a link with spaces, optional angular brackets around it.")
5647 (defvar org-link-re-with-space3 nil
5648 "Matches a link with spaces, only for internal part in bracket links.")
5649 (defvar org-angle-link-re nil
5650 "Matches link with angular brackets, spaces are allowed.")
5651 (defvar org-plain-link-re nil
5652 "Matches plain link, without spaces.")
5653 (defvar org-bracket-link-regexp nil
5654 "Matches a link in double brackets.")
5655 (defvar org-bracket-link-analytic-regexp nil
5656 "Regular expression used to analyze links.
5657 Here is what the match groups contain after a match:
5658 1: http:
5659 2: http
5660 3: path
5661 4: [desc]
5662 5: desc")
5663 (defvar org-bracket-link-analytic-regexp++ nil
5664 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5665 (defvar org-any-link-re nil
5666 "Regular expression matching any link.")
5668 (defconst org-match-sexp-depth 3
5669 "Number of stacked braces for sub/superscript matching.")
5671 (defun org-create-multibrace-regexp (left right n)
5672 "Create a regular expression which will match a balanced sexp.
5673 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5674 as single character strings.
5675 The regexp returned will match the entire expression including the
5676 delimiters. It will also define a single group which contains the
5677 match except for the outermost delimiters. The maximum depth of
5678 stacked delimiters is N. Escaping delimiters is not possible."
5679 (let* ((nothing (concat "[^" left right "]*?"))
5680 (or "\\|")
5681 (re nothing)
5682 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5683 (while (> n 1)
5684 (setq n (1- n)
5685 re (concat re or next)
5686 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5687 (concat left "\\(" re "\\)" right)))
5689 (defconst org-match-substring-regexp
5690 (concat
5691 "\\(\\S-\\)\\([_^]\\)\\("
5692 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5693 "\\|"
5694 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5695 "\\|"
5696 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5697 "The regular expression matching a sub- or superscript.")
5699 (defconst org-match-substring-with-braces-regexp
5700 (concat
5701 "\\(\\S-\\)\\([_^]\\)"
5702 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5703 "The regular expression matching a sub- or superscript, forcing braces.")
5705 (defun org-make-link-regexps ()
5706 "Update the link regular expressions.
5707 This should be called after the variable `org-link-parameters' has changed."
5708 (let ((types-re (regexp-opt (org-link-types) t)))
5709 (setq org-link-types-re
5710 (concat "\\`" types-re ":")
5711 org-link-re-with-space
5712 (concat "<?" types-re ":"
5713 "\\([^" org-non-link-chars " ]"
5714 "[^" org-non-link-chars "]*"
5715 "[^" org-non-link-chars " ]\\)>?")
5716 org-link-re-with-space2
5717 (concat "<?" types-re ":"
5718 "\\([^" org-non-link-chars " ]"
5719 "[^\t\n\r]*"
5720 "[^" org-non-link-chars " ]\\)>?")
5721 org-link-re-with-space3
5722 (concat "<?" types-re ":"
5723 "\\([^" org-non-link-chars " ]"
5724 "[^\t\n\r]*\\)")
5725 org-angle-link-re
5726 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5727 types-re)
5728 org-plain-link-re
5729 (concat
5730 "\\<" types-re ":"
5731 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5732 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5733 org-bracket-link-regexp
5734 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5735 org-bracket-link-analytic-regexp
5736 (concat
5737 "\\[\\["
5738 "\\(" types-re ":\\)?"
5739 "\\([^]]+\\)"
5740 "\\]"
5741 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5742 "\\]")
5743 org-bracket-link-analytic-regexp++
5744 (concat
5745 "\\[\\["
5746 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5747 "\\([^]]+\\)"
5748 "\\]"
5749 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5750 "\\]")
5751 org-any-link-re
5752 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5753 org-angle-link-re "\\)\\|\\("
5754 org-plain-link-re "\\)"))))
5756 (org-make-link-regexps)
5758 (defvar org-emph-face nil)
5760 (defun org-do-emphasis-faces (limit)
5761 "Run through the buffer and emphasize strings."
5762 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5763 (car org-emphasis-regexp-components))))
5764 (catch :exit
5765 (while (re-search-forward quick-re limit t)
5766 (let* ((marker (match-string 2))
5767 (verbatim? (member marker '("~" "="))))
5768 (when (save-excursion
5769 (goto-char (match-beginning 0))
5770 ;; Do not match headline stars. Do not consider
5771 ;; stars of a headline as closing marker for bold
5772 ;; markup either. Do not match table hlines.
5773 (and
5774 (not (looking-at-p org-outline-regexp-bol))
5775 (not (and (equal marker "+")
5776 (org-match-line
5777 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5778 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5779 (not (string-match-p
5780 (concat org-outline-regexp-bol "\\'")
5781 (match-string 0)))))
5782 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5783 (font-lock-prepend-text-property
5784 (match-beginning 2) (match-end 2) 'face face)
5785 (when verbatim?
5786 (org-remove-flyspell-overlays-in
5787 (match-beginning 0) (match-end 0)))
5788 (add-text-properties (match-beginning 2) (match-end 2)
5789 '(font-lock-multiline t org-emphasis t))
5790 (when org-hide-emphasis-markers
5791 (add-text-properties (match-end 4) (match-beginning 5)
5792 '(invisible org-link))
5793 (add-text-properties (match-beginning 3) (match-end 3)
5794 '(invisible org-link)))
5795 (throw :exit t))))))))
5797 (defun org-emphasize (&optional char)
5798 "Insert or change an emphasis, i.e. a font like bold or italic.
5799 If there is an active region, change that region to a new emphasis.
5800 If there is no region, just insert the marker characters and position
5801 the cursor between them.
5802 CHAR should be the marker character. If it is a space, it means to
5803 remove the emphasis of the selected region.
5804 If CHAR is not given (for example in an interactive call) it will be
5805 prompted for."
5806 (interactive)
5807 (let ((erc org-emphasis-regexp-components)
5808 (string "") beg end move s)
5809 (if (org-region-active-p)
5810 (setq beg (region-beginning)
5811 end (region-end)
5812 string (buffer-substring beg end))
5813 (setq move t))
5815 (unless char
5816 (message "Emphasis marker or tag: [%s]"
5817 (mapconcat #'car org-emphasis-alist ""))
5818 (setq char (read-char-exclusive)))
5819 (if (equal char ?\s)
5820 (setq s ""
5821 move nil)
5822 (unless (assoc (char-to-string char) org-emphasis-alist)
5823 (user-error "No such emphasis marker: \"%c\"" char))
5824 (setq s (char-to-string char)))
5825 (while (and (> (length string) 1)
5826 (equal (substring string 0 1) (substring string -1))
5827 (assoc (substring string 0 1) org-emphasis-alist))
5828 (setq string (substring string 1 -1)))
5829 (setq string (concat s string s))
5830 (when beg (delete-region beg end))
5831 (unless (or (bolp)
5832 (string-match (concat "[" (nth 0 erc) "\n]")
5833 (char-to-string (char-before (point)))))
5834 (insert " "))
5835 (unless (or (eobp)
5836 (string-match (concat "[" (nth 1 erc) "\n]")
5837 (char-to-string (char-after (point)))))
5838 (insert " ") (backward-char 1))
5839 (insert string)
5840 (and move (backward-char 1))))
5842 (defconst org-nonsticky-props
5843 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5845 (defsubst org-rear-nonsticky-at (pos)
5846 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5848 (defun org-activate-links (limit)
5849 "Add link properties to links.
5850 This includes angle, plain, and bracket links."
5851 (catch :exit
5852 (while (re-search-forward org-any-link-re limit t)
5853 (let* ((start (match-beginning 0))
5854 (end (match-end 0))
5855 (style (cond ((eq ?< (char-after start)) 'angle)
5856 ((eq ?\[ (char-after (1+ start))) 'bracket)
5857 (t 'plain))))
5858 (when (and (memq style org-highlight-links)
5859 ;; Do not confuse plain links with tags.
5860 (not (and (eq style 'plain)
5861 (let ((face (get-text-property
5862 (max (1- start) (point-min)) 'face)))
5863 (if (consp face) (memq 'org-tag face)
5864 (eq 'org-tag face))))))
5865 (let* ((link-object (save-excursion
5866 (goto-char start)
5867 (save-match-data (org-element-link-parser))))
5868 (link (org-element-property :raw-link link-object))
5869 (type (org-element-property :type link-object))
5870 (path (org-element-property :path link-object))
5871 (properties ;for link's visible part
5872 (list
5873 'face (pcase (org-link-get-parameter type :face)
5874 ((and (pred functionp) face) (funcall face path))
5875 ((and (pred facep) face) face)
5876 ((and (pred consp) face) face) ;anonymous
5877 (_ 'org-link))
5878 'mouse-face (or (org-link-get-parameter type :mouse-face)
5879 'highlight)
5880 'keymap (or (org-link-get-parameter type :keymap)
5881 org-mouse-map)
5882 'help-echo (pcase (org-link-get-parameter type :help-echo)
5883 ((and (pred stringp) echo) echo)
5884 ((and (pred functionp) echo) echo)
5885 (_ (concat "LINK: " link)))
5886 'htmlize-link (pcase (org-link-get-parameter type
5887 :htmlize-link)
5888 ((and (pred functionp) f) (funcall f))
5889 (_ `(:uri ,link)))
5890 'font-lock-multiline t)))
5891 (org-remove-flyspell-overlays-in start end)
5892 (org-rear-nonsticky-at end)
5893 (if (not (eq 'bracket style))
5894 (add-text-properties start end properties)
5895 ;; Handle invisible parts in bracket links.
5896 (remove-text-properties start end '(invisible nil))
5897 (let ((hidden
5898 (append `(invisible
5899 ,(or (org-link-get-parameter type :display)
5900 'org-link))
5901 properties))
5902 (visible-start (or (match-beginning 4) (match-beginning 2)))
5903 (visible-end (or (match-end 4) (match-end 2))))
5904 (add-text-properties start visible-start hidden)
5905 (add-text-properties visible-start visible-end properties)
5906 (add-text-properties visible-end end hidden)
5907 (org-rear-nonsticky-at visible-start)
5908 (org-rear-nonsticky-at visible-end)))
5909 (let ((f (org-link-get-parameter type :activate-func)))
5910 (when (functionp f)
5911 (funcall f start end path (eq style 'bracket))))
5912 (throw :exit t))))) ;signal success
5913 nil))
5915 (defun org-activate-code (limit)
5916 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5917 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5918 (remove-text-properties (match-beginning 0) (match-end 0)
5919 '(display t invisible t intangible t))
5922 (defcustom org-src-fontify-natively t
5923 "When non-nil, fontify code in code blocks.
5924 See also the `org-block' face."
5925 :type 'boolean
5926 :version "26.1"
5927 :package-version '(Org . "8.3")
5928 :group 'org-appearance
5929 :group 'org-babel)
5931 (defcustom org-allow-promoting-top-level-subtree nil
5932 "When non-nil, allow promoting a top level subtree.
5933 The leading star of the top level headline will be replaced
5934 by a #."
5935 :type 'boolean
5936 :version "24.1"
5937 :group 'org-appearance)
5939 (defun org-fontify-meta-lines-and-blocks (limit)
5940 (condition-case nil
5941 (org-fontify-meta-lines-and-blocks-1 limit)
5942 (error (message "org-mode fontification error in %S at %d"
5943 (current-buffer)
5944 (line-number-at-pos)))))
5946 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5947 "Fontify #+ lines and blocks."
5948 (let ((case-fold-search t))
5949 (when (re-search-forward
5950 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5951 limit t)
5952 (let ((beg (match-beginning 0))
5953 (block-start (match-end 0))
5954 (block-end nil)
5955 (lang (match-string 7))
5956 (beg1 (line-beginning-position 2))
5957 (dc1 (downcase (match-string 2)))
5958 (dc3 (downcase (match-string 3)))
5959 end end1 quoting block-type)
5960 (cond
5961 ((and (match-end 4) (equal dc3 "+begin"))
5962 ;; Truly a block
5963 (setq block-type (downcase (match-string 5))
5964 quoting (member block-type org-protecting-blocks))
5965 (when (re-search-forward
5966 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5967 nil t) ;; on purpose, we look further than LIMIT
5968 (setq end (min (point-max) (match-end 0))
5969 end1 (min (point-max) (1- (match-beginning 0))))
5970 (setq block-end (match-beginning 0))
5971 (when quoting
5972 (org-remove-flyspell-overlays-in beg1 end1)
5973 (remove-text-properties beg end
5974 '(display t invisible t intangible t)))
5975 (add-text-properties
5976 beg end '(font-lock-fontified t font-lock-multiline t))
5977 (add-text-properties beg beg1 '(face org-meta-line))
5978 (org-remove-flyspell-overlays-in beg beg1)
5979 (add-text-properties ; For end_src
5980 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5981 (org-remove-flyspell-overlays-in end1 end)
5982 (cond
5983 ((and lang (not (string= lang "")) org-src-fontify-natively)
5984 (org-src-font-lock-fontify-block lang block-start block-end)
5985 (add-text-properties beg1 block-end '(src-block t)))
5986 (quoting
5987 (add-text-properties beg1 (min (point-max) (1+ end1))
5988 (list 'face
5989 (list :inherit
5990 (let ((face-name
5991 (intern (format "org-block-%s" lang))))
5992 (append (and (facep face-name) (list face-name))
5993 '(org-block))))))) ; end of source block
5994 ((not org-fontify-quote-and-verse-blocks))
5995 ((string= block-type "quote")
5996 (add-face-text-property
5997 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5998 ((string= block-type "verse")
5999 (add-face-text-property
6000 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6001 (add-text-properties beg beg1 '(face org-block-begin-line))
6002 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6003 '(face org-block-end-line))
6005 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6006 (org-remove-flyspell-overlays-in
6007 (match-beginning 0)
6008 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6009 (add-text-properties
6010 beg (match-end 3)
6011 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6012 '(font-lock-fontified t invisible t)
6013 '(font-lock-fontified t face org-document-info-keyword)))
6014 (add-text-properties
6015 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6016 (if (string-equal dc1 "+title:")
6017 '(font-lock-fontified t face org-document-title)
6018 '(font-lock-fontified t face org-document-info))))
6019 ((string-prefix-p "+caption" dc1)
6020 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6021 (remove-text-properties (match-beginning 0) (match-end 0)
6022 '(display t invisible t intangible t))
6023 ;; Handle short captions.
6024 (save-excursion
6025 (beginning-of-line)
6026 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6027 (add-text-properties (line-beginning-position) (match-end 1)
6028 '(font-lock-fontified t face org-meta-line))
6029 (add-text-properties (match-end 0) (line-end-position)
6030 '(font-lock-fontified t face org-block))
6032 ((member dc3 '(" " ""))
6033 (org-remove-flyspell-overlays-in beg (match-end 0))
6034 (add-text-properties
6035 beg (match-end 0)
6036 '(font-lock-fontified t face font-lock-comment-face)))
6037 (t ;; just any other in-buffer setting, but not indented
6038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6039 (remove-text-properties (match-beginning 0) (match-end 0)
6040 '(display t invisible t intangible t))
6041 (add-text-properties beg (match-end 0)
6042 '(font-lock-fontified t face org-meta-line))
6043 t))))))
6045 (defun org-fontify-drawers (limit)
6046 "Fontify drawers."
6047 (when (re-search-forward org-drawer-regexp limit t)
6048 (add-text-properties
6049 (match-beginning 0) (match-end 0)
6050 '(font-lock-fontified t face org-special-keyword))
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6054 (defun org-fontify-macros (limit)
6055 "Fontify macros."
6056 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6057 (add-text-properties
6058 (match-beginning 0) (match-end 0)
6059 '(font-lock-fontified t face org-macro))
6060 (when org-hide-macro-markers
6061 (add-text-properties (match-end 2) (match-beginning 2)
6062 '(invisible t))
6063 (add-text-properties (match-beginning 1) (match-end 1)
6064 '(invisible t)))
6065 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6068 (defun org-activate-footnote-links (limit)
6069 "Add text properties for footnotes."
6070 (let ((fn (org-footnote-next-reference-or-definition limit)))
6071 (when fn
6072 (let* ((beg (nth 1 fn))
6073 (end (nth 2 fn))
6074 (label (car fn))
6075 (referencep (/= (line-beginning-position) beg)))
6076 (when (and referencep (nth 3 fn))
6077 (save-excursion
6078 (goto-char beg)
6079 (search-forward (or label "fn:"))
6080 (org-remove-flyspell-overlays-in beg (match-end 0))))
6081 (add-text-properties beg end
6082 (list 'mouse-face 'highlight
6083 'keymap org-mouse-map
6084 'help-echo
6085 (if referencep "Footnote reference"
6086 "Footnote definition")
6087 'font-lock-fontified t
6088 'font-lock-multiline t
6089 'face 'org-footnote))))))
6091 (defun org-activate-dates (limit)
6092 "Add text properties for dates."
6093 (when (and (re-search-forward org-tsr-regexp-both limit t)
6094 (not (equal (char-before (match-beginning 0)) 91)))
6095 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6096 (add-text-properties (match-beginning 0) (match-end 0)
6097 (list 'mouse-face 'highlight
6098 'keymap org-mouse-map))
6099 (org-rear-nonsticky-at (match-end 0))
6100 (when org-display-custom-times
6101 ;; If it's a date range, activate custom time for second date.
6102 (when (match-end 3)
6103 (org-display-custom-time (match-beginning 3) (match-end 3)))
6104 (org-display-custom-time (match-beginning 1) (match-end 1)))
6107 (defvar-local org-target-link-regexp nil
6108 "Regular expression matching radio targets in plain text.")
6110 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6111 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6112 border border border))
6113 "Regular expression matching a link target.")
6115 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6116 "Regular expression matching a radio target.")
6118 (defconst org-any-target-regexp
6119 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6120 "Regular expression matching any target.")
6122 (defun org-activate-target-links (limit)
6123 "Add text properties for target matches."
6124 (when org-target-link-regexp
6125 (let ((case-fold-search t))
6126 (when (re-search-forward org-target-link-regexp limit t)
6127 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6128 (add-text-properties (match-beginning 1) (match-end 1)
6129 (list 'mouse-face 'highlight
6130 'keymap org-mouse-map
6131 'help-echo "Radio target link"
6132 'org-linked-text t))
6133 (org-rear-nonsticky-at (match-end 1))
6134 t))))
6136 (defun org-update-radio-target-regexp ()
6137 "Find all radio targets in this file and update the regular expression.
6138 Also refresh fontification if needed."
6139 (interactive)
6140 (let ((old-regexp org-target-link-regexp)
6141 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6142 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6143 (targets
6144 (org-with-wide-buffer
6145 (goto-char (point-min))
6146 (let (rtn)
6147 (while (re-search-forward org-radio-target-regexp nil t)
6148 ;; Make sure point is really within the object.
6149 (backward-char)
6150 (let ((obj (org-element-context)))
6151 (when (eq (org-element-type obj) 'radio-target)
6152 (cl-pushnew (org-element-property :value obj) rtn
6153 :test #'equal))))
6154 rtn))))
6155 (setq org-target-link-regexp
6156 (and targets
6157 (concat before-re
6158 (mapconcat
6159 (lambda (x)
6160 (replace-regexp-in-string
6161 " +" "\\s-+" (regexp-quote x) t t))
6162 targets
6163 "\\|")
6164 after-re)))
6165 (unless (equal old-regexp org-target-link-regexp)
6166 ;; Clean-up cache.
6167 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6168 ((not org-target-link-regexp) old-regexp)
6170 (concat before-re
6171 (mapconcat
6172 (lambda (re)
6173 (substring re (length before-re)
6174 (- (length after-re))))
6175 (list old-regexp org-target-link-regexp)
6176 "\\|")
6177 after-re)))))
6178 (org-with-wide-buffer
6179 (goto-char (point-min))
6180 (while (re-search-forward regexp nil t)
6181 (org-element-cache-refresh (match-beginning 1)))))
6182 ;; Re fontify buffer.
6183 (when (memq 'radio org-highlight-links)
6184 (org-restart-font-lock)))))
6186 (defvar org-latex-and-related-regexp nil
6187 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6189 (defun org-compute-latex-and-related-regexp ()
6190 "Compute regular expression for LaTeX, entities and sub/superscript.
6191 Result depends on variable `org-highlight-latex-and-related'."
6192 (setq-local
6193 org-latex-and-related-regexp
6194 (let* ((re-sub
6195 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6196 ((eq org-use-sub-superscripts '{})
6197 (list org-match-substring-with-braces-regexp))
6198 (org-use-sub-superscripts (list org-match-substring-regexp))))
6199 (re-latex
6200 (when (memq 'latex org-highlight-latex-and-related)
6201 (let ((matchers (plist-get org-format-latex-options :matchers)))
6202 (delq nil
6203 (mapcar (lambda (x)
6204 (and (member (car x) matchers) (nth 1 x)))
6205 org-latex-regexps)))))
6206 (re-entities
6207 (when (memq 'entities org-highlight-latex-and-related)
6208 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6209 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6211 (defun org-do-latex-and-related (limit)
6212 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6213 LIMIT bounds the search for syntax to highlight. Stop at first
6214 highlighted object, if any. Return t if some highlighting was
6215 done, nil otherwise."
6216 (when (org-string-nw-p org-latex-and-related-regexp)
6217 (catch 'found
6218 (while (re-search-forward org-latex-and-related-regexp limit t)
6219 (unless
6220 (cl-some
6221 (lambda (f)
6222 (memq f '(org-code org-verbatim underline org-special-keyword)))
6223 (save-excursion
6224 (goto-char (1+ (match-beginning 0)))
6225 (face-at-point nil t)))
6226 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6227 '(?_ ?^))
6229 0)))
6230 (font-lock-prepend-text-property
6231 (+ offset (match-beginning 0)) (match-end 0)
6232 'face 'org-latex-and-related)
6233 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6234 '(font-lock-multiline t)))
6235 (throw 'found t)))
6236 nil)))
6238 (defun org-restart-font-lock ()
6239 "Restart `font-lock-mode', to force refontification."
6240 (when (and (boundp 'font-lock-mode) font-lock-mode)
6241 (font-lock-mode -1)
6242 (font-lock-mode 1)))
6244 (defun org-activate-tags (limit)
6245 (when (re-search-forward
6246 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6247 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6248 (add-text-properties (match-beginning 1) (match-end 1)
6249 (list 'mouse-face 'highlight
6250 'keymap org-mouse-map))
6251 (org-rear-nonsticky-at (match-end 1))
6254 (defun org-outline-level ()
6255 "Compute the outline level of the heading at point.
6257 If this is called at a normal headline, the level is the number
6258 of stars. Use `org-reduced-level' to remove the effect of
6259 `org-odd-levels'. Unlike to `org-current-level', this function
6260 takes into consideration inlinetasks."
6261 (org-with-wide-buffer
6262 (end-of-line)
6263 (if (re-search-backward org-outline-regexp-bol nil t)
6264 (1- (- (match-end 0) (match-beginning 0)))
6265 0)))
6267 (defvar org-font-lock-keywords nil)
6269 (defsubst org-re-property (property &optional literal allow-null value)
6270 "Return a regexp matching a PROPERTY line.
6272 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6273 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6274 non-nil, match properties even without a value.
6276 Match group 3 is set to the value when it exists. If there is no
6277 value and ALLOW-NULL is non-nil, it is set to the empty string.
6279 With optional argument VALUE, match only property lines with
6280 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6281 unless LITERAL is non-nil."
6282 (concat
6283 "^\\(?4:[ \t]*\\)"
6284 (format "\\(?1::\\(?2:%s\\):\\)"
6285 (if literal property (regexp-quote property)))
6286 (cond (value
6287 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6288 (if literal value (regexp-quote value))))
6289 (allow-null
6290 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6292 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6294 (defconst org-property-re
6295 (org-re-property "\\S-+" 'literal t)
6296 "Regular expression matching a property line.
6297 There are four matching groups:
6298 1: :PROPKEY: including the leading and trailing colon,
6299 2: PROPKEY without the leading and trailing colon,
6300 3: PROPVAL without leading or trailing spaces,
6301 4: the indentation of the current line,
6302 5: trailing whitespace.")
6304 (defvar org-font-lock-hook nil
6305 "Functions to be called for special font lock stuff.")
6307 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6309 (defvar org-font-lock-set-keywords-hook nil
6310 "Functions that can manipulate `org-font-lock-extra-keywords'.
6311 This is called after `org-font-lock-extra-keywords' is defined, but before
6312 it is installed to be used by font lock. This can be useful if something
6313 needs to be inserted at a specific position in the font-lock sequence.")
6315 (defun org-font-lock-hook (limit)
6316 "Run `org-font-lock-hook' within LIMIT."
6317 (run-hook-with-args 'org-font-lock-hook limit))
6319 (defun org-set-font-lock-defaults ()
6320 "Set font lock defaults for the current buffer."
6321 (let* ((em org-fontify-emphasized-text)
6322 (lk org-highlight-links)
6323 (org-font-lock-extra-keywords
6324 (list
6325 ;; Call the hook
6326 '(org-font-lock-hook)
6327 ;; Headlines
6328 `(,(if org-fontify-whole-heading-line
6329 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6330 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6331 (1 (org-get-level-face 1))
6332 (2 (org-get-level-face 2))
6333 (3 (org-get-level-face 3)))
6334 ;; Table lines
6335 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6336 (1 'org-table t))
6337 ;; Table internals
6338 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6339 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6340 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6341 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6342 ;; Drawers
6343 '(org-fontify-drawers)
6344 ;; Properties
6345 (list org-property-re
6346 '(1 'org-special-keyword t)
6347 '(3 'org-property-value t))
6348 ;; Link related fontification.
6349 '(org-activate-links)
6350 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6351 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6352 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6353 (when (memq 'footnote lk) '(org-activate-footnote-links))
6354 ;; Targets.
6355 (list org-any-target-regexp '(0 'org-target t))
6356 ;; Diary sexps.
6357 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6358 ;; Macro
6359 '(org-fontify-macros)
6360 ;; TODO keyword
6361 (list (format org-heading-keyword-regexp-format
6362 org-todo-regexp)
6363 '(2 (org-get-todo-face 2) t))
6364 ;; DONE
6365 (if org-fontify-done-headline
6366 (list (format org-heading-keyword-regexp-format
6367 (concat
6368 "\\(?:"
6369 (mapconcat 'regexp-quote org-done-keywords "\\|")
6370 "\\)"))
6371 '(2 'org-headline-done t))
6372 nil)
6373 ;; Priorities
6374 '(org-font-lock-add-priority-faces)
6375 ;; Tags
6376 '(org-font-lock-add-tag-faces)
6377 ;; Tags groups
6378 (when (and org-group-tags org-tag-groups-alist)
6379 (list (concat org-outline-regexp-bol ".+\\(:"
6380 (regexp-opt (mapcar 'car org-tag-groups-alist))
6381 ":\\).*$")
6382 '(1 'org-tag-group prepend)))
6383 ;; Special keywords
6384 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6385 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6386 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6387 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6388 ;; Emphasis
6389 (when em '(org-do-emphasis-faces))
6390 ;; Checkboxes
6391 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6392 1 'org-checkbox prepend)
6393 (when (cdr (assq 'checkbox org-list-automatic-rules))
6394 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6395 (0 (org-get-checkbox-statistics-face) t)))
6396 ;; Description list items
6397 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6398 1 'org-list-dt prepend)
6399 ;; ARCHIVEd headings
6400 (list (concat
6401 org-outline-regexp-bol
6402 "\\(.*:" org-archive-tag ":.*\\)")
6403 '(1 'org-archived prepend))
6404 ;; Specials
6405 '(org-do-latex-and-related)
6406 '(org-fontify-entities)
6407 '(org-raise-scripts)
6408 ;; Code
6409 '(org-activate-code (1 'org-code t))
6410 ;; COMMENT
6411 (list (format
6412 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6413 org-todo-regexp
6414 org-comment-string)
6415 '(9 'org-special-keyword t))
6416 ;; Blocks and meta lines
6417 '(org-fontify-meta-lines-and-blocks))))
6418 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6419 (run-hooks 'org-font-lock-set-keywords-hook)
6420 ;; Now set the full font-lock-keywords
6421 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6422 (setq-local font-lock-defaults
6423 '(org-font-lock-keywords t nil nil backward-paragraph))
6424 (kill-local-variable 'font-lock-keywords)
6425 nil))
6427 (defun org-toggle-pretty-entities ()
6428 "Toggle the composition display of entities as UTF8 characters."
6429 (interactive)
6430 (setq-local org-pretty-entities (not org-pretty-entities))
6431 (org-restart-font-lock)
6432 (if org-pretty-entities
6433 (message "Entities are now displayed as UTF8 characters")
6434 (save-restriction
6435 (widen)
6436 (decompose-region (point-min) (point-max))
6437 (message "Entities are now displayed as plain text"))))
6439 (defvar-local org-custom-properties-overlays nil
6440 "List of overlays used for custom properties.")
6442 (defun org-toggle-custom-properties-visibility ()
6443 "Display or hide properties in `org-custom-properties'."
6444 (interactive)
6445 (if org-custom-properties-overlays
6446 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6447 (setq org-custom-properties-overlays nil))
6448 (when org-custom-properties
6449 (org-with-wide-buffer
6450 (goto-char (point-min))
6451 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6452 (while (re-search-forward regexp nil t)
6453 (let ((end (cdr (save-match-data (org-get-property-block)))))
6454 (when (and end (< (point) end))
6455 ;; Hide first custom property in current drawer.
6456 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6457 (overlay-put o 'invisible t)
6458 (overlay-put o 'org-custom-property t)
6459 (push o org-custom-properties-overlays))
6460 ;; Hide additional custom properties in the same drawer.
6461 (while (re-search-forward regexp end t)
6462 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6463 (overlay-put o 'invisible t)
6464 (overlay-put o 'org-custom-property t)
6465 (push o org-custom-properties-overlays)))))
6466 ;; Each entry is limited to a single property drawer.
6467 (outline-next-heading)))))))
6469 (defun org-fontify-entities (limit)
6470 "Find an entity to fontify."
6471 (let (ee)
6472 (when org-pretty-entities
6473 (catch 'match
6474 ;; "\_ "-family is left out on purpose. Only the first one,
6475 ;; i.e., "\_ ", could be fontified anyway, and it would be
6476 ;; confusing when adding a second white space character.
6477 (while (re-search-forward
6478 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6479 limit t)
6480 (when (and (not (org-at-comment-p))
6481 (setq ee (org-entity-get (match-string 1)))
6482 (= (length (nth 6 ee)) 1))
6483 (let* ((end (if (equal (match-string 2) "{}")
6484 (match-end 2)
6485 (match-end 1))))
6486 (add-text-properties
6487 (match-beginning 0) end
6488 (list 'font-lock-fontified t))
6489 (compose-region (match-beginning 0) end
6490 (nth 6 ee) nil)
6491 (backward-char 1)
6492 (throw 'match t))))
6493 nil))))
6495 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6496 "Fontify string S like in Org mode."
6497 (with-temp-buffer
6498 (insert s)
6499 (let ((org-odd-levels-only odd-levels))
6500 (org-mode)
6501 (org-font-lock-ensure)
6502 (buffer-string))))
6504 (defvar org-m nil)
6505 (defvar org-l nil)
6506 (defvar org-f nil)
6507 (defun org-get-level-face (n)
6508 "Get the right face for match N in font-lock matching of headlines."
6509 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6510 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6511 (if org-cycle-level-faces
6512 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6513 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6514 (cond
6515 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6516 ((eq n 2) org-f)
6517 (t (unless org-level-color-stars-only org-f))))
6519 (defun org-face-from-face-or-color (context inherit face-or-color)
6520 "Create a face list that inherits INHERIT, but sets the foreground color.
6521 When FACE-OR-COLOR is not a string, just return it."
6522 (if (stringp face-or-color)
6523 (list :inherit inherit
6524 (cdr (assoc context org-faces-easy-properties))
6525 face-or-color)
6526 face-or-color))
6528 (defun org-get-todo-face (kwd)
6529 "Get the right face for a TODO keyword KWD.
6530 If KWD is a number, get the corresponding match group."
6531 (when (numberp kwd) (setq kwd (match-string kwd)))
6532 (or (org-face-from-face-or-color
6533 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6534 (and (member kwd org-done-keywords) 'org-done)
6535 'org-todo))
6537 (defun org-get-priority-face (priority)
6538 "Get the right face for PRIORITY.
6539 PRIORITY is a character."
6540 (or (org-face-from-face-or-color
6541 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6542 'org-priority))
6544 (defun org-get-tag-face (tag)
6545 "Get the right face for TAG.
6546 If TAG is a number, get the corresponding match group."
6547 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6548 (or (org-face-from-face-or-color
6549 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6550 'org-tag)))
6552 (defun org-font-lock-add-priority-faces (limit)
6553 "Add the special priority faces."
6554 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6555 (add-text-properties
6556 (match-beginning 1) (match-end 1)
6557 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6558 'font-lock-fontified t))))
6560 (defun org-font-lock-add-tag-faces (limit)
6561 "Add the special tag faces."
6562 (when (and org-tag-faces org-tags-special-faces-re)
6563 (while (re-search-forward org-tags-special-faces-re limit t)
6564 (add-text-properties (match-beginning 1) (match-end 1)
6565 (list 'face (org-get-tag-face 1)
6566 'font-lock-fontified t))
6567 (backward-char 1))))
6569 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6570 "Remove fontification and activation overlays from links."
6571 (font-lock-default-unfontify-region beg end)
6572 (let* ((buffer-undo-list t)
6573 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6574 (inhibit-modification-hooks t)
6575 deactivate-mark buffer-file-name buffer-file-truename)
6576 (decompose-region beg end)
6577 (remove-text-properties beg end
6578 '(mouse-face t keymap t org-linked-text t
6579 invisible t intangible t
6580 org-emphasis t))
6581 (org-remove-font-lock-display-properties beg end)))
6583 (defconst org-script-display '(((raise -0.3) (height 0.7))
6584 ((raise 0.3) (height 0.7))
6585 ((raise -0.5))
6586 ((raise 0.5)))
6587 "Display properties for showing superscripts and subscripts.")
6589 (defun org-remove-font-lock-display-properties (beg end)
6590 "Remove specific display properties that have been added by font lock.
6591 The will remove the raise properties that are used to show superscripts
6592 and subscripts."
6593 (let (next prop)
6594 (while (< beg end)
6595 (setq next (next-single-property-change beg 'display nil end)
6596 prop (get-text-property beg 'display))
6597 (when (member prop org-script-display)
6598 (put-text-property beg next 'display nil))
6599 (setq beg next))))
6601 (defun org-raise-scripts (limit)
6602 "Add raise properties to sub/superscripts."
6603 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6604 (re-search-forward
6605 (if (eq org-use-sub-superscripts t)
6606 org-match-substring-regexp
6607 org-match-substring-with-braces-regexp)
6608 limit t))
6609 (let* ((pos (point)) table-p comment-p
6610 (mpos (match-beginning 3))
6611 (emph-p (get-text-property mpos 'org-emphasis))
6612 (link-p (get-text-property mpos 'mouse-face))
6613 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6614 (goto-char (point-at-bol))
6615 (setq table-p (looking-at-p org-table-dataline-regexp)
6616 comment-p (looking-at-p "^[ \t]*#[ +]"))
6617 (goto-char pos)
6618 ;; Handle a_b^c
6619 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6620 (unless (or comment-p emph-p link-p keyw-p)
6621 (put-text-property (match-beginning 3) (match-end 0)
6622 'display
6623 (if (equal (char-after (match-beginning 2)) ?^)
6624 (nth (if table-p 3 1) org-script-display)
6625 (nth (if table-p 2 0) org-script-display)))
6626 (add-text-properties (match-beginning 2) (match-end 2)
6627 (list 'invisible t))
6628 (when (and (eq (char-after (match-beginning 3)) ?{)
6629 (eq (char-before (match-end 3)) ?}))
6630 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6631 (list 'invisible t))
6632 (add-text-properties (1- (match-end 3)) (match-end 3)
6633 (list 'invisible t))))
6634 t)))
6636 ;;;; Visibility cycling, including org-goto and indirect buffer
6638 ;;; Cycling
6640 (defvar-local org-cycle-global-status nil)
6641 (put 'org-cycle-global-status 'org-state t)
6642 (defvar-local org-cycle-subtree-status nil)
6643 (put 'org-cycle-subtree-status 'org-state t)
6645 (defvar org-inlinetask-min-level)
6647 (defun org-unlogged-message (&rest args)
6648 "Display a message, but avoid logging it in the *Messages* buffer."
6649 (let ((message-log-max nil))
6650 (apply 'message args)))
6652 ;;;###autoload
6653 (defun org-cycle (&optional arg)
6654 "TAB-action and visibility cycling for Org mode.
6656 This is the command invoked in Org mode by the `TAB' key. Its main
6657 purpose is outline visibility cycling, but it also invokes other actions
6658 in special contexts.
6660 When this function is called with a `\\[universal-argument]' prefix, rotate \
6661 the entire
6662 buffer through 3 states (global cycling)
6663 1. OVERVIEW: Show only top-level headlines.
6664 2. CONTENTS: Show all headlines of all levels, but no body text.
6665 3. SHOW ALL: Show everything.
6667 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6668 switch to the startup visibility,
6669 determined by the variable `org-startup-folded', and by any VISIBILITY
6670 properties in the buffer.
6672 With a `\\[universal-argument] \\[universal-argument] \
6673 \\[universal-argument]' prefix argument, show the entire buffer, including
6674 any drawers.
6676 When inside a table, re-align the table and move to the next field.
6678 When point is at the beginning of a headline, rotate the subtree started
6679 by this line through 3 different states (local cycling)
6680 1. FOLDED: Only the main headline is shown.
6681 2. CHILDREN: The main headline and the direct children are shown.
6682 From this state, you can move to one of the children
6683 and zoom in further.
6684 3. SUBTREE: Show the entire subtree, including body text.
6685 If there is no subtree, switch directly from CHILDREN to FOLDED.
6687 When point is at the beginning of an empty headline and the variable
6688 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6689 of the headline by demoting and promoting it to likely levels. This
6690 speeds up creation document structure by pressing `TAB' once or several
6691 times right after creating a new headline.
6693 When there is a numeric prefix, go up to a heading with level ARG, do
6694 a `show-subtree' and return to the previous cursor position. If ARG
6695 is negative, go up that many levels.
6697 When point is not at the beginning of a headline, execute the global
6698 binding for `TAB', which is re-indenting the line. See the option
6699 `org-cycle-emulate-tab' for details.
6701 As a special case, if point is at the beginning of the buffer and there is
6702 no headline in line 1, this function will act as if called with prefix arg
6703 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6704 prefix arg, but only
6705 if the variable `org-cycle-global-at-bob' is t."
6706 (interactive "P")
6707 (org-load-modules-maybe)
6708 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6709 (and org-cycle-level-after-item/entry-creation
6710 (or (org-cycle-level)
6711 (org-cycle-item-indentation))))
6712 (let* ((limit-level
6713 (or org-cycle-max-level
6714 (and (boundp 'org-inlinetask-min-level)
6715 org-inlinetask-min-level
6716 (1- org-inlinetask-min-level))))
6717 (nstars (and limit-level
6718 (if org-odd-levels-only
6719 (and limit-level (1- (* limit-level 2)))
6720 limit-level)))
6721 (org-outline-regexp
6722 (if (not (derived-mode-p 'org-mode))
6723 outline-regexp
6724 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6725 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6726 (not (looking-at org-outline-regexp))))
6727 (org-cycle-hook
6728 (if bob-special
6729 (delq 'org-optimize-window-after-visibility-change
6730 (copy-sequence org-cycle-hook))
6731 org-cycle-hook))
6732 (pos (point)))
6734 (cond
6736 ((equal arg '(16))
6737 (setq last-command 'dummy)
6738 (org-set-startup-visibility)
6739 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6741 ((equal arg '(64))
6742 (outline-show-all)
6743 (org-unlogged-message "Entire buffer visible, including drawers"))
6745 ((equal arg '(4)) (org-cycle-internal-global))
6747 ;; Try hiding block at point.
6748 ((org-hide-block-toggle-maybe))
6750 ;; Try cdlatex TAB completion
6751 ((org-try-cdlatex-tab))
6753 ;; Table: enter it or move to the next field.
6754 ((org-at-table-p 'any)
6755 (if (org-at-table.el-p)
6756 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6757 Use `\\[org-edit-special]' to edit table.el tables"))
6758 (if arg (org-table-edit-field t)
6759 (org-table-justify-field-maybe)
6760 (call-interactively 'org-table-next-field))))
6762 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6764 ;; Global cycling: delegate to `org-cycle-internal-global'.
6765 (bob-special (org-cycle-internal-global))
6767 ;; Drawers: delegate to `org-flag-drawer'.
6768 ((save-excursion
6769 (beginning-of-line 1)
6770 (looking-at org-drawer-regexp))
6771 (org-flag-drawer ; toggle block visibility
6772 (not (get-char-property (match-end 0) 'invisible))))
6774 ;; Show-subtree, ARG levels up from here.
6775 ((integerp arg)
6776 (save-excursion
6777 (org-back-to-heading)
6778 (outline-up-heading (if (< arg 0) (- arg)
6779 (- (funcall outline-level) arg)))
6780 (org-show-subtree)))
6782 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6783 ((and (featurep 'org-inlinetask)
6784 (org-inlinetask-at-task-p)
6785 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6786 (org-inlinetask-toggle-visibility))
6788 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6789 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6790 (save-excursion (move-beginning-of-line 1)
6791 (looking-at org-outline-regexp)))
6792 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6793 (org-cycle-internal-local))
6795 ;; From there: TAB emulation and template completion.
6796 (buffer-read-only (org-back-to-heading))
6798 ((run-hook-with-args-until-success
6799 'org-tab-after-check-for-cycling-hook))
6801 ((org-try-structure-completion))
6803 ((run-hook-with-args-until-success
6804 'org-tab-before-tab-emulation-hook))
6806 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6807 (or (not (bolp))
6808 (not (looking-at org-outline-regexp))))
6809 (call-interactively (global-key-binding "\t")))
6811 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6812 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6813 (or (and (eq org-cycle-emulate-tab 'white)
6814 (= (match-end 0) (point-at-eol)))
6815 (and (eq org-cycle-emulate-tab 'whitestart)
6816 (>= (match-end 0) pos))))
6818 (eq org-cycle-emulate-tab t))
6819 (call-interactively (global-key-binding "\t")))
6821 (t (save-excursion
6822 (org-back-to-heading)
6823 (org-cycle)))))))
6825 (defun org-cycle-internal-global ()
6826 "Do the global cycling action."
6827 ;; Hack to avoid display of messages for .org attachments in Gnus
6828 (let ((ga (string-match "\\*fontification" (buffer-name))))
6829 (cond
6830 ((and (eq last-command this-command)
6831 (eq org-cycle-global-status 'overview))
6832 ;; We just created the overview - now do table of contents
6833 ;; This can be slow in very large buffers, so indicate action
6834 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6835 (unless ga (org-unlogged-message "CONTENTS..."))
6836 (org-content)
6837 (unless ga (org-unlogged-message "CONTENTS...done"))
6838 (setq org-cycle-global-status 'contents)
6839 (run-hook-with-args 'org-cycle-hook 'contents))
6841 ((and (eq last-command this-command)
6842 (eq org-cycle-global-status 'contents))
6843 ;; We just showed the table of contents - now show everything
6844 (run-hook-with-args 'org-pre-cycle-hook 'all)
6845 (outline-show-all)
6846 (unless ga (org-unlogged-message "SHOW ALL"))
6847 (setq org-cycle-global-status 'all)
6848 (run-hook-with-args 'org-cycle-hook 'all))
6851 ;; Default action: go to overview
6852 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6853 (org-overview)
6854 (unless ga (org-unlogged-message "OVERVIEW"))
6855 (setq org-cycle-global-status 'overview)
6856 (run-hook-with-args 'org-cycle-hook 'overview)))))
6858 (defvar org-called-with-limited-levels nil
6859 "Non-nil when `org-with-limited-levels' is currently active.")
6861 (defun org-invisible-p (&optional pos)
6862 "Non-nil if the character after POS is invisible.
6863 If POS is nil, use `point' instead."
6864 (get-char-property (or pos (point)) 'invisible))
6866 (defun org-cycle-internal-local ()
6867 "Do the local cycling action."
6868 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6869 ;; First, determine end of headline (EOH), end of subtree or item
6870 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6871 (save-excursion
6872 (if (org-at-item-p)
6873 (progn
6874 (beginning-of-line)
6875 (setq struct (org-list-struct))
6876 (setq eoh (point-at-eol))
6877 (setq eos (org-list-get-item-end-before-blank (point) struct))
6878 (setq has-children (org-list-has-child-p (point) struct)))
6879 (org-back-to-heading)
6880 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6881 (setq eos (save-excursion (org-end-of-subtree t t)
6882 (when (bolp) (backward-char)) (point)))
6883 (setq has-children
6884 (or (save-excursion
6885 (let ((level (funcall outline-level)))
6886 (outline-next-heading)
6887 (and (org-at-heading-p t)
6888 (> (funcall outline-level) level))))
6889 (save-excursion
6890 (org-list-search-forward (org-item-beginning-re) eos t)))))
6891 ;; Determine end invisible part of buffer (EOL)
6892 (beginning-of-line 2)
6893 (while (and (not (eobp)) ;This is like `next-line'.
6894 (get-char-property (1- (point)) 'invisible))
6895 (goto-char (next-single-char-property-change (point) 'invisible))
6896 (and (eolp) (beginning-of-line 2)))
6897 (setq eol (point)))
6898 ;; Find out what to do next and set `this-command'
6899 (cond
6900 ((= eos eoh)
6901 ;; Nothing is hidden behind this heading
6902 (unless (org-before-first-heading-p)
6903 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6904 (org-unlogged-message "EMPTY ENTRY")
6905 (setq org-cycle-subtree-status nil)
6906 (save-excursion
6907 (goto-char eos)
6908 (outline-next-heading)
6909 (when (org-invisible-p) (org-flag-heading nil))))
6910 ((and (or (>= eol eos)
6911 (not (string-match "\\S-" (buffer-substring eol eos))))
6912 (or has-children
6913 (not (setq children-skipped
6914 org-cycle-skip-children-state-if-no-children))))
6915 ;; Entire subtree is hidden in one line: children view
6916 (unless (org-before-first-heading-p)
6917 (run-hook-with-args 'org-pre-cycle-hook 'children))
6918 (if (org-at-item-p)
6919 (org-list-set-item-visibility (point-at-bol) struct 'children)
6920 (org-show-entry)
6921 (org-with-limited-levels (org-show-children))
6922 ;; FIXME: This slows down the func way too much.
6923 ;; How keep drawers hidden in subtree anyway?
6924 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6925 ;; (org-cycle-hide-drawers 'subtree))
6927 ;; Fold every list in subtree to top-level items.
6928 (when (eq org-cycle-include-plain-lists 'integrate)
6929 (save-excursion
6930 (org-back-to-heading)
6931 (while (org-list-search-forward (org-item-beginning-re) eos t)
6932 (beginning-of-line 1)
6933 (let* ((struct (org-list-struct))
6934 (prevs (org-list-prevs-alist struct))
6935 (end (org-list-get-bottom-point struct)))
6936 (dolist (e (org-list-get-all-items (point) struct prevs))
6937 (org-list-set-item-visibility e struct 'folded))
6938 (goto-char (if (< end eos) end eos)))))))
6939 (org-unlogged-message "CHILDREN")
6940 (save-excursion
6941 (goto-char eos)
6942 (outline-next-heading)
6943 (when (org-invisible-p) (org-flag-heading nil)))
6944 (setq org-cycle-subtree-status 'children)
6945 (unless (org-before-first-heading-p)
6946 (run-hook-with-args 'org-cycle-hook 'children)))
6947 ((or children-skipped
6948 (and (eq last-command this-command)
6949 (eq org-cycle-subtree-status 'children)))
6950 ;; We just showed the children, or no children are there,
6951 ;; now show everything.
6952 (unless (org-before-first-heading-p)
6953 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6954 (outline-flag-region eoh eos nil)
6955 (org-unlogged-message
6956 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6957 (setq org-cycle-subtree-status 'subtree)
6958 (unless (org-before-first-heading-p)
6959 (run-hook-with-args 'org-cycle-hook 'subtree)))
6961 ;; Default action: hide the subtree.
6962 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6963 (outline-flag-region eoh eos t)
6964 (org-unlogged-message "FOLDED")
6965 (setq org-cycle-subtree-status 'folded)
6966 (unless (org-before-first-heading-p)
6967 (run-hook-with-args 'org-cycle-hook 'folded))))))
6969 ;;;###autoload
6970 (defun org-global-cycle (&optional arg)
6971 "Cycle the global visibility. For details see `org-cycle'.
6972 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6973 With a numeric prefix, show all headlines up to that level."
6974 (interactive "P")
6975 (let ((org-cycle-include-plain-lists
6976 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6977 (cond
6978 ((integerp arg)
6979 (outline-show-all)
6980 (outline-hide-sublevels arg)
6981 (setq org-cycle-global-status 'contents))
6982 ((equal arg '(4))
6983 (org-set-startup-visibility)
6984 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6986 (org-cycle '(4))))))
6988 (defun org-set-startup-visibility ()
6989 "Set the visibility required by startup options and properties."
6990 (cond
6991 ((eq org-startup-folded t)
6992 (org-overview))
6993 ((eq org-startup-folded 'content)
6994 (org-content))
6995 ((or (eq org-startup-folded 'showeverything)
6996 (eq org-startup-folded nil))
6997 (outline-show-all)))
6998 (unless (eq org-startup-folded 'showeverything)
6999 (when org-hide-block-startup (org-hide-block-all))
7000 (org-set-visibility-according-to-property 'no-cleanup)
7001 (org-cycle-hide-archived-subtrees 'all)
7002 (org-cycle-hide-drawers 'all)
7003 (org-cycle-show-empty-lines t)))
7005 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7006 "Switch subtree visibilities according to :VISIBILITY: property."
7007 (interactive)
7008 (org-with-wide-buffer
7009 (goto-char (point-min))
7010 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7011 (if (not (org-at-property-p)) (outline-next-heading)
7012 (let ((state (match-string 3)))
7013 (save-excursion
7014 (org-back-to-heading t)
7015 (outline-hide-subtree)
7016 (org-reveal)
7017 (cond
7018 ((equal state "folded")
7019 (outline-hide-subtree))
7020 ((equal state "children")
7021 (org-show-hidden-entry)
7022 (org-show-children))
7023 ((equal state "content")
7024 (save-excursion
7025 (save-restriction
7026 (org-narrow-to-subtree)
7027 (org-content))))
7028 ((member state '("all" "showall"))
7029 (outline-show-subtree)))))))
7030 (unless no-cleanup
7031 (org-cycle-hide-archived-subtrees 'all)
7032 (org-cycle-hide-drawers 'all)
7033 (org-cycle-show-empty-lines 'all))))
7035 ;; This function uses outline-regexp instead of the more fundamental
7036 ;; org-outline-regexp so that org-cycle-global works outside of Org
7037 ;; buffers, where outline-regexp is needed.
7038 (defun org-overview ()
7039 "Switch to overview mode, showing only top-level headlines.
7040 This shows all headlines with a level equal or greater than the level
7041 of the first headline in the buffer. This is important, because if the
7042 first headline is not level one, then (hide-sublevels 1) gives confusing
7043 results."
7044 (interactive)
7045 (save-excursion
7046 (let ((level
7047 (save-excursion
7048 (goto-char (point-min))
7049 (when (re-search-forward (concat "^" outline-regexp) nil t)
7050 (goto-char (match-beginning 0))
7051 (funcall outline-level)))))
7052 (and level (outline-hide-sublevels level)))))
7054 (defun org-content (&optional arg)
7055 "Show all headlines in the buffer, like a table of contents.
7056 With numerical argument N, show content up to level N."
7057 (interactive "P")
7058 (org-overview)
7059 (save-excursion
7060 ;; Visit all headings and show their offspring
7061 (and (integerp arg) (org-overview))
7062 (goto-char (point-max))
7063 (catch 'exit
7064 (while (and (progn (condition-case nil
7065 (outline-previous-visible-heading 1)
7066 (error (goto-char (point-min))))
7068 (looking-at org-outline-regexp))
7069 (if (integerp arg)
7070 (org-show-children (1- arg))
7071 (outline-show-branches))
7072 (when (bobp) (throw 'exit nil))))))
7074 (defun org-optimize-window-after-visibility-change (state)
7075 "Adjust the window after a change in outline visibility.
7076 This function is the default value of the hook `org-cycle-hook'."
7077 (when (get-buffer-window (current-buffer))
7078 (cond
7079 ((eq state 'content) nil)
7080 ((eq state 'all) nil)
7081 ((eq state 'folded) nil)
7082 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7083 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7085 (defun org-remove-empty-overlays-at (pos)
7086 "Remove outline overlays that do not contain non-white stuff."
7087 (dolist (o (overlays-at pos))
7088 (and (eq 'outline (overlay-get o 'invisible))
7089 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7090 (overlay-end o))))
7091 (delete-overlay o))))
7093 (defun org-clean-visibility-after-subtree-move ()
7094 "Fix visibility issues after moving a subtree."
7095 ;; First, find a reasonable region to look at:
7096 ;; Start two siblings above, end three below
7097 (let* ((beg (save-excursion
7098 (and (org-get-last-sibling)
7099 (org-get-last-sibling))
7100 (point)))
7101 (end (save-excursion
7102 (and (org-get-next-sibling)
7103 (org-get-next-sibling)
7104 (org-get-next-sibling))
7105 (if (org-at-heading-p)
7106 (point-at-eol)
7107 (point))))
7108 (level (looking-at "\\*+"))
7109 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7110 (save-excursion
7111 (save-restriction
7112 (narrow-to-region beg end)
7113 (when re
7114 ;; Properly fold already folded siblings
7115 (goto-char (point-min))
7116 (while (re-search-forward re nil t)
7117 (when (and (not (org-invisible-p))
7118 (save-excursion
7119 (goto-char (point-at-eol)) (org-invisible-p)))
7120 (outline-hide-entry))))
7121 (org-cycle-show-empty-lines 'overview)
7122 (org-cycle-hide-drawers 'overview)))))
7124 (defun org-cycle-show-empty-lines (state)
7125 "Show empty lines above all visible headlines.
7126 The region to be covered depends on STATE when called through
7127 `org-cycle-hook'. Lisp program can use t for STATE to get the
7128 entire buffer covered. Note that an empty line is only shown if there
7129 are at least `org-cycle-separator-lines' empty lines before the headline."
7130 (when (/= org-cycle-separator-lines 0)
7131 (save-excursion
7132 (let* ((n (abs org-cycle-separator-lines))
7133 (re (cond
7134 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7135 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7136 (t (let ((ns (number-to-string (- n 2))))
7137 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7138 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7139 beg end)
7140 (cond
7141 ((memq state '(overview contents t))
7142 (setq beg (point-min) end (point-max)))
7143 ((memq state '(children folded))
7144 (setq beg (point)
7145 end (progn (org-end-of-subtree t t)
7146 (line-beginning-position 2)))))
7147 (when beg
7148 (goto-char beg)
7149 (while (re-search-forward re end t)
7150 (unless (get-char-property (match-end 1) 'invisible)
7151 (let ((e (match-end 1))
7152 (b (if (>= org-cycle-separator-lines 0)
7153 (match-beginning 1)
7154 (save-excursion
7155 (goto-char (match-beginning 0))
7156 (skip-chars-backward " \t\n")
7157 (line-end-position)))))
7158 (outline-flag-region b e nil))))))))
7159 ;; Never hide empty lines at the end of the file.
7160 (save-excursion
7161 (goto-char (point-max))
7162 (outline-previous-heading)
7163 (outline-end-of-heading)
7164 (when (and (looking-at "[ \t\n]+")
7165 (= (match-end 0) (point-max)))
7166 (outline-flag-region (point) (match-end 0) nil))))
7168 (defun org-show-empty-lines-in-parent ()
7169 "Move to the parent and re-show empty lines before visible headlines."
7170 (save-excursion
7171 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7172 (org-cycle-show-empty-lines context))))
7174 (defun org-files-list ()
7175 "Return `org-agenda-files' list, plus all open Org files.
7176 This is useful for operations that need to scan all of a user's
7177 open and agenda-wise Org files."
7178 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7179 (dolist (buf (buffer-list))
7180 (with-current-buffer buf
7181 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7182 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7183 files))
7185 (defsubst org-entry-beginning-position ()
7186 "Return the beginning position of the current entry."
7187 (save-excursion (org-back-to-heading t) (point)))
7189 (defsubst org-entry-end-position ()
7190 "Return the end position of the current entry."
7191 (save-excursion (outline-next-heading) (point)))
7193 (defun org-cycle-hide-drawers (state &optional exceptions)
7194 "Re-hide all drawers after a visibility state change.
7195 STATE should be one of the symbols listed in the docstring of
7196 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7197 a list of strings specifying which drawers should not be hidden."
7198 (when (and (derived-mode-p 'org-mode)
7199 (not (memq state '(overview folded contents))))
7200 (save-excursion
7201 (let* ((globalp (eq state 'all))
7202 (beg (if globalp (point-min) (point)))
7203 (end (if globalp (point-max)
7204 (if (eq state 'children)
7205 (save-excursion (outline-next-heading) (point))
7206 (org-end-of-subtree t)))))
7207 (goto-char beg)
7208 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7209 (unless (member-ignore-case (match-string 1) exceptions)
7210 (let ((drawer (org-element-at-point)))
7211 (when (memq (org-element-type drawer) '(drawer property-drawer))
7212 (org-flag-drawer t drawer)
7213 ;; Make sure to skip drawer entirely or we might flag
7214 ;; it another time when matching its ending line with
7215 ;; `org-drawer-regexp'.
7216 (goto-char (org-element-property :end drawer))))))))))
7218 (defun org-flag-drawer (flag &optional element)
7219 "When FLAG is non-nil, hide the drawer we are at.
7220 Otherwise make it visible. When optional argument ELEMENT is
7221 a parsed drawer, as returned by `org-element-at-point', hide or
7222 show that drawer instead."
7223 (let ((drawer (or element
7224 (and (save-excursion
7225 (beginning-of-line)
7226 (looking-at-p org-drawer-regexp))
7227 (org-element-at-point)))))
7228 (when (memq (org-element-type drawer) '(drawer property-drawer))
7229 (let ((post (org-element-property :post-affiliated drawer)))
7230 (save-excursion
7231 (outline-flag-region
7232 (progn (goto-char post) (line-end-position))
7233 (progn (goto-char (org-element-property :end drawer))
7234 (skip-chars-backward " \r\t\n")
7235 (line-end-position))
7236 flag))
7237 ;; When the drawer is hidden away, make sure point lies in
7238 ;; a visible part of the buffer.
7239 (when (and flag (> (line-beginning-position) post))
7240 (goto-char post))))))
7242 (defun org-subtree-end-visible-p ()
7243 "Is the end of the current subtree visible?"
7244 (pos-visible-in-window-p
7245 (save-excursion (org-end-of-subtree t) (point))))
7247 (defun org-first-headline-recenter ()
7248 "Move cursor to the first headline and recenter the headline."
7249 (let ((window (get-buffer-window)))
7250 (when window
7251 (goto-char (point-min))
7252 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7253 (set-window-start window (line-beginning-position))))))
7255 ;;; Saving and restoring visibility
7257 (defun org-outline-overlay-data (&optional use-markers)
7258 "Return a list of the locations of all outline overlays.
7259 These are overlays with the `invisible' property value `outline'.
7260 The return value is a list of cons cells, with start and stop
7261 positions for each overlay.
7262 If USE-MARKERS is set, return the positions as markers."
7263 (let (beg end)
7264 (org-with-wide-buffer
7265 (delq nil
7266 (mapcar (lambda (o)
7267 (when (eq (overlay-get o 'invisible) 'outline)
7268 (setq beg (overlay-start o)
7269 end (overlay-end o))
7270 (and beg end (> end beg)
7271 (if use-markers
7272 (cons (copy-marker beg)
7273 (copy-marker end t))
7274 (cons beg end)))))
7275 (overlays-in (point-min) (point-max)))))))
7277 (defun org-set-outline-overlay-data (data)
7278 "Create visibility overlays for all positions in DATA.
7279 DATA should have been made by `org-outline-overlay-data'."
7280 (org-with-wide-buffer
7281 (outline-show-all)
7282 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7284 ;;; Folding of blocks
7286 (defvar-local org-hide-block-overlays nil
7287 "Overlays hiding blocks.")
7289 (defun org-block-map (function &optional start end)
7290 "Call FUNCTION at the head of all source blocks in the current buffer.
7291 Optional arguments START and END can be used to limit the range."
7292 (let ((start (or start (point-min)))
7293 (end (or end (point-max))))
7294 (save-excursion
7295 (goto-char start)
7296 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7297 (save-excursion
7298 (save-match-data
7299 (goto-char (match-beginning 0))
7300 (funcall function)))))))
7302 (defun org-hide-block-toggle-all ()
7303 "Toggle the visibility of all blocks in the current buffer."
7304 (org-block-map 'org-hide-block-toggle))
7306 (defun org-hide-block-all ()
7307 "Fold all blocks in the current buffer."
7308 (interactive)
7309 (org-show-block-all)
7310 (org-block-map 'org-hide-block-toggle-maybe))
7312 (defun org-show-block-all ()
7313 "Unfold all blocks in the current buffer."
7314 (interactive)
7315 (mapc #'delete-overlay org-hide-block-overlays)
7316 (setq org-hide-block-overlays nil))
7318 (defun org-hide-block-toggle-maybe ()
7319 "Toggle visibility of block at point.
7320 Unlike to `org-hide-block-toggle', this function does not throw
7321 an error. Return a non-nil value when toggling is successful."
7322 (interactive)
7323 (ignore-errors (org-hide-block-toggle)))
7325 (defun org-hide-block-toggle (&optional force)
7326 "Toggle the visibility of the current block.
7327 When optional argument FORCE is `off', make block visible. If it
7328 is non-nil, hide it unconditionally. Throw an error when not at
7329 a block. Return a non-nil value when toggling is successful."
7330 (interactive)
7331 (let ((element (org-element-at-point)))
7332 (unless (memq (org-element-type element)
7333 '(center-block comment-block dynamic-block example-block
7334 export-block quote-block special-block
7335 src-block verse-block))
7336 (user-error "Not at a block"))
7337 (let* ((start (save-excursion
7338 (goto-char (org-element-property :post-affiliated element))
7339 (line-end-position)))
7340 (end (save-excursion
7341 (goto-char (org-element-property :end element))
7342 (skip-chars-backward " \r\t\n")
7343 (line-end-position)))
7344 (overlays (overlays-at start)))
7345 (cond
7346 ;; Do nothing when not before or at the block opening line or
7347 ;; at the block closing line.
7348 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7349 ((and (not (eq force 'off))
7350 (not (memq t (mapcar
7351 (lambda (o)
7352 (eq (overlay-get o 'invisible) 'org-hide-block))
7353 overlays))))
7354 (let ((ov (make-overlay start end)))
7355 (overlay-put ov 'invisible 'org-hide-block)
7356 ;; Make the block accessible to `isearch'.
7357 (overlay-put
7358 ov 'isearch-open-invisible
7359 (lambda (ov)
7360 (when (memq ov org-hide-block-overlays)
7361 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7362 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7363 (delete-overlay ov))))
7364 (push ov org-hide-block-overlays)
7365 ;; When the block is hidden away, make sure point is left in
7366 ;; a visible part of the buffer.
7367 (when (> (line-beginning-position) start)
7368 (goto-char start)
7369 (beginning-of-line))
7370 ;; Signal successful toggling.
7372 ((or (not force) (eq force 'off))
7373 (dolist (ov overlays t)
7374 (when (memq ov org-hide-block-overlays)
7375 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7376 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7377 (delete-overlay ov))))))))
7379 ;; Remove overlays when changing major mode
7380 (add-hook 'org-mode-hook
7381 (lambda () (add-hook 'change-major-mode-hook
7382 'org-show-block-all 'append 'local)))
7384 ;;; Org-goto
7386 (defvar org-goto-window-configuration nil)
7387 (defvar org-goto-marker nil)
7388 (defvar org-goto-map)
7389 (defun org-goto-map ()
7390 "Set the keymap `org-goto'."
7391 (setq org-goto-map
7392 (let ((map (make-sparse-keymap)))
7393 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7394 mouse-drag-region universal-argument org-occur)))
7395 (dolist (cmd cmds)
7396 (substitute-key-definition cmd cmd map global-map)))
7397 (suppress-keymap map)
7398 (org-defkey map "\C-m" 'org-goto-ret)
7399 (org-defkey map [(return)] 'org-goto-ret)
7400 (org-defkey map [(left)] 'org-goto-left)
7401 (org-defkey map [(right)] 'org-goto-right)
7402 (org-defkey map [(control ?g)] 'org-goto-quit)
7403 (org-defkey map "\C-i" 'org-cycle)
7404 (org-defkey map [(tab)] 'org-cycle)
7405 (org-defkey map [(down)] 'outline-next-visible-heading)
7406 (org-defkey map [(up)] 'outline-previous-visible-heading)
7407 (if org-goto-auto-isearch
7408 (if (fboundp 'define-key-after)
7409 (define-key-after map [t] 'org-goto-local-auto-isearch)
7410 nil)
7411 (org-defkey map "q" 'org-goto-quit)
7412 (org-defkey map "n" 'outline-next-visible-heading)
7413 (org-defkey map "p" 'outline-previous-visible-heading)
7414 (org-defkey map "f" 'outline-forward-same-level)
7415 (org-defkey map "b" 'outline-backward-same-level)
7416 (org-defkey map "u" 'outline-up-heading))
7417 (org-defkey map "/" 'org-occur)
7418 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7419 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7420 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7421 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7422 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7423 map)))
7425 (defconst org-goto-help
7426 "Browse buffer copy, to find location or copy text.%s
7427 RET=jump to location C-g=quit and return to previous location
7428 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7430 (defvar org-goto-start-pos) ; dynamically scoped parameter
7432 (defun org-goto (&optional alternative-interface)
7433 "Look up a different location in the current file, keeping current visibility.
7435 When you want look-up or go to a different location in a
7436 document, the fastest way is often to fold the entire buffer and
7437 then dive into the tree. This method has the disadvantage, that
7438 the previous location will be folded, which may not be what you
7439 want.
7441 This command works around this by showing a copy of the current
7442 buffer in an indirect buffer, in overview mode. You can dive
7443 into the tree in that copy, use org-occur and incremental search
7444 to find a location. When pressing RET or `Q', the command
7445 returns to the original buffer in which the visibility is still
7446 unchanged. After RET it will also jump to the location selected
7447 in the indirect buffer and expose the headline hierarchy above.
7449 With a prefix argument, use the alternative interface: e.g., if
7450 `org-goto-interface' is `outline' use `outline-path-completion'."
7451 (interactive "P")
7452 (org-goto-map)
7453 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7454 (org-refile-use-outline-path t)
7455 (org-refile-target-verify-function nil)
7456 (interface
7457 (if (not alternative-interface)
7458 org-goto-interface
7459 (if (eq org-goto-interface 'outline)
7460 'outline-path-completion
7461 'outline)))
7462 (org-goto-start-pos (point))
7463 (selected-point
7464 (if (eq interface 'outline)
7465 (car (org-get-location (current-buffer) org-goto-help))
7466 (let ((pa (org-refile-get-location "Goto")))
7467 (org-refile-check-position pa)
7468 (nth 3 pa)))))
7469 (if selected-point
7470 (progn
7471 (org-mark-ring-push org-goto-start-pos)
7472 (goto-char selected-point)
7473 (when (or (org-invisible-p) (org-invisible-p2))
7474 (org-show-context 'org-goto)))
7475 (message "Quit"))))
7477 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7478 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7479 (defvar org-goto-local-auto-isearch-map) ; defined below
7481 (defun org-get-location (_buf help)
7482 "Let the user select a location in current buffer.
7483 This function uses a recursive edit. It returns the selected position
7484 or nil."
7485 (org-no-popups
7486 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7487 (isearch-hide-immediately nil)
7488 (isearch-search-fun-function
7489 (lambda () 'org-goto-local-search-headings))
7490 (org-goto-selected-point org-goto-exit-command))
7491 (save-excursion
7492 (save-window-excursion
7493 (delete-other-windows)
7494 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7495 (pop-to-buffer-same-window
7496 (condition-case nil
7497 (make-indirect-buffer (current-buffer) "*org-goto*")
7498 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7499 (with-output-to-temp-buffer "*Org Help*"
7500 (princ (format help (if org-goto-auto-isearch
7501 " Just type for auto-isearch."
7502 " n/p/f/b/u to navigate, q to quit."))))
7503 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7504 (setq buffer-read-only nil)
7505 (let ((org-startup-truncated t)
7506 (org-startup-folded nil)
7507 (org-startup-align-all-tables nil))
7508 (org-mode)
7509 (org-overview))
7510 (setq buffer-read-only t)
7511 (if (and (boundp 'org-goto-start-pos)
7512 (integer-or-marker-p org-goto-start-pos))
7513 (progn (goto-char org-goto-start-pos)
7514 (when (org-invisible-p)
7515 (org-show-set-visibility 'lineage)))
7516 (goto-char (point-min)))
7517 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7518 (message "Select location and press RET")
7519 (use-local-map org-goto-map)
7520 (recursive-edit)))
7521 (kill-buffer "*org-goto*")
7522 (cons org-goto-selected-point org-goto-exit-command))))
7524 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7525 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7526 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7527 (if (fboundp 'isearch-other-control-char)
7528 (progn
7529 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7530 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7531 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7532 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7533 (define-key org-goto-local-auto-isearch-map [return] nil))
7535 (defun org-goto-local-search-headings (string bound noerror)
7536 "Search and make sure that any matches are in headlines."
7537 (catch 'return
7538 (while (if isearch-forward
7539 (search-forward string bound noerror)
7540 (search-backward string bound noerror))
7541 (when (save-match-data
7542 (and (save-excursion
7543 (beginning-of-line)
7544 (looking-at org-complex-heading-regexp))
7545 (or (not (match-beginning 5))
7546 (< (point) (match-beginning 5)))))
7547 (throw 'return (point))))))
7549 (defun org-goto-local-auto-isearch ()
7550 "Start isearch."
7551 (interactive)
7552 (goto-char (point-min))
7553 (let ((keys (this-command-keys)))
7554 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7555 (isearch-mode t)
7556 (isearch-process-search-char (string-to-char keys)))))
7558 (defun org-goto-ret (&optional _arg)
7559 "Finish `org-goto' by going to the new location."
7560 (interactive "P")
7561 (setq org-goto-selected-point (point))
7562 (setq org-goto-exit-command 'return)
7563 (throw 'exit nil))
7565 (defun org-goto-left ()
7566 "Finish `org-goto' by going to the new location."
7567 (interactive)
7568 (if (org-at-heading-p)
7569 (progn
7570 (beginning-of-line 1)
7571 (setq org-goto-selected-point (point)
7572 org-goto-exit-command 'left)
7573 (throw 'exit nil))
7574 (user-error "Not on a heading")))
7576 (defun org-goto-right ()
7577 "Finish `org-goto' by going to the new location."
7578 (interactive)
7579 (if (org-at-heading-p)
7580 (progn
7581 (setq org-goto-selected-point (point)
7582 org-goto-exit-command 'right)
7583 (throw 'exit nil))
7584 (user-error "Not on a heading")))
7586 (defun org-goto-quit ()
7587 "Finish `org-goto' without cursor motion."
7588 (interactive)
7589 (setq org-goto-selected-point nil)
7590 (setq org-goto-exit-command 'quit)
7591 (throw 'exit nil))
7593 ;;; Indirect buffer display of subtrees
7595 (defvar org-indirect-dedicated-frame nil
7596 "This is the frame being used for indirect tree display.")
7597 (defvar org-last-indirect-buffer nil)
7599 (defun org-tree-to-indirect-buffer (&optional arg)
7600 "Create indirect buffer and narrow it to current subtree.
7602 With a numerical prefix ARG, go up to this level and then take that tree.
7603 If ARG is negative, go up that many levels.
7605 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7606 indirect buffer previously made with this command, to avoid proliferation of
7607 indirect buffers. However, when you call the command with a \
7608 `\\[universal-argument]' prefix, or
7609 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7610 so that you can work with several indirect buffers at the same time. If
7611 `org-indirect-buffer-display' is `dedicated-frame', the \
7612 `\\[universal-argument]' prefix also
7613 requests that a new frame be made for the new buffer, so that the dedicated
7614 frame is not changed."
7615 (interactive "P")
7616 (let ((cbuf (current-buffer))
7617 (cwin (selected-window))
7618 (pos (point))
7619 beg end level heading ibuf)
7620 (save-excursion
7621 (org-back-to-heading t)
7622 (when (numberp arg)
7623 (setq level (org-outline-level))
7624 (when (< arg 0) (setq arg (+ level arg)))
7625 (while (> (setq level (org-outline-level)) arg)
7626 (org-up-heading-safe)))
7627 (setq beg (point)
7628 heading (org-get-heading 'no-tags))
7629 (org-end-of-subtree t t)
7630 (when (org-at-heading-p) (backward-char 1))
7631 (setq end (point)))
7632 (when (and (buffer-live-p org-last-indirect-buffer)
7633 (not (eq org-indirect-buffer-display 'new-frame))
7634 (not arg))
7635 (kill-buffer org-last-indirect-buffer))
7636 (setq ibuf (org-get-indirect-buffer cbuf heading)
7637 org-last-indirect-buffer ibuf)
7638 (cond
7639 ((or (eq org-indirect-buffer-display 'new-frame)
7640 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7641 (select-frame (make-frame))
7642 (delete-other-windows)
7643 (pop-to-buffer-same-window ibuf)
7644 (org-set-frame-title heading))
7645 ((eq org-indirect-buffer-display 'dedicated-frame)
7646 (raise-frame
7647 (select-frame (or (and org-indirect-dedicated-frame
7648 (frame-live-p org-indirect-dedicated-frame)
7649 org-indirect-dedicated-frame)
7650 (setq org-indirect-dedicated-frame (make-frame)))))
7651 (delete-other-windows)
7652 (pop-to-buffer-same-window ibuf)
7653 (org-set-frame-title (concat "Indirect: " heading)))
7654 ((eq org-indirect-buffer-display 'current-window)
7655 (pop-to-buffer-same-window ibuf))
7656 ((eq org-indirect-buffer-display 'other-window)
7657 (pop-to-buffer ibuf))
7658 (t (error "Invalid value")))
7659 (narrow-to-region beg end)
7660 (outline-show-all)
7661 (goto-char pos)
7662 (run-hook-with-args 'org-cycle-hook 'all)
7663 (and (window-live-p cwin) (select-window cwin))))
7665 (defun org-get-indirect-buffer (&optional buffer heading)
7666 (setq buffer (or buffer (current-buffer)))
7667 (let ((n 1) (base (buffer-name buffer)) bname)
7668 (while (buffer-live-p
7669 (get-buffer
7670 (setq bname
7671 (concat base "-"
7672 (if heading (concat heading "-" (number-to-string n))
7673 (number-to-string n))))))
7674 (setq n (1+ n)))
7675 (condition-case nil
7676 (make-indirect-buffer buffer bname 'clone)
7677 (error (make-indirect-buffer buffer bname)))))
7679 (defun org-set-frame-title (title)
7680 "Set the title of the current frame to the string TITLE."
7681 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7683 ;;;; Structure editing
7685 ;;; Inserting headlines
7687 (defun org--line-empty-p (n)
7688 "Is the Nth next line empty?
7690 Counts the current line as N = 1 and the previous line as N = 0;
7691 see `beginning-of-line'."
7692 (save-excursion
7693 (and (not (bobp))
7694 (or (beginning-of-line n) t)
7695 (save-match-data
7696 (looking-at "[ \t]*$")))))
7698 (defun org-previous-line-empty-p ()
7699 "Is the previous line a blank line?
7700 When NEXT is non-nil, check the next line instead."
7701 (org--line-empty-p 0))
7703 (defun org-next-line-empty-p ()
7704 "Is the previous line a blank line?
7705 When NEXT is non-nil, check the next line instead."
7706 (org--line-empty-p 2))
7708 (defun org--blank-before-heading-p (&optional parent)
7709 "Non-nil when an empty line should precede a new heading here.
7710 When optional argument PARENT is non-nil, consider parent
7711 headline instead of current one."
7712 (pcase (assq 'heading org-blank-before-new-entry)
7713 (`(heading . auto)
7714 (save-excursion
7715 (org-with-limited-levels
7716 (unless (and (org-before-first-heading-p)
7717 (not (outline-next-heading)))
7718 (org-back-to-heading t)
7719 (when parent (org-up-heading-safe))
7720 (cond ((not (bobp))
7721 (org-previous-line-empty-p))
7722 ((outline-next-heading)
7723 (org-previous-line-empty-p))
7724 ;; Ignore trailing spaces on last buffer line.
7725 ((progn (skip-chars-backward " \t") (bolp))
7726 (org-previous-line-empty-p))
7727 (t nil))))))
7728 (`(heading . ,value) value)
7729 (_ nil)))
7731 (defun org-insert-heading (&optional arg invisible-ok top)
7732 "Insert a new heading or an item with the same depth at point.
7734 If point is at the beginning of a heading, insert a new heading
7735 or a new headline above the current one. When at the beginning
7736 of a regular line of text, turn it into a heading.
7738 If point is in the middle of a line, split it and create a new
7739 headline with the text in the current line after point (see
7740 `org-M-RET-may-split-line' on how to modify this behavior). As
7741 a special case, on a headline, splitting can only happen on the
7742 title itself. E.g., this excludes breaking stars or tags.
7744 With a `\\[universal-argument]' prefix, set \
7745 `org-insert-heading-respect-content' to
7746 a non-nil value for the duration of the command. This forces the
7747 insertion of a heading after the current subtree, independently
7748 on the location of point.
7750 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7751 insert the heading at the end of the tree
7752 above the current heading. For example, if point is within a
7753 2nd-level heading, then it will insert a 2nd-level heading at
7754 the end of the 1st-level parent subtree.
7756 When INVISIBLE-OK is set, stop at invisible headlines when going
7757 back. This is important for non-interactive uses of the
7758 command.
7760 When optional argument TOP is non-nil, insert a level 1 heading,
7761 unconditionally."
7762 (interactive "P")
7763 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7764 (level (org-current-level))
7765 (stars (make-string (if (and level (not top)) level 1) ?*)))
7766 (cond
7767 ((or org-insert-heading-respect-content
7768 (member arg '((4) (16)))
7769 (and (not invisible-ok)
7770 (invisible-p (max (1- (point)) (point-min)))))
7771 ;; Position point at the location of insertion.
7772 (if (not level) ;before first headline
7773 (org-with-limited-levels (outline-next-heading))
7774 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7775 ;; is nil.
7776 (org-with-limited-levels (org-back-to-heading invisible-ok))
7777 (cond ((equal arg '(16))
7778 (org-up-heading-safe)
7779 (org-end-of-subtree t t))
7781 (org-end-of-subtree t t))))
7782 (unless (bolp) (insert "\n")) ;ensure final newline
7783 (unless (and blank? (org-previous-line-empty-p))
7784 (org-N-empty-lines-before-current (if blank? 1 0)))
7785 (insert stars " \n")
7786 (forward-char -1))
7787 ;; At a headline...
7788 ((org-at-heading-p)
7789 (cond ((bolp)
7790 (when blank? (save-excursion (insert "\n")))
7791 (save-excursion (insert stars " \n"))
7792 (unless (and blank? (org-previous-line-empty-p))
7793 (org-N-empty-lines-before-current (if blank? 1 0)))
7794 (end-of-line))
7795 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7796 (org-match-line org-complex-heading-regexp)
7797 (org-pos-in-match-range (point) 4))
7798 ;; Grab the text that should moved to the new headline.
7799 ;; Preserve tags.
7800 (let ((split (delete-and-extract-region (point) (match-end 4))))
7801 (if (looking-at "[ \t]*$") (replace-match "")
7802 (org-set-tags nil t))
7803 (end-of-line)
7804 (when blank? (insert "\n"))
7805 (insert "\n" stars " ")
7806 (when (org-string-nw-p split) (insert split))
7807 (when (eobp) (save-excursion (insert "\n")))))
7809 (end-of-line)
7810 (when blank? (insert "\n"))
7811 (insert "\n" stars " ")
7812 (when (eobp) (save-excursion (insert "\n"))))))
7813 ;; On regular text, turn line into a headline or split, if
7814 ;; appropriate.
7815 ((bolp)
7816 (insert stars " ")
7817 (unless (and blank? (org-previous-line-empty-p))
7818 (org-N-empty-lines-before-current (if blank? 1 0))))
7820 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7821 (end-of-line))
7822 (insert "\n" stars " ")
7823 (unless (and blank? (org-previous-line-empty-p))
7824 (org-N-empty-lines-before-current (if blank? 1 0))))))
7825 (run-hooks 'org-insert-heading-hook))
7827 (defun org-N-empty-lines-before-current (n)
7828 "Make the number of empty lines before current exactly N.
7829 So this will delete or add empty lines."
7830 (let ((column (current-column)))
7831 (beginning-of-line)
7832 (unless (bobp)
7833 (let ((start (save-excursion
7834 (skip-chars-backward " \r\t\n")
7835 (line-end-position))))
7836 (delete-region start (line-end-position 0))))
7837 (insert (make-string n ?\n))
7838 (move-to-column column)))
7840 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7841 "Return the heading of the current entry, without the stars.
7842 When NO-TAGS is non-nil, don't include tags.
7843 When NO-TODO is non-nil, don't include TODO keywords.
7844 When NO-PRIORITY is non-nil, don't include priority cookie.
7845 When NO-COMMENT is non-nil, don't include COMMENT string."
7846 (save-excursion
7847 (org-back-to-heading t)
7848 (let ((case-fold-search nil))
7849 (looking-at org-complex-heading-regexp)
7850 (let ((todo (and (not no-todo) (match-string 2)))
7851 (priority (and (not no-priority) (match-string 3)))
7852 (headline (pcase (match-string 4)
7853 (`nil "")
7854 ((and (guard no-comment) h)
7855 (replace-regexp-in-string
7856 (eval-when-compile
7857 (format "\\`%s[ \t]+" org-comment-string))
7858 "" h))
7859 (h h)))
7860 (tags (and (not no-tags) (match-string 5))))
7861 (mapconcat #'identity
7862 (delq nil (list todo priority headline tags))
7863 " ")))))
7865 (defvar orgstruct-mode) ; defined below
7867 (defun org-heading-components ()
7868 "Return the components of the current heading.
7869 This is a list with the following elements:
7870 - the level as an integer
7871 - the reduced level, different if `org-odd-levels-only' is set.
7872 - the TODO keyword, or nil
7873 - the priority character, like ?A, or nil if no priority is given
7874 - the headline text itself, or the tags string if no headline text
7875 - the tags string, or nil."
7876 (save-excursion
7877 (org-back-to-heading t)
7878 (when (let (case-fold-search)
7879 (looking-at
7880 (if orgstruct-mode
7881 org-heading-regexp
7882 org-complex-heading-regexp)))
7883 (if orgstruct-mode
7884 (list (length (match-string 1))
7885 (org-reduced-level (length (match-string 1)))
7888 (match-string 2)
7889 nil)
7890 (list (length (match-string 1))
7891 (org-reduced-level (length (match-string 1)))
7892 (match-string-no-properties 2)
7893 (and (match-end 3) (aref (match-string 3) 2))
7894 (match-string-no-properties 4)
7895 (match-string-no-properties 5))))))
7897 (defun org-get-entry ()
7898 "Get the entry text, after heading, entire subtree."
7899 (save-excursion
7900 (org-back-to-heading t)
7901 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7903 (defun org-edit-headline (&optional heading)
7904 "Edit the current headline.
7905 Set it to HEADING when provided."
7906 (interactive)
7907 (org-with-wide-buffer
7908 (org-back-to-heading t)
7909 (let ((case-fold-search nil))
7910 (when (looking-at org-complex-heading-regexp)
7911 (let* ((old (match-string-no-properties 4))
7912 (new (save-match-data
7913 (org-trim (or heading (read-string "Edit: " old))))))
7914 (unless (equal old new)
7915 (if old (replace-match new t t nil 4)
7916 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7917 (insert " " new))
7918 (org-set-tags nil t)
7919 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7921 (defun org-insert-heading-after-current ()
7922 "Insert a new heading with same level as current, after current subtree."
7923 (interactive)
7924 (org-back-to-heading)
7925 (org-insert-heading)
7926 (org-move-subtree-down)
7927 (end-of-line 1))
7929 (defun org-insert-heading-respect-content (&optional invisible-ok)
7930 "Insert heading with `org-insert-heading-respect-content' set to t."
7931 (interactive)
7932 (org-insert-heading '(4) invisible-ok))
7934 (defun org-insert-todo-heading-respect-content (&optional force-state)
7935 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7936 (interactive)
7937 (org-insert-todo-heading force-state '(4)))
7939 (defun org-insert-todo-heading (arg &optional force-heading)
7940 "Insert a new heading with the same level and TODO state as current heading.
7942 If the heading has no TODO state, or if the state is DONE, use
7943 the first state (TODO by default). Also with one prefix arg,
7944 force first state. With two prefix args, force inserting at the
7945 end of the parent subtree.
7947 When called at a plain list item, insert a new item with an
7948 unchecked check box."
7949 (interactive "P")
7950 (when (or force-heading (not (org-insert-item 'checkbox)))
7951 (org-insert-heading (or (and (equal arg '(16)) '(16))
7952 force-heading))
7953 (save-excursion
7954 (org-back-to-heading)
7955 (outline-previous-heading)
7956 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7957 (let* ((new-mark-x
7958 (if (or (equal arg '(4))
7959 (not (match-beginning 2))
7960 (member (match-string 2) org-done-keywords))
7961 (car org-todo-keywords-1)
7962 (match-string 2)))
7963 (new-mark
7965 (run-hook-with-args-until-success
7966 'org-todo-get-default-hook new-mark-x nil)
7967 new-mark-x)))
7968 (beginning-of-line 1)
7969 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7970 (if org-treat-insert-todo-heading-as-state-change
7971 (org-todo new-mark)
7972 (insert new-mark " "))))
7973 (when org-provide-todo-statistics
7974 (org-update-parent-todo-statistics))))
7976 (defun org-insert-subheading (arg)
7977 "Insert a new subheading and demote it.
7978 Works for outline headings and for plain lists alike."
7979 (interactive "P")
7980 (org-insert-heading arg)
7981 (cond
7982 ((org-at-heading-p) (org-do-demote))
7983 ((org-at-item-p) (org-indent-item))))
7985 (defun org-insert-todo-subheading (arg)
7986 "Insert a new subheading with TODO keyword or checkbox and demote it.
7987 Works for outline headings and for plain lists alike."
7988 (interactive "P")
7989 (org-insert-todo-heading arg)
7990 (cond
7991 ((org-at-heading-p) (org-do-demote))
7992 ((org-at-item-p) (org-indent-item))))
7994 ;;; Promotion and Demotion
7996 (defvar org-after-demote-entry-hook nil
7997 "Hook run after an entry has been demoted.
7998 The cursor will be at the beginning of the entry.
7999 When a subtree is being demoted, the hook will be called for each node.")
8001 (defvar org-after-promote-entry-hook nil
8002 "Hook run after an entry has been promoted.
8003 The cursor will be at the beginning of the entry.
8004 When a subtree is being promoted, the hook will be called for each node.")
8006 (defun org-promote-subtree ()
8007 "Promote the entire subtree.
8008 See also `org-promote'."
8009 (interactive)
8010 (save-excursion
8011 (org-with-limited-levels (org-map-tree 'org-promote)))
8012 (org-fix-position-after-promote))
8014 (defun org-demote-subtree ()
8015 "Demote the entire subtree.
8016 See `org-demote' and `org-promote'."
8017 (interactive)
8018 (save-excursion
8019 (org-with-limited-levels (org-map-tree 'org-demote)))
8020 (org-fix-position-after-promote))
8022 (defun org-do-promote ()
8023 "Promote the current heading higher up the tree.
8024 If the region is active in `transient-mark-mode', promote all
8025 headings in the region."
8026 (interactive)
8027 (save-excursion
8028 (if (org-region-active-p)
8029 (org-map-region 'org-promote (region-beginning) (region-end))
8030 (org-promote)))
8031 (org-fix-position-after-promote))
8033 (defun org-do-demote ()
8034 "Demote the current heading lower down the tree.
8035 If the region is active in `transient-mark-mode', demote all
8036 headings in the region."
8037 (interactive)
8038 (save-excursion
8039 (if (org-region-active-p)
8040 (org-map-region 'org-demote (region-beginning) (region-end))
8041 (org-demote)))
8042 (org-fix-position-after-promote))
8044 (defun org-fix-position-after-promote ()
8045 "Fix cursor position and indentation after demoting/promoting."
8046 (let ((pos (point)))
8047 (when (save-excursion
8048 (beginning-of-line)
8049 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8050 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8051 (cond ((eobp) (insert " "))
8052 ((eolp) (insert " "))
8053 ((equal (char-after) ?\s) (forward-char 1))))))
8055 (defun org-current-level ()
8056 "Return the level of the current entry, or nil if before the first headline.
8057 The level is the number of stars at the beginning of the
8058 headline. Use `org-reduced-level' to remove the effect of
8059 `org-odd-levels'. Unlike to `org-outline-level', this function
8060 ignores inlinetasks."
8061 (let ((level (org-with-limited-levels (org-outline-level))))
8062 (and (> level 0) level)))
8064 (defun org-get-previous-line-level ()
8065 "Return the outline depth of the last headline before the current line.
8066 Returns 0 for the first headline in the buffer, and nil if before the
8067 first headline."
8068 (and (org-current-level)
8069 (or (and (/= (line-beginning-position) (point-min))
8070 (save-excursion (beginning-of-line 0) (org-current-level)))
8071 0)))
8073 (defun org-reduced-level (l)
8074 "Compute the effective level of a heading.
8075 This takes into account the setting of `org-odd-levels-only'."
8076 (cond
8077 ((zerop l) 0)
8078 (org-odd-levels-only (1+ (floor (/ l 2))))
8079 (t l)))
8081 (defun org-level-increment ()
8082 "Return the number of stars that will be added or removed at a
8083 time to headlines when structure editing, based on the value of
8084 `org-odd-levels-only'."
8085 (if org-odd-levels-only 2 1))
8087 (defun org-get-valid-level (level &optional change)
8088 "Rectify a level change under the influence of `org-odd-levels-only'.
8089 LEVEL is a current level, CHANGE is by how much the level should
8090 be modified. Even if CHANGE is nil, LEVEL may be returned
8091 modified because even level numbers will become the next higher
8092 odd number. Returns values greater than 0."
8093 (if org-odd-levels-only
8094 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8095 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8096 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8097 (max 1 (+ level (or change 0)))))
8099 (defun org-promote ()
8100 "Promote the current heading higher up the tree."
8101 (org-with-wide-buffer
8102 (org-back-to-heading t)
8103 (let* ((after-change-functions (remq 'flyspell-after-change-function
8104 after-change-functions))
8105 (level (save-match-data (funcall outline-level)))
8106 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8107 (diff (abs (- level (length up-head) -1))))
8108 (cond
8109 ((and (= level 1) org-allow-promoting-top-level-subtree)
8110 (replace-match "# " nil t))
8111 ((= level 1)
8112 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8113 (t (replace-match up-head nil t)))
8114 (unless (= level 1)
8115 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8116 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8117 (run-hooks 'org-after-promote-entry-hook))))
8119 (defun org-demote ()
8120 "Demote the current heading lower down the tree."
8121 (org-with-wide-buffer
8122 (org-back-to-heading t)
8123 (let* ((after-change-functions (remq 'flyspell-after-change-function
8124 after-change-functions))
8125 (level (save-match-data (funcall outline-level)))
8126 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8127 (diff (abs (- level (length down-head) -1))))
8128 (replace-match down-head nil t)
8129 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8130 (when org-adapt-indentation (org-fixup-indentation diff))
8131 (run-hooks 'org-after-demote-entry-hook))))
8133 (defun org-cycle-level ()
8134 "Cycle the level of an empty headline through possible states.
8135 This goes first to child, then to parent, level, then up the hierarchy.
8136 After top level, it switches back to sibling level."
8137 (interactive)
8138 (let ((org-adapt-indentation nil))
8139 (when (org-point-at-end-of-empty-headline)
8140 (setq this-command 'org-cycle-level) ; Only needed for caching
8141 (let ((cur-level (org-current-level))
8142 (prev-level (org-get-previous-line-level)))
8143 (cond
8144 ;; If first headline in file, promote to top-level.
8145 ((= prev-level 0)
8146 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8147 do (org-do-promote)))
8148 ;; If same level as prev, demote one.
8149 ((= prev-level cur-level)
8150 (org-do-demote))
8151 ;; If parent is top-level, promote to top level if not already.
8152 ((= prev-level 1)
8153 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8154 do (org-do-promote)))
8155 ;; If top-level, return to prev-level.
8156 ((= cur-level 1)
8157 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8158 do (org-do-demote)))
8159 ;; If less than prev-level, promote one.
8160 ((< cur-level prev-level)
8161 (org-do-promote))
8162 ;; If deeper than prev-level, promote until higher than
8163 ;; prev-level.
8164 ((> cur-level prev-level)
8165 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8166 do (org-do-promote))))
8167 t))))
8169 (defun org-map-tree (fun)
8170 "Call FUN for every heading underneath the current one."
8171 (org-back-to-heading t)
8172 (let ((level (funcall outline-level)))
8173 (save-excursion
8174 (funcall fun)
8175 (while (and (progn
8176 (outline-next-heading)
8177 (> (funcall outline-level) level))
8178 (not (eobp)))
8179 (funcall fun)))))
8181 (defun org-map-region (fun beg end)
8182 "Call FUN for every heading between BEG and END."
8183 (let ((org-ignore-region t))
8184 (save-excursion
8185 (setq end (copy-marker end))
8186 (goto-char beg)
8187 (when (and (re-search-forward org-outline-regexp-bol nil t)
8188 (< (point) end))
8189 (funcall fun))
8190 (while (and (progn
8191 (outline-next-heading)
8192 (< (point) end))
8193 (not (eobp)))
8194 (funcall fun)))))
8196 (defun org-fixup-indentation (diff)
8197 "Change the indentation in the current entry by DIFF.
8199 DIFF is an integer. Indentation is done according to the
8200 following rules:
8202 - Planning information and property drawers are always indented
8203 according to the new level of the headline;
8205 - Footnote definitions and their contents are ignored;
8207 - Inlinetasks' boundaries are not shifted;
8209 - Empty lines are ignored;
8211 - Other lines' indentation are shifted by DIFF columns, unless
8212 it would introduce a structural change in the document, in
8213 which case no shifting is done at all.
8215 Assume point is at a heading or an inlinetask beginning."
8216 (org-with-wide-buffer
8217 (narrow-to-region (line-beginning-position)
8218 (save-excursion
8219 (if (org-with-limited-levels (org-at-heading-p))
8220 (org-with-limited-levels (outline-next-heading))
8221 (org-inlinetask-goto-end))
8222 (point)))
8223 (forward-line)
8224 ;; Indent properly planning info and property drawer.
8225 (when (looking-at-p org-planning-line-re)
8226 (org-indent-line)
8227 (forward-line))
8228 (when (looking-at org-property-drawer-re)
8229 (goto-char (match-end 0))
8230 (forward-line)
8231 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8232 (catch 'no-shift
8233 (when (zerop diff) (throw 'no-shift nil))
8234 ;; If DIFF is negative, first check if a shift is possible at all
8235 ;; (e.g., it doesn't break structure). This can only happen if
8236 ;; some contents are not properly indented.
8237 (let ((case-fold-search t))
8238 (when (< diff 0)
8239 (let ((diff (- diff))
8240 (forbidden-re (concat org-outline-regexp
8241 "\\|"
8242 (substring org-footnote-definition-re 1))))
8243 (save-excursion
8244 (while (not (eobp))
8245 (cond
8246 ((looking-at-p "[ \t]*$") (forward-line))
8247 ((and (looking-at-p org-footnote-definition-re)
8248 (let ((e (org-element-at-point)))
8249 (and (eq (org-element-type e) 'footnote-definition)
8250 (goto-char (org-element-property :end e))))))
8251 ((looking-at-p org-outline-regexp) (forward-line))
8252 ;; Give up if shifting would move before column 0 or
8253 ;; if it would introduce a headline or a footnote
8254 ;; definition.
8256 (skip-chars-forward " \t")
8257 (let ((ind (current-column)))
8258 (when (or (< ind diff)
8259 (and (= ind diff) (looking-at-p forbidden-re)))
8260 (throw 'no-shift nil)))
8261 ;; Ignore contents of example blocks and source
8262 ;; blocks if their indentation is meant to be
8263 ;; preserved. Jump to block's closing line.
8264 (beginning-of-line)
8265 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8266 (let ((e (org-element-at-point)))
8267 (and (memq (org-element-type e)
8268 '(example-block src-block))
8269 (or org-src-preserve-indentation
8270 (org-element-property :preserve-indent e))
8271 (goto-char (org-element-property :end e))
8272 (progn (skip-chars-backward " \r\t\n")
8273 (beginning-of-line)
8274 t))))
8275 (forward-line))))))))
8276 ;; Shift lines but footnote definitions, inlinetasks boundaries
8277 ;; by DIFF. Also skip contents of source or example blocks
8278 ;; when indentation is meant to be preserved.
8279 (while (not (eobp))
8280 (cond
8281 ((and (looking-at-p org-footnote-definition-re)
8282 (let ((e (org-element-at-point)))
8283 (and (eq (org-element-type e) 'footnote-definition)
8284 (goto-char (org-element-property :end e))))))
8285 ((looking-at-p org-outline-regexp) (forward-line))
8286 ((looking-at-p "[ \t]*$") (forward-line))
8288 (indent-line-to (+ (org-get-indentation) diff))
8289 (beginning-of-line)
8290 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8291 (let ((e (org-element-at-point)))
8292 (and (memq (org-element-type e)
8293 '(example-block src-block))
8294 (or org-src-preserve-indentation
8295 (org-element-property :preserve-indent e))
8296 (goto-char (org-element-property :end e))
8297 (progn (skip-chars-backward " \r\t\n")
8298 (beginning-of-line)
8299 t))))
8300 (forward-line)))))))))
8302 (defun org-convert-to-odd-levels ()
8303 "Convert an Org file with all levels allowed to one with odd levels.
8304 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8305 level 5 etc."
8306 (interactive)
8307 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8308 (let ((outline-level 'org-outline-level)
8309 (org-odd-levels-only nil) n)
8310 (save-excursion
8311 (goto-char (point-min))
8312 (while (re-search-forward "^\\*\\*+ " nil t)
8313 (setq n (- (length (match-string 0)) 2))
8314 (while (>= (setq n (1- n)) 0)
8315 (org-demote))
8316 (end-of-line 1))))))
8318 (defun org-convert-to-oddeven-levels ()
8319 "Convert an Org file with only odd levels to one with odd/even levels.
8320 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8321 file contains a section with an even level, conversion would
8322 destroy the structure of the file. An error is signaled in this
8323 case."
8324 (interactive)
8325 (goto-char (point-min))
8326 ;; First check if there are no even levels
8327 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8328 (org-show-set-visibility 'canonical)
8329 (error "Not all levels are odd in this file. Conversion not possible"))
8330 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8331 (let ((outline-regexp org-outline-regexp)
8332 (outline-level 'org-outline-level)
8333 (org-odd-levels-only nil) n)
8334 (save-excursion
8335 (goto-char (point-min))
8336 (while (re-search-forward "^\\*\\*+ " nil t)
8337 (setq n (/ (1- (length (match-string 0))) 2))
8338 (while (>= (setq n (1- n)) 0)
8339 (org-promote))
8340 (end-of-line 1))))))
8342 (defun org-tr-level (n)
8343 "Make N odd if required."
8344 (if org-odd-levels-only (1+ (/ n 2)) n))
8346 ;;; Vertical tree motion, cutting and pasting of subtrees
8348 (defun org-move-subtree-up (&optional arg)
8349 "Move the current subtree up past ARG headlines of the same level."
8350 (interactive "p")
8351 (org-move-subtree-down (- (prefix-numeric-value arg))))
8353 (defun org-move-subtree-down (&optional arg)
8354 "Move the current subtree down past ARG headlines of the same level."
8355 (interactive "p")
8356 (setq arg (prefix-numeric-value arg))
8357 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8358 'org-get-last-sibling))
8359 (ins-point (make-marker))
8360 (cnt (abs arg))
8361 (col (current-column))
8362 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8363 ;; Select the tree
8364 (org-back-to-heading)
8365 (setq beg0 (point))
8366 (save-excursion
8367 (setq ne-beg (org-back-over-empty-lines))
8368 (setq beg (point)))
8369 (save-match-data
8370 (save-excursion (outline-end-of-heading)
8371 (setq folded (org-invisible-p)))
8372 (progn (org-end-of-subtree nil t)
8373 (unless (eobp) (backward-char))))
8374 (outline-next-heading)
8375 (setq ne-end (org-back-over-empty-lines))
8376 (setq end (point))
8377 (goto-char beg0)
8378 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8379 ;; include less whitespace
8380 (save-excursion
8381 (goto-char beg)
8382 (forward-line (- ne-beg ne-end))
8383 (setq beg (point))))
8384 ;; Find insertion point, with error handling
8385 (while (> cnt 0)
8386 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8387 (progn (goto-char beg0)
8388 (user-error "Cannot move past superior level or buffer limit")))
8389 (setq cnt (1- cnt)))
8390 (when (> arg 0)
8391 ;; Moving forward - still need to move over subtree
8392 (org-end-of-subtree t t)
8393 (save-excursion
8394 (org-back-over-empty-lines)
8395 (or (bolp) (newline))))
8396 (setq ne-ins (org-back-over-empty-lines))
8397 (move-marker ins-point (point))
8398 (setq txt (buffer-substring beg end))
8399 (org-save-markers-in-region beg end)
8400 (delete-region beg end)
8401 (org-remove-empty-overlays-at beg)
8402 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8403 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8404 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8405 (let ((bbb (point)))
8406 (insert-before-markers txt)
8407 (org-reinstall-markers-in-region bbb)
8408 (move-marker ins-point bbb))
8409 (or (bolp) (insert "\n"))
8410 (setq ins-end (point))
8411 (goto-char ins-point)
8412 (org-skip-whitespace)
8413 (when (and (< arg 0)
8414 (org-first-sibling-p)
8415 (> ne-ins ne-beg))
8416 ;; Move whitespace back to beginning
8417 (save-excursion
8418 (goto-char ins-end)
8419 (let ((kill-whole-line t))
8420 (kill-line (- ne-ins ne-beg)) (point)))
8421 (insert (make-string (- ne-ins ne-beg) ?\n)))
8422 (move-marker ins-point nil)
8423 (if folded
8424 (outline-hide-subtree)
8425 (org-show-entry)
8426 (org-show-children)
8427 (org-cycle-hide-drawers 'children))
8428 (org-clean-visibility-after-subtree-move)
8429 ;; move back to the initial column we were at
8430 (move-to-column col)))
8432 (defvar org-subtree-clip ""
8433 "Clipboard for cut and paste of subtrees.
8434 This is actually only a copy of the kill, because we use the normal kill
8435 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8437 (defvar org-subtree-clip-folded nil
8438 "Was the last copied subtree folded?
8439 This is used to fold the tree back after pasting.")
8441 (defun org-cut-subtree (&optional n)
8442 "Cut the current subtree into the clipboard.
8443 With prefix arg N, cut this many sequential subtrees.
8444 This is a short-hand for marking the subtree and then cutting it."
8445 (interactive "p")
8446 (org-copy-subtree n 'cut))
8448 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8449 "Copy the current subtree it in the clipboard.
8450 With prefix arg N, copy this many sequential subtrees.
8451 This is a short-hand for marking the subtree and then copying it.
8452 If CUT is non-nil, actually cut the subtree.
8453 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8454 of some markers in the region, even if CUT is non-nil. This is
8455 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8456 (interactive "p")
8457 (let (beg end folded (beg0 (point)))
8458 (if (called-interactively-p 'any)
8459 (org-back-to-heading nil) ; take what looks like a subtree
8460 (org-back-to-heading t)) ; take what is really there
8461 (setq beg (point))
8462 (skip-chars-forward " \t\r\n")
8463 (save-match-data
8464 (if nosubtrees
8465 (outline-next-heading)
8466 (save-excursion (outline-end-of-heading)
8467 (setq folded (org-invisible-p)))
8468 (ignore-errors (org-forward-heading-same-level (1- n) t))
8469 (org-end-of-subtree t t)))
8470 ;; Include the end of an inlinetask
8471 (when (and (featurep 'org-inlinetask)
8472 (looking-at-p (concat (org-inlinetask-outline-regexp)
8473 "END[ \t]*$")))
8474 (end-of-line))
8475 (setq end (point))
8476 (goto-char beg0)
8477 (when (> end beg)
8478 (setq org-subtree-clip-folded folded)
8479 (when (or cut force-store-markers)
8480 (org-save-markers-in-region beg end))
8481 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8482 (setq org-subtree-clip (current-kill 0))
8483 (message "%s: Subtree(s) with %d characters"
8484 (if cut "Cut" "Copied")
8485 (length org-subtree-clip)))))
8487 (defun org-paste-subtree (&optional level tree for-yank remove)
8488 "Paste the clipboard as a subtree, with modification of headline level.
8489 The entire subtree is promoted or demoted in order to match a new headline
8490 level.
8492 If the cursor is at the beginning of a headline, the same level as
8493 that headline is used to paste the tree.
8495 If not, the new level is derived from the *visible* headings
8496 before and after the insertion point, and taken to be the inferior headline
8497 level of the two. So if the previous visible heading is level 3 and the
8498 next is level 4 (or vice versa), level 4 will be used for insertion.
8499 This makes sure that the subtree remains an independent subtree and does
8500 not swallow low level entries.
8502 You can also force a different level, either by using a numeric prefix
8503 argument, or by inserting the heading marker by hand. For example, if the
8504 cursor is after \"*****\", then the tree will be shifted to level 5.
8506 If optional TREE is given, use this text instead of the kill ring.
8508 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8509 move back over whitespace before inserting, and move point to the end of
8510 the inserted text when done.
8512 When REMOVE is non-nil, remove the subtree from the clipboard."
8513 (interactive "P")
8514 (setq tree (or tree (and kill-ring (current-kill 0))))
8515 (unless (org-kill-is-subtree-p tree)
8516 (user-error "%s"
8517 (substitute-command-keys
8518 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8519 (org-with-limited-levels
8520 (let* ((visp (not (org-invisible-p)))
8521 (txt tree)
8522 (^re_ "\\(\\*+\\)[ \t]*")
8523 (old-level (if (string-match org-outline-regexp-bol txt)
8524 (- (match-end 0) (match-beginning 0) 1)
8525 -1))
8526 (force-level (cond (level (prefix-numeric-value level))
8527 ((and (looking-at "[ \t]*$")
8528 (string-match
8529 "^\\*+$" (buffer-substring
8530 (point-at-bol) (point))))
8531 (- (match-end 0) (match-beginning 0)))
8532 ((and (bolp)
8533 (looking-at org-outline-regexp))
8534 (- (match-end 0) (point) 1))))
8535 (previous-level (save-excursion
8536 (condition-case nil
8537 (progn
8538 (outline-previous-visible-heading 1)
8539 (if (looking-at ^re_)
8540 (- (match-end 0) (match-beginning 0) 1)
8542 (error 1))))
8543 (next-level (save-excursion
8544 (condition-case nil
8545 (progn
8546 (or (looking-at org-outline-regexp)
8547 (outline-next-visible-heading 1))
8548 (if (looking-at ^re_)
8549 (- (match-end 0) (match-beginning 0) 1)
8551 (error 1))))
8552 (new-level (or force-level (max previous-level next-level)))
8553 (shift (if (or (= old-level -1)
8554 (= new-level -1)
8555 (= old-level new-level))
8557 (- new-level old-level)))
8558 (delta (if (> shift 0) -1 1))
8559 (func (if (> shift 0) 'org-demote 'org-promote))
8560 (org-odd-levels-only nil)
8561 beg end newend)
8562 ;; Remove the forced level indicator
8563 (when force-level
8564 (delete-region (point-at-bol) (point)))
8565 ;; Paste
8566 (beginning-of-line (if (bolp) 1 2))
8567 (setq beg (point))
8568 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8569 (insert-before-markers txt)
8570 (unless (string-suffix-p "\n" txt) (insert "\n"))
8571 (setq newend (point))
8572 (org-reinstall-markers-in-region beg)
8573 (setq end (point))
8574 (goto-char beg)
8575 (skip-chars-forward " \t\n\r")
8576 (setq beg (point))
8577 (when (and (org-invisible-p) visp)
8578 (save-excursion (outline-show-heading)))
8579 ;; Shift if necessary
8580 (unless (= shift 0)
8581 (save-restriction
8582 (narrow-to-region beg end)
8583 (while (not (= shift 0))
8584 (org-map-region func (point-min) (point-max))
8585 (setq shift (+ delta shift)))
8586 (goto-char (point-min))
8587 (setq newend (point-max))))
8588 (when (or (called-interactively-p 'interactive) for-yank)
8589 (message "Clipboard pasted as level %d subtree" new-level))
8590 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8591 kill-ring
8592 (eq org-subtree-clip (current-kill 0))
8593 org-subtree-clip-folded)
8594 ;; The tree was folded before it was killed/copied
8595 (outline-hide-subtree))
8596 (and for-yank (goto-char newend))
8597 (and remove (setq kill-ring (cdr kill-ring))))))
8599 (defun org-kill-is-subtree-p (&optional txt)
8600 "Check if the current kill is an outline subtree, or a set of trees.
8601 Returns nil if kill does not start with a headline, or if the first
8602 headline level is not the largest headline level in the tree.
8603 So this will actually accept several entries of equal levels as well,
8604 which is OK for `org-paste-subtree'.
8605 If optional TXT is given, check this string instead of the current kill."
8606 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8607 (re (org-get-limited-outline-regexp))
8608 (^re (concat "^" re))
8609 (start-level (and kill
8610 (string-match
8611 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8612 kill)
8613 (- (match-end 2) (match-beginning 2) 1)))
8614 (start (1+ (or (match-beginning 2) -1))))
8615 (if (not start-level)
8616 (progn
8617 nil) ;; does not even start with a heading
8618 (catch 'exit
8619 (while (setq start (string-match ^re kill (1+ start)))
8620 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8621 (throw 'exit nil)))
8622 t))))
8624 (defvar org-markers-to-move nil
8625 "Markers that should be moved with a cut-and-paste operation.
8626 Those markers are stored together with their positions relative to
8627 the start of the region.")
8629 (defun org-save-markers-in-region (beg end)
8630 "Check markers in region.
8631 If these markers are between BEG and END, record their position relative
8632 to BEG, so that after moving the block of text, we can put the markers back
8633 into place.
8634 This function gets called just before an entry or tree gets cut from the
8635 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8636 called immediately, to move the markers with the entries."
8637 (setq org-markers-to-move nil)
8638 (when (featurep 'org-clock)
8639 (org-clock-save-markers-for-cut-and-paste beg end))
8640 (when (featurep 'org-agenda)
8641 (org-agenda-save-markers-for-cut-and-paste beg end)))
8643 (defun org-check-and-save-marker (marker beg end)
8644 "Check if MARKER is between BEG and END.
8645 If yes, remember the marker and the distance to BEG."
8646 (when (and (marker-buffer marker)
8647 (equal (marker-buffer marker) (current-buffer))
8648 (>= marker beg) (< marker end))
8649 (push (cons marker (- marker beg)) org-markers-to-move)))
8651 (defun org-reinstall-markers-in-region (beg)
8652 "Move all remembered markers to their position relative to BEG."
8653 (dolist (x org-markers-to-move)
8654 (move-marker (car x) (+ beg (cdr x))))
8655 (setq org-markers-to-move nil))
8657 (defun org-narrow-to-subtree ()
8658 "Narrow buffer to the current subtree."
8659 (interactive)
8660 (save-excursion
8661 (save-match-data
8662 (org-with-limited-levels
8663 (narrow-to-region
8664 (progn (org-back-to-heading t) (point))
8665 (progn (org-end-of-subtree t t)
8666 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8667 (point)))))))
8669 (defun org-narrow-to-block ()
8670 "Narrow buffer to the current block."
8671 (interactive)
8672 (let* ((case-fold-search t)
8673 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8674 "^[ \t]*#\\+end_.*")))
8675 (if blockp
8676 (narrow-to-region (car blockp) (cdr blockp))
8677 (user-error "Not in a block"))))
8679 (defun org-clone-subtree-with-time-shift (n &optional shift)
8680 "Clone the task (subtree) at point N times.
8681 The clones will be inserted as siblings.
8683 In interactive use, the user will be prompted for the number of
8684 clones to be produced. If the entry has a timestamp, the user
8685 will also be prompted for a time shift, which may be a repeater
8686 as used in time stamps, for example `+3d'. To disable this,
8687 you can call the function with a universal prefix argument.
8689 When a valid repeater is given and the entry contains any time
8690 stamps, the clones will become a sequence in time, with time
8691 stamps in the subtree shifted for each clone produced. If SHIFT
8692 is nil or the empty string, time stamps will be left alone. The
8693 ID property of the original subtree is removed.
8695 In each clone, all the CLOCK entries will be removed. This
8696 prevents Org from considering that the clocked times overlap.
8698 If the original subtree did contain time stamps with a repeater,
8699 the following will happen:
8700 - the repeater will be removed in each clone
8701 - an additional clone will be produced, with the current, unshifted
8702 date(s) in the entry.
8703 - the original entry will be placed *after* all the clones, with
8704 repeater intact.
8705 - the start days in the repeater in the original entry will be shifted
8706 to past the last clone.
8707 In this way you can spell out a number of instances of a repeating task,
8708 and still retain the repeater to cover future instances of the task.
8710 As described above, N+1 clones are produced when the original
8711 subtree has a repeater. Setting N to 0, then, can be used to
8712 remove the repeater from a subtree and create a shifted clone
8713 with the original repeater."
8714 (interactive "nNumber of clones to produce: ")
8715 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8716 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8717 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8718 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8719 (shift
8720 (or shift
8721 (if (and (not (equal current-prefix-arg '(4)))
8722 (save-excursion
8723 (goto-char beg)
8724 (re-search-forward org-ts-regexp-both end-of-tree t)))
8725 (read-from-minibuffer
8726 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8727 ""))) ;No time shift
8728 (doshift
8729 (and (org-string-nw-p shift)
8730 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8731 shift)
8732 (user-error "Invalid shift specification %s" shift)))))
8733 (goto-char end-of-tree)
8734 (unless (bolp) (insert "\n"))
8735 (let* ((end (point))
8736 (template (buffer-substring beg end))
8737 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8738 (shift-what (pcase (and doshift (match-string 2 shift))
8739 (`nil nil)
8740 ("d" 'day)
8741 ("w" (setq shift-n (* 7 shift-n)) 'day)
8742 ("m" 'month)
8743 ("y" 'year)
8744 (_ (error "Unsupported time unit"))))
8745 (nmin 1)
8746 (nmax n)
8747 (n-no-remove -1)
8748 (idprop (org-entry-get nil "ID")))
8749 (when (and doshift
8750 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8751 template))
8752 (delete-region beg end)
8753 (setq end beg)
8754 (setq nmin 0)
8755 (setq nmax (1+ nmax))
8756 (setq n-no-remove nmax))
8757 (goto-char end)
8758 (cl-loop for n from nmin to nmax do
8759 (insert
8760 ;; Prepare clone.
8761 (with-temp-buffer
8762 (insert template)
8763 (org-mode)
8764 (goto-char (point-min))
8765 (org-show-subtree)
8766 (and idprop (if org-clone-delete-id
8767 (org-entry-delete nil "ID")
8768 (org-id-get-create t)))
8769 (unless (= n 0)
8770 (while (re-search-forward org-clock-line-re nil t)
8771 (delete-region (line-beginning-position)
8772 (line-beginning-position 2)))
8773 (goto-char (point-min))
8774 (while (re-search-forward org-drawer-regexp nil t)
8775 (org-remove-empty-drawer-at (point))))
8776 (goto-char (point-min))
8777 (when doshift
8778 (while (re-search-forward org-ts-regexp-both nil t)
8779 (org-timestamp-change (* n shift-n) shift-what))
8780 (unless (= n n-no-remove)
8781 (goto-char (point-min))
8782 (while (re-search-forward org-ts-regexp nil t)
8783 (save-excursion
8784 (goto-char (match-beginning 0))
8785 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8786 (delete-region (match-beginning 1) (match-end 1)))))))
8787 (buffer-string)))))
8788 (goto-char beg)))
8790 ;;; Outline Sorting
8792 (defun org-sort (&optional with-case)
8793 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8794 Optional argument WITH-CASE means sort case-sensitively."
8795 (interactive "P")
8796 (org-call-with-arg
8797 (cond ((org-at-table-p) #'org-table-sort-lines)
8798 ((org-at-item-p) #'org-sort-list)
8799 (t #'org-sort-entries))
8800 with-case))
8802 (defun org-sort-remove-invisible (s)
8803 "Remove invisible part of links and emphasis markers from string S."
8804 (remove-text-properties 0 (length s) org-rm-props s)
8805 (replace-regexp-in-string
8806 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8807 (replace-regexp-in-string
8808 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8809 (org-link-display-format s)
8810 t t) t t))
8812 (defvar org-priority-regexp) ; defined later in the file
8814 (defvar org-after-sorting-entries-or-items-hook nil
8815 "Hook that is run after a bunch of entries or items have been sorted.
8816 When children are sorted, the cursor is in the parent line when this
8817 hook gets called. When a region or a plain list is sorted, the cursor
8818 will be in the first entry of the sorted region/list.")
8820 (defun org-sort-entries
8821 (&optional with-case sorting-type getkey-func compare-func property
8822 interactive?)
8823 "Sort entries on a certain level of an outline tree.
8824 If there is an active region, the entries in the region are sorted.
8825 Else, if the cursor is before the first entry, sort the top-level items.
8826 Else, the children of the entry at point are sorted.
8828 Sorting can be alphabetically, numerically, by date/time as given by
8829 a time stamp, by a property, by priority order, or by a custom function.
8831 The command prompts for the sorting type unless it has been given to the
8832 function through the SORTING-TYPE argument, which needs to be a character,
8833 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8834 the precise meaning of each character:
8836 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8837 c By creation time, which is assumed to be the first inactive time stamp
8838 at the beginning of a line.
8839 d By deadline date/time.
8840 k By clocking time.
8841 n Numerically, by converting the beginning of the entry/item to a number.
8842 o By order of TODO keywords.
8843 p By priority according to the cookie.
8844 r By the value of a property.
8845 s By scheduled date/time.
8846 t By date/time, either the first active time stamp in the entry, or, if
8847 none exist, by the first inactive one.
8849 Capital letters will reverse the sort order.
8851 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8852 called with point at the beginning of the record. It must return a
8853 value that is compatible with COMPARE-FUNC, the function used to
8854 compare entries.
8856 Comparing entries ignores case by default. However, with an optional argument
8857 WITH-CASE, the sorting considers case as well.
8859 Sorting is done against the visible part of the headlines, it ignores hidden
8860 links.
8862 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8864 A non-nil value for INTERACTIVE? is used to signal that this
8865 function is being called interactively."
8866 (interactive (list current-prefix-arg nil nil nil nil t))
8867 (let ((case-func (if with-case 'identity 'downcase))
8868 start beg end stars re re2
8869 txt what tmp)
8870 ;; Find beginning and end of region to sort
8871 (cond
8872 ((org-region-active-p)
8873 ;; we will sort the region
8874 (setq end (region-end)
8875 what "region")
8876 (goto-char (region-beginning))
8877 (unless (org-at-heading-p) (outline-next-heading))
8878 (setq start (point)))
8879 ((or (org-at-heading-p)
8880 (ignore-errors (progn (org-back-to-heading) t)))
8881 ;; we will sort the children of the current headline
8882 (org-back-to-heading)
8883 (setq start (point)
8884 end (progn (org-end-of-subtree t t)
8885 (or (bolp) (insert "\n"))
8886 (when (>= (org-back-over-empty-lines) 1)
8887 (forward-line 1))
8888 (point))
8889 what "children")
8890 (goto-char start)
8891 (outline-show-subtree)
8892 (outline-next-heading))
8894 ;; we will sort the top-level entries in this file
8895 (goto-char (point-min))
8896 (or (org-at-heading-p) (outline-next-heading))
8897 (setq start (point))
8898 (goto-char (point-max))
8899 (beginning-of-line 1)
8900 (when (looking-at ".*?\\S-")
8901 ;; File ends in a non-white line
8902 (end-of-line 1)
8903 (insert "\n"))
8904 (setq end (point-max))
8905 (setq what "top-level")
8906 (goto-char start)
8907 (outline-show-all)))
8909 (setq beg (point))
8910 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8912 (looking-at "\\(\\*+\\)")
8913 (setq stars (match-string 1)
8914 re (concat "^" (regexp-quote stars) " +")
8915 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8916 txt (buffer-substring beg end))
8917 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8918 (when (and (not (equal stars "*")) (string-match re2 txt))
8919 (user-error "Region to sort contains a level above the first entry"))
8921 (unless sorting-type
8922 (message
8923 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8924 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8925 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8926 what)
8927 (setq sorting-type (read-char-exclusive)))
8929 (unless getkey-func
8930 (and (= (downcase sorting-type) ?f)
8931 (setq getkey-func
8932 (or (and interactive?
8933 (org-read-function
8934 "Function for extracting keys: "))
8935 (error "Missing key extractor")))))
8937 (and (= (downcase sorting-type) ?r)
8938 (not property)
8939 (setq property
8940 (completing-read "Property: "
8941 (mapcar #'list (org-buffer-property-keys t))
8942 nil t)))
8944 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8945 (message "Sorting entries...")
8947 (save-restriction
8948 (narrow-to-region start end)
8949 (let ((restore-clock?
8950 ;; The clock marker is lost when using `sort-subr'; mark
8951 ;; the clock with temporary `:org-clock-marker-backup'
8952 ;; text property.
8953 (when (and (eq (org-clock-is-active) (current-buffer))
8954 (<= start (marker-position org-clock-marker))
8955 (>= end (marker-position org-clock-marker)))
8956 (org-with-silent-modifications
8957 (put-text-property (1- org-clock-marker) org-clock-marker
8958 :org-clock-marker-backup t))
8960 (dcst (downcase sorting-type))
8961 (case-fold-search nil)
8962 (now (current-time)))
8963 (sort-subr
8964 (/= dcst sorting-type)
8965 ;; This function moves to the beginning character of the "record" to
8966 ;; be sorted.
8967 (lambda nil
8968 (if (re-search-forward re nil t)
8969 (goto-char (match-beginning 0))
8970 (goto-char (point-max))))
8971 ;; This function moves to the last character of the "record" being
8972 ;; sorted.
8973 (lambda nil
8974 (save-match-data
8975 (condition-case nil
8976 (outline-forward-same-level 1)
8977 (error
8978 (goto-char (point-max))))))
8979 ;; This function returns the value that gets sorted against.
8980 (lambda nil
8981 (cond
8982 ((= dcst ?n)
8983 (if (looking-at org-complex-heading-regexp)
8984 (string-to-number (org-sort-remove-invisible (match-string 4)))
8985 nil))
8986 ((= dcst ?a)
8987 (if (looking-at org-complex-heading-regexp)
8988 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8989 nil))
8990 ((= dcst ?k)
8991 (or (get-text-property (point) :org-clock-minutes) 0))
8992 ((= dcst ?t)
8993 (let ((end (save-excursion (outline-next-heading) (point))))
8994 (if (or (re-search-forward org-ts-regexp end t)
8995 (re-search-forward org-ts-regexp-both end t))
8996 (org-time-string-to-seconds (match-string 0))
8997 (float-time now))))
8998 ((= dcst ?c)
8999 (let ((end (save-excursion (outline-next-heading) (point))))
9000 (if (re-search-forward
9001 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9002 end t)
9003 (org-time-string-to-seconds (match-string 0))
9004 (float-time now))))
9005 ((= dcst ?s)
9006 (let ((end (save-excursion (outline-next-heading) (point))))
9007 (if (re-search-forward org-scheduled-time-regexp end t)
9008 (org-time-string-to-seconds (match-string 1))
9009 (float-time now))))
9010 ((= dcst ?d)
9011 (let ((end (save-excursion (outline-next-heading) (point))))
9012 (if (re-search-forward org-deadline-time-regexp end t)
9013 (org-time-string-to-seconds (match-string 1))
9014 (float-time now))))
9015 ((= dcst ?p)
9016 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9017 (string-to-char (match-string 2))
9018 org-default-priority))
9019 ((= dcst ?r)
9020 (or (org-entry-get nil property) ""))
9021 ((= dcst ?o)
9022 (when (looking-at org-complex-heading-regexp)
9023 (let* ((m (match-string 2))
9024 (s (if (member m org-done-keywords) '- '+)))
9025 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9026 ((= dcst ?f)
9027 (if getkey-func
9028 (progn
9029 (setq tmp (funcall getkey-func))
9030 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9031 tmp)
9032 (error "Invalid key function `%s'" getkey-func)))
9033 (t (error "Invalid sorting type `%c'" sorting-type))))
9035 (cond
9036 ((= dcst ?a) 'string<)
9037 ((= dcst ?f)
9038 (or compare-func
9039 (and interactive?
9040 (org-read-function
9041 (concat "Function for comparing keys "
9042 "(empty for default `sort-subr' predicate): ")
9043 'allow-empty))))
9044 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9045 (when restore-clock?
9046 (move-marker org-clock-marker
9047 (1+ (next-single-property-change
9048 start :org-clock-marker-backup)))
9049 (remove-text-properties (1- org-clock-marker) org-clock-marker
9050 '(:org-clock-marker-backup t)))))
9051 (run-hooks 'org-after-sorting-entries-or-items-hook)
9052 (message "Sorting entries...done")))
9054 ;;; The orgstruct minor mode
9056 ;; Define a minor mode which can be used in other modes in order to
9057 ;; integrate the Org mode structure editing commands.
9059 ;; This is really a hack, because the Org mode structure commands use
9060 ;; keys which normally belong to the major mode. Here is how it
9061 ;; works: The minor mode defines all the keys necessary to operate the
9062 ;; structure commands, but wraps the commands into a function which
9063 ;; tests if the cursor is currently at a headline or a plain list
9064 ;; item. If that is the case, the structure command is used,
9065 ;; temporarily setting many Org mode variables like regular
9066 ;; expressions for filling etc. However, when any of those keys is
9067 ;; used at a different location, function uses `key-binding' to look
9068 ;; up if the key has an associated command in another currently active
9069 ;; keymap (minor modes, major mode, global), and executes that
9070 ;; command. There might be problems if any of the keys is otherwise
9071 ;; used as a prefix key.
9073 (defcustom orgstruct-heading-prefix-regexp ""
9074 "Regexp that matches the custom prefix of Org headlines in
9075 orgstruct(++)-mode."
9076 :group 'org
9077 :version "26.1"
9078 :package-version '(Org . "8.3")
9079 :type 'regexp)
9080 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9082 (defcustom orgstruct-setup-hook nil
9083 "Hook run after orgstruct-mode-map is filled."
9084 :group 'org
9085 :version "24.4"
9086 :package-version '(Org . "8.0")
9087 :type 'hook)
9089 (defvar orgstruct-initialized nil)
9091 (defvar org-local-vars nil
9092 "List of local variables, for use by `orgstruct-mode'.")
9094 ;;;###autoload
9095 (define-minor-mode orgstruct-mode
9096 "Toggle the minor mode `orgstruct-mode'.
9097 This mode is for using Org mode structure commands in other
9098 modes. The following keys behave as if Org mode were active, if
9099 the cursor is on a headline, or on a plain list item (both as
9100 defined by Org mode)."
9101 nil " OrgStruct" (make-sparse-keymap)
9102 (funcall (if orgstruct-mode
9103 'add-to-invisibility-spec
9104 'remove-from-invisibility-spec)
9105 '(outline . t))
9106 (when orgstruct-mode
9107 (org-load-modules-maybe)
9108 (unless orgstruct-initialized
9109 (orgstruct-setup)
9110 (setq orgstruct-initialized t))))
9112 ;;;###autoload
9113 (defun turn-on-orgstruct ()
9114 "Unconditionally turn on `orgstruct-mode'."
9115 (orgstruct-mode 1))
9117 (defvar-local orgstruct-is-++ nil
9118 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9119 (defvar-local org-fb-vars nil)
9120 (defun orgstruct++-mode (&optional arg)
9121 "Toggle `orgstruct-mode', the enhanced version of it.
9122 In addition to setting orgstruct-mode, this also exports all
9123 indentation and autofilling variables from Org mode into the
9124 buffer. It will also recognize item context in multiline items."
9125 (interactive "P")
9126 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9127 (if (< arg 1)
9128 (progn (orgstruct-mode -1)
9129 (dolist (v org-fb-vars)
9130 (set (make-local-variable (car v))
9131 (if (eq (car-safe (cadr v)) 'quote)
9132 (cl-cadadr v)
9133 (nth 1 v)))))
9134 (orgstruct-mode 1)
9135 (setq org-fb-vars nil)
9136 (unless org-local-vars
9137 (setq org-local-vars (org-get-local-variables)))
9138 (let (var val)
9139 (dolist (x org-local-vars)
9140 (when (string-match
9141 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9142 \\|fill-prefix\\|indent-\\)"
9143 (symbol-name (car x)))
9144 (setq var (car x) val (nth 1 x))
9145 (push (list var `(quote ,(eval var))) org-fb-vars)
9146 (set (make-local-variable var)
9147 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9148 (setq-local orgstruct-is-++ t))))
9150 ;;;###autoload
9151 (defun turn-on-orgstruct++ ()
9152 "Unconditionally turn on `orgstruct++-mode'."
9153 (orgstruct++-mode 1))
9155 (defun orgstruct-error ()
9156 "Error when there is no default binding for a structure key."
9157 (interactive)
9158 (funcall (if (fboundp 'user-error)
9159 'user-error
9160 'error)
9161 "This key has no function outside structure elements"))
9163 (defun orgstruct-setup ()
9164 "Setup orgstruct keymap."
9165 (dolist (cell '((org-demote . t)
9166 (org-metaleft . t)
9167 (org-metaright . t)
9168 (org-promote . t)
9169 (org-shiftmetaleft . t)
9170 (org-shiftmetaright . t)
9171 org-backward-element
9172 org-backward-heading-same-level
9173 org-ctrl-c-ret
9174 org-ctrl-c-minus
9175 org-ctrl-c-star
9176 org-cycle
9177 org-force-cycle-archived
9178 org-forward-heading-same-level
9179 org-insert-heading
9180 org-insert-heading-respect-content
9181 org-kill-note-or-show-branches
9182 org-mark-subtree
9183 org-meta-return
9184 org-metadown
9185 org-metaup
9186 org-narrow-to-subtree
9187 org-promote-subtree
9188 org-reveal
9189 org-shiftdown
9190 org-shiftleft
9191 org-shiftmetadown
9192 org-shiftmetaup
9193 org-shiftright
9194 org-shifttab
9195 org-shifttab
9196 org-shiftup
9197 org-show-children
9198 org-show-subtree
9199 org-sort
9200 org-up-element
9201 outline-demote
9202 outline-next-visible-heading
9203 outline-previous-visible-heading
9204 outline-promote
9205 outline-up-heading))
9206 (let ((f (or (car-safe cell) cell))
9207 (disable-when-heading-prefix (cdr-safe cell)))
9208 (when (fboundp f)
9209 (let ((new-bindings))
9210 (dolist (binding (nconc (where-is-internal f org-mode-map)
9211 (where-is-internal f outline-mode-map)))
9212 (push binding new-bindings)
9213 ;; TODO use local-function-key-map
9214 (dolist (rep '(("<tab>" . "TAB")
9215 ("<return>" . "RET")
9216 ("<escape>" . "ESC")
9217 ("<delete>" . "DEL")))
9218 (setq binding (read-kbd-macro
9219 (let ((case-fold-search))
9220 (replace-regexp-in-string
9221 (regexp-quote (cdr rep))
9222 (car rep)
9223 (key-description binding)))))
9224 (cl-pushnew binding new-bindings :test 'equal)))
9225 (dolist (binding new-bindings)
9226 (let ((key (lookup-key orgstruct-mode-map binding)))
9227 (when (or (not key) (numberp key))
9228 (ignore-errors
9229 (org-defkey orgstruct-mode-map
9230 binding
9231 (orgstruct-make-binding
9232 f binding disable-when-heading-prefix))))))))))
9233 (run-hooks 'orgstruct-setup-hook))
9235 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9236 "Create a function for binding in the structure minor mode.
9237 FUN is the command to call inside a table. KEY is the key that
9238 should be checked in for a command to execute outside of tables.
9239 Non-nil `disable-when-heading-prefix' means to disable the command
9240 if `orgstruct-heading-prefix-regexp' is not empty."
9241 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9242 (let ((nname name)
9243 (i 0))
9244 (while (fboundp (intern nname))
9245 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9246 (setq name (intern nname)))
9247 (eval
9248 (let ((bindings '((org-heading-regexp
9249 (concat "^"
9250 orgstruct-heading-prefix-regexp
9251 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9252 (org-outline-regexp
9253 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9254 (org-outline-regexp-bol
9255 (concat "^" org-outline-regexp))
9256 (outline-regexp org-outline-regexp)
9257 (outline-heading-end-regexp "\n")
9258 (outline-level 'org-outline-level)
9259 (outline-heading-alist))))
9260 `(defun ,name (arg)
9261 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9262 "Outside of structure, run the binding of `"
9263 (key-description key) "'."
9264 (when disable-when-heading-prefix
9265 (concat
9266 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9267 "back to the default binding due to limitations of Org's implementation of\n"
9268 "`" (symbol-name fun) "'.")))
9269 (interactive "p")
9270 (let* ((disable
9271 ,(and disable-when-heading-prefix
9272 '(not (string= orgstruct-heading-prefix-regexp ""))))
9273 (fallback
9274 (or disable
9275 (not
9276 (let* ,bindings
9277 (org-context-p 'headline 'item
9278 ,(when (memq fun
9279 '(org-insert-heading
9280 org-insert-heading-respect-content
9281 org-meta-return))
9282 '(when orgstruct-is-++
9283 'item-body))))))))
9284 (if fallback
9285 (let* ((orgstruct-mode)
9286 (binding
9287 (let ((key ,key))
9288 (catch 'exit
9289 (dolist
9290 (rep
9291 '(nil
9292 ("<\\([^>]*\\)tab>" . "\\1TAB")
9293 ("<\\([^>]*\\)return>" . "\\1RET")
9294 ("<\\([^>]*\\)escape>" . "\\1ESC")
9295 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9296 nil)
9297 (when rep
9298 (setq key (read-kbd-macro
9299 (let ((case-fold-search))
9300 (replace-regexp-in-string
9301 (car rep)
9302 (cdr rep)
9303 (key-description key))))))
9304 (when (key-binding key)
9305 (throw 'exit (key-binding key))))))))
9306 (if (keymapp binding)
9307 (org-set-transient-map binding)
9308 (let ((func (or binding
9309 (unless disable
9310 'orgstruct-error))))
9311 (when func
9312 (call-interactively func)))))
9313 (org-run-like-in-org-mode
9314 (lambda ()
9315 (interactive)
9316 (let* ,bindings
9317 (call-interactively ',fun)))))))))
9318 name))
9320 (defun org-contextualize-keys (alist contexts)
9321 "Return valid elements in ALIST depending on CONTEXTS.
9323 `org-agenda-custom-commands' or `org-capture-templates' are the
9324 values used for ALIST, and `org-agenda-custom-commands-contexts'
9325 or `org-capture-templates-contexts' are the associated contexts
9326 definitions."
9327 (let ((contexts
9328 ;; normalize contexts
9329 (mapcar
9330 (lambda(c) (cond ((listp (cadr c))
9331 (list (car c) (car c) (nth 1 c)))
9332 ((string= "" (cadr c))
9333 (list (car c) (car c) (nth 2 c)))
9334 (t c)))
9335 contexts))
9336 (a alist) r s)
9337 ;; loop over all commands or templates
9338 (dolist (c a)
9339 (let (vrules repl)
9340 (cond
9341 ((not (assoc (car c) contexts))
9342 (push c r))
9343 ((and (assoc (car c) contexts)
9344 (setq vrules (org-contextualize-validate-key
9345 (car c) contexts)))
9346 (mapc (lambda (vr)
9347 (unless (equal (car vr) (cadr vr))
9348 (setq repl vr)))
9349 vrules)
9350 (if (not repl) (push c r)
9351 (push (cadr repl) s)
9352 (push
9353 (cons (car c)
9354 (cdr (or (assoc (cadr repl) alist)
9355 (error "Undefined key `%s' as contextual replacement for `%s'"
9356 (cadr repl) (car c)))))
9357 r))))))
9358 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9359 (delq
9361 (delete-dups
9362 (mapcar (lambda (x)
9363 (let ((tpl (car x)))
9364 (unless (delq
9366 (mapcar (lambda (y)
9367 (equal y tpl))
9369 x)))
9370 (reverse r))))))
9372 (defun org-contextualize-validate-key (key contexts)
9373 "Check CONTEXTS for agenda or capture KEY."
9374 (let (res)
9375 (dolist (r contexts)
9376 (dolist (rr (car (last r)))
9377 (when
9378 (and (equal key (car r))
9379 (if (functionp rr) (funcall rr)
9380 (or (and (eq (car rr) 'in-file)
9381 (buffer-file-name)
9382 (string-match (cdr rr) (buffer-file-name)))
9383 (and (eq (car rr) 'in-mode)
9384 (string-match (cdr rr) (symbol-name major-mode)))
9385 (and (eq (car rr) 'in-buffer)
9386 (string-match (cdr rr) (buffer-name)))
9387 (when (and (eq (car rr) 'not-in-file)
9388 (buffer-file-name))
9389 (not (string-match (cdr rr) (buffer-file-name))))
9390 (when (eq (car rr) 'not-in-mode)
9391 (not (string-match (cdr rr) (symbol-name major-mode))))
9392 (when (eq (car rr) 'not-in-buffer)
9393 (not (string-match (cdr rr) (buffer-name)))))))
9394 (push r res))))
9395 (delete-dups (delq nil res))))
9397 (defun org-context-p (&rest contexts)
9398 "Check if local context is any of CONTEXTS.
9399 Possible values in the list of contexts are `table', `headline', and `item'."
9400 (let ((pos (point)))
9401 (goto-char (point-at-bol))
9402 (prog1 (or (and (memq 'table contexts)
9403 (looking-at "[ \t]*|"))
9404 (and (memq 'headline contexts)
9405 (looking-at org-outline-regexp))
9406 (and (memq 'item contexts)
9407 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9408 (and (memq 'item-body contexts)
9409 (org-in-item-p)))
9410 (goto-char pos))))
9412 ;;;###autoload
9413 (defun org-run-like-in-org-mode (cmd)
9414 "Run a command, pretending that the current buffer is in Org mode.
9415 This will temporarily bind local variables that are typically bound in
9416 Org mode to the values they have in Org mode, and then interactively
9417 call CMD."
9418 (org-load-modules-maybe)
9419 (unless org-local-vars
9420 (setq org-local-vars (org-get-local-variables)))
9421 (let (binds)
9422 (dolist (var org-local-vars)
9423 (when (or (not (boundp (car var)))
9424 (eq (symbol-value (car var))
9425 (default-value (car var))))
9426 (push (list (car var) `(quote ,(cadr var))) binds)))
9427 (eval `(let ,binds
9428 (call-interactively (quote ,cmd))))))
9430 (defun org-get-category (&optional pos force-refresh)
9431 "Get the category applying to position POS."
9432 (save-match-data
9433 (when force-refresh (org-refresh-category-properties))
9434 (let ((pos (or pos (point))))
9435 (or (get-text-property pos 'org-category)
9436 (progn (org-refresh-category-properties)
9437 (get-text-property pos 'org-category))))))
9439 ;;; Refresh properties
9441 (defun org-refresh-properties (dprop tprop)
9442 "Refresh buffer text properties.
9443 DPROP is the drawer property and TPROP is either the
9444 corresponding text property to set, or an alist with each element
9445 being a text property (as a symbol) and a function to apply to
9446 the value of the drawer property."
9447 (let* ((case-fold-search t)
9448 (inhibit-read-only t)
9449 (inherit? (org-property-inherit-p dprop))
9450 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9451 (global (and inherit? (org--property-global-value dprop nil))))
9452 (org-with-silent-modifications
9453 (org-with-point-at 1
9454 ;; Set global values (e.g., values defined through
9455 ;; "#+PROPERTY:" keywords) to the whole buffer.
9456 (when global (put-text-property (point-min) (point-max) tprop global))
9457 ;; Set local values.
9458 (while (re-search-forward property-re nil t)
9459 (when (org-at-property-p)
9460 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9461 (outline-next-heading))))))
9463 (defun org-refresh-property (tprop p &optional inherit)
9464 "Refresh the buffer text property TPROP from the drawer property P.
9465 The refresh happens only for the current headline, or the whole
9466 sub-tree if optional argument INHERIT is non-nil."
9467 (unless (org-before-first-heading-p)
9468 (save-excursion
9469 (org-back-to-heading t)
9470 (let ((start (point))
9471 (end (save-excursion
9472 (if inherit (org-end-of-subtree t t)
9473 (or (outline-next-heading) (point-max))))))
9474 (if (symbolp tprop)
9475 ;; TPROP is a text property symbol.
9476 (put-text-property start end tprop p)
9477 ;; TPROP is an alist with (property . function) elements.
9478 (pcase-dolist (`(,prop . ,f) tprop)
9479 (put-text-property start end prop (funcall f p))))))))
9481 (defun org-refresh-category-properties ()
9482 "Refresh category text properties in the buffer."
9483 (let ((case-fold-search t)
9484 (inhibit-read-only t)
9485 (default-category
9486 (cond ((null org-category)
9487 (if buffer-file-name
9488 (file-name-sans-extension
9489 (file-name-nondirectory buffer-file-name))
9490 "???"))
9491 ((symbolp org-category) (symbol-name org-category))
9492 (t org-category))))
9493 (org-with-silent-modifications
9494 (org-with-wide-buffer
9495 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9496 ;; This is the default category for the buffer. If none is
9497 ;; found, fall-back to `org-category' or buffer file name.
9498 (put-text-property
9499 (point-min) (point-max)
9500 'org-category
9501 (catch 'buffer-category
9502 (goto-char (point-max))
9503 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9504 (let ((element (org-element-at-point)))
9505 (when (eq (org-element-type element) 'keyword)
9506 (throw 'buffer-category
9507 (org-element-property :value element)))))
9508 default-category))
9509 ;; Set sub-tree specific categories.
9510 (goto-char (point-min))
9511 (let ((regexp (org-re-property "CATEGORY")))
9512 (while (re-search-forward regexp nil t)
9513 (let ((value (match-string-no-properties 3)))
9514 (when (org-at-property-p)
9515 (put-text-property
9516 (save-excursion (org-back-to-heading t) (point))
9517 (save-excursion (org-end-of-subtree t t) (point))
9518 'org-category
9519 value)))))))))
9521 (defun org-refresh-stats-properties ()
9522 "Refresh stats text properties in the buffer."
9523 (org-with-silent-modifications
9524 (org-with-point-at 1
9525 (let ((regexp (concat org-outline-regexp-bol
9526 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9527 (while (re-search-forward regexp nil t)
9528 (let* ((numerator (string-to-number (match-string 1)))
9529 (denominator (and (match-end 2)
9530 (string-to-number (match-string 2))))
9531 (stats (cond ((not denominator) numerator) ;percent
9532 ((= denominator 0) 0)
9533 (t (/ (* numerator 100) denominator)))))
9534 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9535 'org-stats stats)))))))
9537 (defun org-refresh-effort-properties ()
9538 "Refresh effort properties"
9539 (org-refresh-properties
9540 org-effort-property
9541 '((effort . identity)
9542 (effort-minutes . org-duration-to-minutes))))
9544 ;;;; Link Stuff
9546 ;;; Link abbreviations
9548 (defun org-link-expand-abbrev (link)
9549 "Apply replacements as defined in `org-link-abbrev-alist'."
9550 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9551 (let* ((key (match-string 1 link))
9552 (as (or (assoc key org-link-abbrev-alist-local)
9553 (assoc key org-link-abbrev-alist)))
9554 (tag (and (match-end 2) (match-string 3 link)))
9555 rpl)
9556 (if (not as)
9557 link
9558 (setq rpl (cdr as))
9559 (cond
9560 ((symbolp rpl) (funcall rpl tag))
9561 ((string-match "%(\\([^)]+\\))" rpl)
9562 (replace-match
9563 (save-match-data
9564 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9565 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9566 ((string-match "%h" rpl)
9567 (replace-match (url-hexify-string (or tag "")) t t rpl))
9568 (t (concat rpl tag)))))
9569 link))
9571 ;;; Storing and inserting links
9573 (defvar org-insert-link-history nil
9574 "Minibuffer history for links inserted with `org-insert-link'.")
9576 (defvar org-stored-links nil
9577 "Contains the links stored with `org-store-link'.")
9579 (defvar org-store-link-plist nil
9580 "Plist with info about the most recently link created with `org-store-link'.")
9582 (defun org-store-link-functions ()
9583 "Return a list of functions that are called to create and store a link.
9584 The functions defined in the :store property of
9585 `org-link-parameters'.
9587 Each function will be called in turn until one returns a non-nil
9588 value. Each function should check if it is responsible for
9589 creating this link (for example by looking at the major mode).
9590 If not, it must exit and return nil. If yes, it should return
9591 a non-nil value after calling `org-store-link-props' with a list
9592 of properties and values. Special properties are:
9594 :type The link prefix, like \"http\". This must be given.
9595 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9596 This is obligatory as well.
9597 :description Optional default description for the second pair
9598 of brackets in an Org mode link. The user can still change
9599 this when inserting this link into an Org mode buffer.
9601 In addition to these, any additional properties can be specified
9602 and then used in capture templates."
9603 (cl-loop for link in org-link-parameters
9604 with store-func
9605 do (setq store-func (org-link-get-parameter (car link) :store))
9606 if store-func
9607 collect store-func))
9609 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9610 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9612 ;;;###autoload
9613 (defun org-store-link (arg)
9614 "Store an org-link to the current location.
9615 \\<org-mode-map>
9616 This link is added to `org-stored-links' and can later be inserted
9617 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9619 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9620 A single
9621 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9622 `org-gnus-prefer-web-links' for links to Usenet articles.
9624 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9625 skipping storing functions that are not
9626 part of Org core.
9628 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9629 prefix ARG forces storing a link for each line in the
9630 active region."
9631 (interactive "P")
9632 (org-load-modules-maybe)
9633 (if (and (equal arg '(64)) (org-region-active-p))
9634 (save-excursion
9635 (let ((end (region-end)))
9636 (goto-char (region-beginning))
9637 (set-mark (point))
9638 (while (< (point-at-eol) end)
9639 (move-end-of-line 1) (activate-mark)
9640 (let (current-prefix-arg)
9641 (call-interactively 'org-store-link))
9642 (move-beginning-of-line 2)
9643 (set-mark (point)))))
9644 (setq org-store-link-plist nil)
9645 (let (link cpltxt desc description search
9646 txt custom-id agenda-link sfuns sfunsn)
9647 (cond
9649 ;; Store a link using an external link type
9650 ((and (not (equal arg '(16)))
9651 (setq sfuns
9652 (delq
9653 nil (mapcar (lambda (f)
9654 (let (fs) (if (funcall f) (push f fs))))
9655 (org-store-link-functions)))
9656 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9657 (or (and (cdr sfuns)
9658 (funcall (intern
9659 (completing-read
9660 "Which function for creating the link? "
9661 sfunsn nil t (car sfunsn)))))
9662 (funcall (caar sfuns)))
9663 (setq link (plist-get org-store-link-plist :link)
9664 desc (or (plist-get org-store-link-plist
9665 :description)
9666 link))))
9668 ;; Store a link from a source code buffer.
9669 ((org-src-edit-buffer-p)
9670 (let ((coderef-format (org-src-coderef-format)))
9671 (cond ((save-excursion
9672 (beginning-of-line)
9673 (looking-at (org-src-coderef-regexp coderef-format)))
9674 (setq link (format "(%s)" (match-string-no-properties 3))))
9675 ((called-interactively-p 'any)
9676 (let ((label (read-string "Code line label: ")))
9677 (end-of-line)
9678 (setq link (format coderef-format label))
9679 (let ((gc (- 79 (length link))))
9680 (if (< (current-column) gc)
9681 (org-move-to-column gc t)
9682 (insert " ")))
9683 (insert link)
9684 (setq link (concat "(" label ")"))
9685 (setq desc nil)))
9686 (t (setq link nil)))))
9688 ;; We are in the agenda, link to referenced location
9689 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9690 (let ((m (or (get-text-property (point) 'org-hd-marker)
9691 (get-text-property (point) 'org-marker))))
9692 (when m
9693 (org-with-point-at m
9694 (setq agenda-link
9695 (if (called-interactively-p 'any)
9696 (call-interactively 'org-store-link)
9697 (org-store-link nil)))))))
9699 ((eq major-mode 'calendar-mode)
9700 (let ((cd (calendar-cursor-to-date)))
9701 (setq link
9702 (format-time-string
9703 (car org-time-stamp-formats)
9704 (apply 'encode-time
9705 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9706 nil nil nil))))
9707 (org-store-link-props :type "calendar" :date cd)))
9709 ((eq major-mode 'help-mode)
9710 (setq link (concat "help:" (save-excursion
9711 (goto-char (point-min))
9712 (looking-at "^[^ ]+")
9713 (match-string 0))))
9714 (org-store-link-props :type "help"))
9716 ((eq major-mode 'w3-mode)
9717 (setq cpltxt (if (and (buffer-name)
9718 (not (string-match "Untitled" (buffer-name))))
9719 (buffer-name)
9720 (url-view-url t))
9721 link (url-view-url t))
9722 (org-store-link-props :type "w3" :url (url-view-url t)))
9724 ((eq major-mode 'image-mode)
9725 (setq cpltxt (concat "file:"
9726 (abbreviate-file-name buffer-file-name))
9727 link cpltxt)
9728 (org-store-link-props :type "image" :file buffer-file-name))
9730 ;; In dired, store a link to the file of the current line
9731 ((derived-mode-p 'dired-mode)
9732 (let ((file (dired-get-filename nil t)))
9733 (setq file (if file
9734 (abbreviate-file-name
9735 (expand-file-name (dired-get-filename nil t)))
9736 ;; otherwise, no file so use current directory.
9737 default-directory))
9738 (setq cpltxt (concat "file:" file)
9739 link cpltxt)))
9741 ((setq search (run-hook-with-args-until-success
9742 'org-create-file-search-functions))
9743 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9744 "::" search))
9745 (setq cpltxt (or description link)))
9747 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9748 (org-with-limited-levels
9749 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9750 (cond
9751 ;; Store a link using the target at point
9752 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9753 (setq cpltxt
9754 (concat "file:"
9755 (abbreviate-file-name
9756 (buffer-file-name (buffer-base-buffer)))
9757 "::" (match-string 1))
9758 link cpltxt))
9759 ((and (featurep 'org-id)
9760 (or (eq org-id-link-to-org-use-id t)
9761 (and (called-interactively-p 'any)
9762 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9763 (and (eq org-id-link-to-org-use-id
9764 'create-if-interactive-and-no-custom-id)
9765 (not custom-id))))
9766 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9767 ;; Store a link using the ID at point
9768 (setq link (condition-case nil
9769 (prog1 (org-id-store-link)
9770 (setq desc (or (plist-get org-store-link-plist
9771 :description)
9772 "")))
9773 (error
9774 ;; Probably before first headline, link only to file
9775 (concat "file:"
9776 (abbreviate-file-name
9777 (buffer-file-name (buffer-base-buffer))))))))
9779 ;; Just link to current headline
9780 (setq cpltxt (concat "file:"
9781 (abbreviate-file-name
9782 (buffer-file-name (buffer-base-buffer)))))
9783 ;; Add a context search string
9784 (when (org-xor org-context-in-file-links
9785 (equal arg '(4)))
9786 (let* ((element (org-element-at-point))
9787 (name (org-element-property :name element)))
9788 (setq txt (cond
9789 ((org-at-heading-p) nil)
9790 (name)
9791 ((org-region-active-p)
9792 (buffer-substring (region-beginning) (region-end)))))
9793 (when (or (null txt) (string-match "\\S-" txt))
9794 (setq cpltxt
9795 (concat cpltxt "::"
9796 (condition-case nil
9797 (org-make-org-heading-search-string txt)
9798 (error "")))
9799 desc (or name
9800 (nth 4 (ignore-errors (org-heading-components)))
9801 "NONE")))))
9802 (when (string-match "::\\'" cpltxt)
9803 (setq cpltxt (substring cpltxt 0 -2)))
9804 (setq link cpltxt)))))
9806 ((buffer-file-name (buffer-base-buffer))
9807 ;; Just link to this file here.
9808 (setq cpltxt (concat "file:"
9809 (abbreviate-file-name
9810 (buffer-file-name (buffer-base-buffer)))))
9811 ;; Add a context string.
9812 (when (org-xor org-context-in-file-links
9813 (equal arg '(4)))
9814 (setq txt (if (org-region-active-p)
9815 (buffer-substring (region-beginning) (region-end))
9816 (buffer-substring (point-at-bol) (point-at-eol))))
9817 ;; Only use search option if there is some text.
9818 (when (string-match "\\S-" txt)
9819 (setq cpltxt
9820 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9821 desc "NONE")))
9822 (setq link cpltxt))
9824 ((called-interactively-p 'interactive)
9825 (user-error "No method for storing a link from this buffer"))
9827 (t (setq link nil)))
9829 ;; We're done setting link and desc, clean up
9830 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9831 (setq link (or link cpltxt)
9832 desc (or desc cpltxt))
9833 (cond ((not desc))
9834 ((equal desc "NONE") (setq desc nil))
9835 (t (setq desc
9836 (replace-regexp-in-string
9837 org-bracket-link-analytic-regexp
9838 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9839 desc))))
9840 ;; Return the link
9841 (if (not (and (or (called-interactively-p 'any)
9842 executing-kbd-macro)
9843 link))
9844 (or agenda-link (and link (org-make-link-string link desc)))
9845 (push (list link desc) org-stored-links)
9846 (message "Stored: %s" (or desc link))
9847 (when custom-id
9848 (setq link (concat "file:" (abbreviate-file-name
9849 (buffer-file-name)) "::#" custom-id))
9850 (push (list link desc) org-stored-links))
9851 (car org-stored-links)))))
9853 (defun org-store-link-props (&rest plist)
9854 "Store link properties, extract names, addresses and dates."
9855 (let ((x (plist-get plist :from)))
9856 (when x
9857 (let ((adr (mail-extract-address-components x)))
9858 (setq plist (plist-put plist :fromname (car adr)))
9859 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9860 (let ((x (plist-get plist :to)))
9861 (when x
9862 (let ((adr (mail-extract-address-components x)))
9863 (setq plist (plist-put plist :toname (car adr)))
9864 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9865 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9866 (when x
9867 (setq plist (plist-put plist :date-timestamp
9868 (format-time-string
9869 (org-time-stamp-format t) x)))
9870 (setq plist (plist-put plist :date-timestamp-inactive
9871 (format-time-string
9872 (org-time-stamp-format t t) x)))))
9873 (let ((from (plist-get plist :from))
9874 (to (plist-get plist :to)))
9875 (when (and from to org-from-is-user-regexp)
9876 (setq plist
9877 (plist-put plist :fromto
9878 (if (string-match org-from-is-user-regexp from)
9879 (concat "to %t")
9880 (concat "from %f"))))))
9881 (setq org-store-link-plist plist))
9883 (defun org-add-link-props (&rest plist)
9884 "Add these properties to the link property list."
9885 (let (key value)
9886 (while plist
9887 (setq key (pop plist) value (pop plist))
9888 (setq org-store-link-plist
9889 (plist-put org-store-link-plist key value)))))
9891 (defun org-email-link-description (&optional fmt)
9892 "Return the description part of an email link.
9893 This takes information from `org-store-link-plist' and formats it
9894 according to FMT (default from `org-email-link-description-format')."
9895 (setq fmt (or fmt org-email-link-description-format))
9896 (let* ((p org-store-link-plist)
9897 (to (plist-get p :toaddress))
9898 (from (plist-get p :fromaddress))
9899 (table
9900 (list
9901 (cons "%c" (plist-get p :fromto))
9902 (cons "%F" (plist-get p :from))
9903 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9904 (cons "%T" (plist-get p :to))
9905 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9906 (cons "%s" (plist-get p :subject))
9907 (cons "%d" (plist-get p :date))
9908 (cons "%m" (plist-get p :message-id)))))
9909 (when (string-match "%c" fmt)
9910 ;; Check if the user wrote this message
9911 (if (and org-from-is-user-regexp from to
9912 (save-match-data (string-match org-from-is-user-regexp from)))
9913 (setq fmt (replace-match "to %t" t t fmt))
9914 (setq fmt (replace-match "from %f" t t fmt))))
9915 (org-replace-escapes fmt table)))
9917 (defun org-make-org-heading-search-string (&optional string)
9918 "Make search string for the current headline or STRING."
9919 (let ((s (or string
9920 (and (derived-mode-p 'org-mode)
9921 (save-excursion
9922 (org-back-to-heading t)
9923 (org-element-property :raw-value (org-element-at-point))))))
9924 (lines org-context-in-file-links))
9925 (unless string (setq s (concat "*" s))) ;Add * for headlines
9926 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9927 (when (and string (integerp lines) (> lines 0))
9928 (let ((slines (org-split-string s "\n")))
9929 (when (< lines (length slines))
9930 (setq s (mapconcat
9931 'identity
9932 (reverse (nthcdr (- (length slines) lines)
9933 (reverse slines))) "\n")))))
9934 (mapconcat #'identity (split-string s) " ")))
9936 (defun org-make-link-string (link &optional description)
9937 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9938 (unless (org-string-nw-p link) (error "Empty link"))
9939 (let ((uri (cond ((string-match org-link-types-re link)
9940 (concat (match-string 1 link)
9941 (org-link-escape (substring link (match-end 1)))))
9942 ;; For readability, url-encode internal links only
9943 ;; when absolutely needed (i.e, when they contain
9944 ;; square brackets). File links however, are
9945 ;; encoded since, e.g., spaces are significant.
9946 ((or (file-name-absolute-p link)
9947 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9948 (org-link-escape link))
9949 (t link)))
9950 (description
9951 (and (org-string-nw-p description)
9952 ;; Remove brackets from description, as they are fatal.
9953 (replace-regexp-in-string
9954 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9955 (org-trim description)))))
9956 (format "[[%s]%s]"
9958 (if description (format "[%s]" description) ""))))
9960 (defconst org-link-escape-chars
9961 ;;%20 %5B %5D %25
9962 '(?\s ?\[ ?\] ?%)
9963 "List of characters that should be escaped in a link when stored to Org.
9964 This is the list that is used for internal purposes.")
9966 (defun org-link-escape (text &optional table merge)
9967 "Return percent escaped representation of TEXT.
9968 TEXT is a string with the text to escape.
9969 Optional argument TABLE is a list with characters that should be
9970 escaped. When nil, `org-link-escape-chars' is used.
9971 If optional argument MERGE is set, merge TABLE into
9972 `org-link-escape-chars'."
9973 (let ((characters-to-encode
9974 (cond ((null table) org-link-escape-chars)
9975 (merge (append org-link-escape-chars table))
9976 (t table))))
9977 (mapconcat
9978 (lambda (c)
9979 (if (or (memq c characters-to-encode)
9980 (and org-url-hexify-p (or (< c 32) (> c 126))))
9981 (mapconcat (lambda (e) (format "%%%.2X" e))
9982 (or (encode-coding-char c 'utf-8)
9983 (error "Unable to percent escape character: %c" c))
9985 (char-to-string c)))
9986 text "")))
9988 (defun org-link-unescape (str)
9989 "Unhex hexified Unicode parts in string STR.
9990 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9991 reciprocal of `org-link-escape', which see."
9992 (if (org-string-nw-p str)
9993 (replace-regexp-in-string
9994 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9995 str))
9997 (defun org-link-unescape-compound (hex)
9998 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9999 Note: this function also decodes single byte encodings like
10000 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10001 (save-match-data
10002 (let* ((bytes (cdr (split-string hex "%")))
10003 (ret "")
10004 (eat 0)
10005 (sum 0))
10006 (while bytes
10007 (let* ((val (string-to-number (pop bytes) 16))
10008 (shift-xor
10009 (if (= 0 eat)
10010 (cond
10011 ((>= val 252) (cons 6 252))
10012 ((>= val 248) (cons 5 248))
10013 ((>= val 240) (cons 4 240))
10014 ((>= val 224) (cons 3 224))
10015 ((>= val 192) (cons 2 192))
10016 (t (cons 0 0)))
10017 (cons 6 128))))
10018 (when (>= val 192) (setq eat (car shift-xor)))
10019 (setq val (logxor val (cdr shift-xor)))
10020 (setq sum (+ (lsh sum (car shift-xor)) val))
10021 (when (> eat 0) (setq eat (- eat 1)))
10022 (cond
10023 ((= 0 eat) ;multi byte
10024 (setq ret (concat ret (char-to-string sum)))
10025 (setq sum 0))
10026 ((not bytes) ; single byte(s)
10027 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10028 ret)))
10030 (defun org-link-unescape-single-byte-sequence (hex)
10031 "Unhexify hex-encoded single byte character sequences."
10032 (mapconcat (lambda (byte)
10033 (char-to-string (string-to-number byte 16)))
10034 (cdr (split-string hex "%")) ""))
10036 (defun org-xor (a b)
10037 "Exclusive or."
10038 (if a (not b) b))
10040 (defun org-fixup-message-id-for-http (s)
10041 "Replace special characters in a message id, so it can be used in an http query."
10042 (when (string-match "%" s)
10043 (setq s (mapconcat (lambda (c)
10044 (if (eq c ?%)
10045 "%25"
10046 (char-to-string c)))
10047 s "")))
10048 (while (string-match "<" s)
10049 (setq s (replace-match "%3C" t t s)))
10050 (while (string-match ">" s)
10051 (setq s (replace-match "%3E" t t s)))
10052 (while (string-match "@" s)
10053 (setq s (replace-match "%40" t t s)))
10056 (defun org-link-prettify (link)
10057 "Return a human-readable representation of LINK.
10058 The car of LINK must be a raw link.
10059 The cdr of LINK must be either a link description or nil."
10060 (let ((desc (or (cadr link) "<no description>")))
10061 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10062 "<" (car link) ">")))
10064 ;;;###autoload
10065 (defun org-insert-link-global ()
10066 "Insert a link like Org mode does.
10067 This command can be called in any mode to insert a link in Org syntax."
10068 (interactive)
10069 (org-load-modules-maybe)
10070 (org-run-like-in-org-mode 'org-insert-link))
10072 (defun org-insert-all-links (arg &optional pre post)
10073 "Insert all links in `org-stored-links'.
10074 When a universal prefix, do not delete the links from `org-stored-links'.
10075 When `ARG' is a number, insert the last N link(s).
10076 `PRE' and `POST' are optional arguments to define a string to
10077 prepend or to append."
10078 (interactive "P")
10079 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10080 (links (copy-sequence org-stored-links))
10081 (pr (or pre "- "))
10082 (po (or post "\n"))
10083 (cnt 1) l)
10084 (if (null org-stored-links)
10085 (message "No link to insert")
10086 (while (and (or (listp arg) (>= arg cnt))
10087 (setq l (if (listp arg)
10088 (pop links)
10089 (pop org-stored-links))))
10090 (setq cnt (1+ cnt))
10091 (insert pr)
10092 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10093 (insert po)))))
10095 (defun org-insert-last-stored-link (arg)
10096 "Insert the last link stored in `org-stored-links'."
10097 (interactive "p")
10098 (org-insert-all-links arg "" "\n"))
10100 (defun org-link-fontify-links-to-this-file ()
10101 "Fontify links to the current file in `org-stored-links'."
10102 (let ((f (buffer-file-name)) a b)
10103 (setq a (mapcar (lambda(l)
10104 (let ((ll (car l)))
10105 (when (and (string-match "^file:\\(.+\\)::" ll)
10106 (equal f (expand-file-name (match-string 1 ll))))
10107 ll)))
10108 org-stored-links))
10109 (when (featurep 'org-id)
10110 (setq b (mapcar (lambda(l)
10111 (let ((ll (car l)))
10112 (when (and (string-match "^id:\\(.+\\)$" ll)
10113 (equal f (expand-file-name
10114 (or (org-id-find-id-file
10115 (match-string 1 ll)) ""))))
10116 ll)))
10117 org-stored-links)))
10118 (mapcar (lambda(l)
10119 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10120 (delq nil (append a b)))))
10122 (defvar org--links-history nil)
10123 (defun org-insert-link (&optional complete-file link-location default-description)
10124 "Insert a link. At the prompt, enter the link.
10126 Completion can be used to insert any of the link protocol prefixes in use.
10128 The history can be used to select a link previously stored with
10129 `org-store-link'. When the empty string is entered (i.e. if you just
10130 press `RET' at the prompt), the link defaults to the most recently
10131 stored link. As `SPC' triggers completion in the minibuffer, you need to
10132 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10134 You will also be prompted for a description, and if one is given, it will
10135 be displayed in the buffer instead of the link.
10137 If there is already a link at point, this command will allow you to edit
10138 link and description parts.
10140 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10141 file name can be
10142 selected using completion. The path to the file will be relative to the
10143 current directory if the file is in the current directory or a subdirectory.
10144 Otherwise, the link will be the absolute path as completed in the minibuffer
10145 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10146 option `org-link-file-path-type'.
10148 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10149 absolute path even if the file is in
10150 the current directory or below.
10152 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10153 prefix negates `org-keep-stored-link-after-insertion'.
10155 If the LINK-LOCATION parameter is non-nil, this value will be used as
10156 the link location instead of reading one interactively.
10158 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10159 be used as the default description. Otherwise, if
10160 `org-make-link-description-function' is non-nil, this function
10161 will be called with the link target, and the result will be the
10162 default link description."
10163 (interactive "P")
10164 (let* ((wcf (current-window-configuration))
10165 (origbuf (current-buffer))
10166 (region (when (org-region-active-p)
10167 (buffer-substring (region-beginning) (region-end))))
10168 (remove (and region (list (region-beginning) (region-end))))
10169 (desc region)
10170 (link link-location)
10171 (abbrevs org-link-abbrev-alist-local)
10172 entry all-prefixes auto-desc)
10173 (cond
10174 (link-location) ; specified by arg, just use it.
10175 ((org-in-regexp org-bracket-link-regexp 1)
10176 ;; We do have a link at point, and we are going to edit it.
10177 (setq remove (list (match-beginning 0) (match-end 0)))
10178 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10179 (setq link (read-string "Link: "
10180 (org-link-unescape
10181 (match-string-no-properties 1)))))
10182 ((or (org-in-regexp org-angle-link-re)
10183 (org-in-regexp org-plain-link-re))
10184 ;; Convert to bracket link
10185 (setq remove (list (match-beginning 0) (match-end 0))
10186 link (read-string "Link: "
10187 (org-unbracket-string "<" ">" (match-string 0)))))
10188 ((member complete-file '((4) (16)))
10189 ;; Completing read for file names.
10190 (setq link (org-file-complete-link complete-file)))
10192 ;; Read link, with completion for stored links.
10193 (org-link-fontify-links-to-this-file)
10194 (org-switch-to-buffer-other-window "*Org Links*")
10195 (with-current-buffer "*Org Links*"
10196 (erase-buffer)
10197 (insert "Insert a link.
10198 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10199 (when org-stored-links
10200 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10201 (insert (mapconcat 'org-link-prettify
10202 (reverse org-stored-links) "\n")))
10203 (goto-char (point-min)))
10204 (let ((cw (selected-window)))
10205 (select-window (get-buffer-window "*Org Links*" 'visible))
10206 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10207 (unless (pos-visible-in-window-p (point-max))
10208 (org-fit-window-to-buffer))
10209 (and (window-live-p cw) (select-window cw)))
10210 (setq all-prefixes (append (mapcar 'car abbrevs)
10211 (mapcar 'car org-link-abbrev-alist)
10212 (org-link-types)))
10213 (unwind-protect
10214 ;; Fake a link history, containing the stored links.
10215 (let ((org--links-history
10216 (append (mapcar #'car org-stored-links)
10217 org-insert-link-history)))
10218 (setq link
10219 (org-completing-read
10220 "Link: "
10221 (append
10222 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10223 (mapcar #'car org-stored-links))
10224 nil nil nil
10225 'org--links-history
10226 (caar org-stored-links)))
10227 (unless (org-string-nw-p link) (user-error "No link selected"))
10228 (dolist (l org-stored-links)
10229 (when (equal link (cadr l))
10230 (setq link (car l))
10231 (setq auto-desc t)))
10232 (when (or (member link all-prefixes)
10233 (and (equal ":" (substring link -1))
10234 (member (substring link 0 -1) all-prefixes)
10235 (setq link (substring link 0 -1))))
10236 (setq link (with-current-buffer origbuf
10237 (org-link-try-special-completion link)))))
10238 (set-window-configuration wcf)
10239 (kill-buffer "*Org Links*"))
10240 (setq entry (assoc link org-stored-links))
10241 (or entry (push link org-insert-link-history))
10242 (setq desc (or desc (nth 1 entry)))))
10244 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10245 (not org-keep-stored-link-after-insertion))
10246 (setq org-stored-links (delq (assoc link org-stored-links)
10247 org-stored-links)))
10249 (when (and (string-match org-plain-link-re link)
10250 (not (string-match org-ts-regexp link)))
10251 ;; URL-like link, normalize the use of angular brackets.
10252 (setq link (org-unbracket-string "<" ">" link)))
10254 ;; Check if we are linking to the current file with a search
10255 ;; option If yes, simplify the link by using only the search
10256 ;; option.
10257 (when (and buffer-file-name
10258 (let ((case-fold-search nil))
10259 (string-match "\\`file:\\(.+?\\)::" link)))
10260 (let ((path (match-string-no-properties 1 link))
10261 (search (substring-no-properties link (match-end 0))))
10262 (save-match-data
10263 (when (equal (file-truename buffer-file-name) (file-truename path))
10264 ;; We are linking to this same file, with a search option
10265 (setq link search)))))
10267 ;; Check if we can/should use a relative path. If yes, simplify the link
10268 (let ((case-fold-search nil))
10269 (when (string-match "\\`\\(file\\|docview\\):" link)
10270 (let* ((type (match-string-no-properties 0 link))
10271 (path (substring-no-properties link (match-end 0)))
10272 (origpath path))
10273 (cond
10274 ((or (eq org-link-file-path-type 'absolute)
10275 (equal complete-file '(16)))
10276 (setq path (abbreviate-file-name (expand-file-name path))))
10277 ((eq org-link-file-path-type 'noabbrev)
10278 (setq path (expand-file-name path)))
10279 ((eq org-link-file-path-type 'relative)
10280 (setq path (file-relative-name path)))
10282 (save-match-data
10283 (if (string-match (concat "^" (regexp-quote
10284 (expand-file-name
10285 (file-name-as-directory
10286 default-directory))))
10287 (expand-file-name path))
10288 ;; We are linking a file with relative path name.
10289 (setq path (substring (expand-file-name path)
10290 (match-end 0)))
10291 (setq path (abbreviate-file-name (expand-file-name path)))))))
10292 (setq link (concat type path))
10293 (when (equal desc origpath)
10294 (setq desc path)))))
10296 (unless auto-desc
10297 (let ((initial-input
10298 (cond
10299 (default-description)
10300 ((not org-make-link-description-function) desc)
10301 (t (condition-case nil
10302 (funcall org-make-link-description-function link desc)
10303 (error
10304 (message "Can't get link description from `%s'"
10305 (symbol-name org-make-link-description-function))
10306 (sit-for 2)
10307 nil))))))
10308 (setq desc (read-string "Description: " initial-input))))
10310 (unless (string-match "\\S-" desc) (setq desc nil))
10311 (when remove (apply 'delete-region remove))
10312 (insert (org-make-link-string link desc))
10313 ;; Redisplay so as the new link has proper invisible characters.
10314 (sit-for 0)))
10316 (defun org-link-try-special-completion (type)
10317 "If there is completion support for link type TYPE, offer it."
10318 (let ((fun (org-link-get-parameter type :complete)))
10319 (if (functionp fun)
10320 (funcall fun)
10321 (read-string "Link (no completion support): " (concat type ":")))))
10323 (defun org-file-complete-link (&optional arg)
10324 "Create a file link using completion."
10325 (let ((file (read-file-name "File: "))
10326 (pwd (file-name-as-directory (expand-file-name ".")))
10327 (pwd1 (file-name-as-directory (abbreviate-file-name
10328 (expand-file-name ".")))))
10329 (cond ((equal arg '(16))
10330 (concat "file:"
10331 (abbreviate-file-name (expand-file-name file))))
10332 ((string-match
10333 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10334 (concat "file:" (match-string 1 file)))
10335 ((string-match
10336 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10337 (expand-file-name file))
10338 (concat "file:"
10339 (match-string 1 (expand-file-name file))))
10340 (t (concat "file:" file)))))
10342 (defun org-completing-read (&rest args)
10343 "Completing-read with SPACE being a normal character."
10344 (let ((enable-recursive-minibuffers t)
10345 (minibuffer-local-completion-map
10346 (copy-keymap minibuffer-local-completion-map)))
10347 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10348 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10349 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10350 'org-time-stamp-inactive)
10351 (apply #'completing-read args)))
10353 ;;; Opening/following a link
10355 (defvar org-link-search-failed nil)
10357 (defvar org-open-link-functions nil
10358 "Hook for functions finding a plain text link.
10359 These functions must take a single argument, the link content.
10360 They will be called for links that look like [[link text][description]]
10361 when LINK TEXT does not have a protocol like \"http:\" and does not look
10362 like a filename (e.g. \"./blue.png\").
10364 These functions will be called *before* Org attempts to resolve the
10365 link by doing text searches in the current buffer - so if you want a
10366 link \"[[target]]\" to still find \"<<target>>\", your function should
10367 handle this as a special case.
10369 When the function does handle the link, it must return a non-nil value.
10370 If it decides that it is not responsible for this link, it must return
10371 nil to indicate that that Org can continue with other options like
10372 exact and fuzzy text search.")
10374 (defun org-next-link (&optional search-backward)
10375 "Move forward to the next link.
10376 If the link is in hidden text, expose it."
10377 (interactive "P")
10378 (when (and org-link-search-failed (eq this-command last-command))
10379 (goto-char (point-min))
10380 (message "Link search wrapped back to beginning of buffer"))
10381 (setq org-link-search-failed nil)
10382 (let* ((pos (point))
10383 (ct (org-context))
10384 (a (assq :link ct))
10385 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10386 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10387 ((looking-at org-any-link-re)
10388 ;; Don't stay stuck at link without an org-link face
10389 (forward-char (if search-backward -1 1))))
10390 (if (funcall srch-fun org-any-link-re nil t)
10391 (progn
10392 (goto-char (match-beginning 0))
10393 (when (org-invisible-p) (org-show-context)))
10394 (goto-char pos)
10395 (setq org-link-search-failed t)
10396 (message "No further link found"))))
10398 (defun org-previous-link ()
10399 "Move backward to the previous link.
10400 If the link is in hidden text, expose it."
10401 (interactive)
10402 (funcall 'org-next-link t))
10404 (defun org-translate-link (s)
10405 "Translate a link string if a translation function has been defined."
10406 (with-temp-buffer
10407 (insert (org-trim s))
10408 (org-trim (org-element-interpret-data (org-element-context)))))
10410 (defun org-translate-link-from-planner (type path)
10411 "Translate a link from Emacs Planner syntax so that Org can follow it.
10412 This is still an experimental function, your mileage may vary."
10413 (cond
10414 ((member type '("http" "https" "news" "ftp"))
10415 ;; standard Internet links are the same.
10416 nil)
10417 ((and (equal type "irc") (string-match "^//" path))
10418 ;; Planner has two / at the beginning of an irc link, we have 1.
10419 ;; We should have zero, actually....
10420 (setq path (substring path 1)))
10421 ((and (equal type "lisp") (string-match "^/" path))
10422 ;; Planner has a slash, we do not.
10423 (setq type "elisp" path (substring path 1)))
10424 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10425 ;; A typical message link. Planner has the id after the final slash,
10426 ;; we separate it with a hash mark
10427 (setq path (concat (match-string 1 path) "#"
10428 (org-unbracket-string "<" ">" (match-string 2 path))))))
10429 (cons type path))
10431 (defun org-find-file-at-mouse (ev)
10432 "Open file link or URL at mouse."
10433 (interactive "e")
10434 (mouse-set-point ev)
10435 (org-open-at-point 'in-emacs))
10437 (defun org-open-at-mouse (ev)
10438 "Open file link or URL at mouse.
10439 See the docstring of `org-open-file' for details."
10440 (interactive "e")
10441 (mouse-set-point ev)
10442 (when (eq major-mode 'org-agenda-mode)
10443 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10444 (org-open-at-point))
10446 (defvar org-window-config-before-follow-link nil
10447 "The window configuration before following a link.
10448 This is saved in case the need arises to restore it.")
10450 ;;;###autoload
10451 (defun org-open-at-point-global ()
10452 "Follow a link or time-stamp like Org mode does.
10453 This command can be called in any mode to follow an external link
10454 or a time-stamp that has Org mode syntax. Its behavior is
10455 undefined when called on internal links (e.g., fuzzy links).
10456 Raise an error when there is nothing to follow. "
10457 (interactive)
10458 (cond ((org-in-regexp org-any-link-re)
10459 (org-open-link-from-string (match-string-no-properties 0)))
10460 ((or (org-in-regexp org-ts-regexp-both nil t)
10461 (org-in-regexp org-tsr-regexp-both nil t))
10462 (org-follow-timestamp-link))
10463 (t (user-error "No link found"))))
10465 ;;;###autoload
10466 (defun org-open-link-from-string (s &optional arg reference-buffer)
10467 "Open a link in the string S, as if it was in Org mode."
10468 (interactive "sLink: \nP")
10469 (let ((reference-buffer (or reference-buffer (current-buffer))))
10470 (with-temp-buffer
10471 (let ((org-inhibit-startup (not reference-buffer)))
10472 (org-mode)
10473 (insert s)
10474 (goto-char (point-min))
10475 (when reference-buffer
10476 (setq org-link-abbrev-alist-local
10477 (with-current-buffer reference-buffer
10478 org-link-abbrev-alist-local)))
10479 (org-open-at-point arg reference-buffer)))))
10481 (defvar org-open-at-point-functions nil
10482 "Hook that is run when following a link at point.
10484 Functions in this hook must return t if they identify and follow
10485 a link at point. If they don't find anything interesting at point,
10486 they must return nil.")
10488 (defvar org-link-search-inhibit-query nil)
10489 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10490 (defun org--open-doi-link (path)
10491 "Open a \"doi\" type link.
10492 PATH is a the path to search for, as a string."
10493 (browse-url (url-encode-url (concat org-doi-server-url path))))
10495 (defun org--open-elisp-link (path)
10496 "Open a \"elisp\" type link.
10497 PATH is the sexp to evaluate, as a string."
10498 (let ((cmd path))
10499 (if (or (and (org-string-nw-p
10500 org-confirm-elisp-link-not-regexp)
10501 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10502 (not org-confirm-elisp-link-function)
10503 (funcall org-confirm-elisp-link-function
10504 (format "Execute \"%s\" as elisp? "
10505 (org-add-props cmd nil 'face 'org-warning))))
10506 (message "%s => %s" cmd
10507 (if (eq (string-to-char cmd) ?\()
10508 (eval (read cmd))
10509 (call-interactively (read cmd))))
10510 (user-error "Abort"))))
10512 (defun org--open-help-link (path)
10513 "Open a \"help\" type link.
10514 PATH is a symbol name, as a string."
10515 (pcase (intern path)
10516 ((and (pred fboundp) variable) (describe-function variable))
10517 ((and (pred boundp) function) (describe-variable function))
10518 (name (user-error "Unknown function or variable: %s" name))))
10520 (defun org--open-shell-link (path)
10521 "Open a \"shell\" type link.
10522 PATH is the command to execute, as a string."
10523 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10524 (cmd path))
10525 (if (or (and (org-string-nw-p
10526 org-confirm-shell-link-not-regexp)
10527 (string-match
10528 org-confirm-shell-link-not-regexp cmd))
10529 (not org-confirm-shell-link-function)
10530 (funcall org-confirm-shell-link-function
10531 (format "Execute \"%s\" in shell? "
10532 (org-add-props cmd nil
10533 'face 'org-warning))))
10534 (progn
10535 (message "Executing %s" cmd)
10536 (shell-command cmd buf)
10537 (when (featurep 'midnight)
10538 (setq clean-buffer-list-kill-buffer-names
10539 (cons (buffer-name buf)
10540 clean-buffer-list-kill-buffer-names))))
10541 (user-error "Abort"))))
10543 (defun org-open-at-point (&optional arg reference-buffer)
10544 "Open link, timestamp, footnote or tags at point.
10546 When point is on a link, follow it. Normally, files will be
10547 opened by an appropriate application. If the optional prefix
10548 argument ARG is non-nil, Emacs will visit the file. With
10549 a double prefix argument, try to open outside of Emacs, in the
10550 application the system uses for this file type.
10552 When point is on a timestamp, open the agenda at the day
10553 specified.
10555 When point is a footnote definition, move to the first reference
10556 found. If it is on a reference, move to the associated
10557 definition.
10559 When point is on a headline, display a list of every link in the
10560 entry, so it is possible to pick one, or all, of them. If point
10561 is on a tag, call `org-tags-view' instead.
10563 When optional argument REFERENCE-BUFFER is non-nil, it should
10564 specify a buffer from where the link search should happen. This
10565 is used internally by `org-open-link-from-string'.
10567 On top of syntactically correct links, this function will also
10568 try to open links and time-stamps in comments, example
10569 blocks... i.e., whenever point is on something looking like
10570 a timestamp or a link."
10571 (interactive "P")
10572 ;; On a code block, open block's results.
10573 (unless (call-interactively 'org-babel-open-src-block-result)
10574 (org-load-modules-maybe)
10575 (setq org-window-config-before-follow-link (current-window-configuration))
10576 (org-remove-occur-highlights nil nil t)
10577 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10578 (let* ((context
10579 ;; Only consider supported types, even if they are not
10580 ;; the closest one.
10581 (org-element-lineage
10582 (org-element-context)
10583 '(clock footnote-definition footnote-reference headline
10584 inlinetask link timestamp)
10586 (type (org-element-type context))
10587 (value (org-element-property :value context)))
10588 (cond
10589 ;; On a headline or an inlinetask, but not on a timestamp,
10590 ;; a link, a footnote reference.
10591 ((memq type '(headline inlinetask))
10592 (org-match-line org-complex-heading-regexp)
10593 (if (and (match-beginning 5)
10594 (>= (point) (match-beginning 5))
10595 (< (point) (match-end 5)))
10596 ;; On tags.
10597 (org-tags-view arg (substring (match-string 5) 0 -1))
10598 ;; Not on tags.
10599 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10600 (`(nil . ,_)
10601 (require 'org-attach)
10602 (org-attach-reveal 'if-exists))
10603 (`(,links . ,links-end)
10604 (dolist (link (if (stringp links) (list links) links))
10605 (search-forward link nil links-end)
10606 (goto-char (match-beginning 0))
10607 (org-open-at-point))))))
10608 ;; On a footnote reference or at definition's label.
10609 ((or (eq type 'footnote-reference)
10610 (and (eq type 'footnote-definition)
10611 (save-excursion
10612 ;; Do not validate action when point is on the
10613 ;; spaces right after the footnote label, in
10614 ;; order to be on par with behaviour on links.
10615 (skip-chars-forward " \t")
10616 (let ((begin
10617 (org-element-property :contents-begin context)))
10618 (if begin (< (point) begin)
10619 (= (org-element-property :post-affiliated context)
10620 (line-beginning-position)))))))
10621 (org-footnote-action))
10622 ;; No valid context. Ignore catch-all types like `headline'.
10623 ;; If point is on something looking like a link or
10624 ;; a time-stamp, try opening it. It may be useful in
10625 ;; comments, example blocks...
10626 ((memq type '(footnote-definition headline inlinetask nil))
10627 (call-interactively #'org-open-at-point-global))
10628 ;; On a clock line, make sure point is on the timestamp
10629 ;; before opening it.
10630 ((and (eq type 'clock)
10631 value
10632 (>= (point) (org-element-property :begin value))
10633 (<= (point) (org-element-property :end value)))
10634 (org-follow-timestamp-link))
10635 ;; Do nothing on white spaces after an object.
10636 ((>= (point)
10637 (save-excursion
10638 (goto-char (org-element-property :end context))
10639 (skip-chars-backward " \t")
10640 (point)))
10641 (user-error "No link found"))
10642 ((eq type 'timestamp) (org-follow-timestamp-link))
10643 ((eq type 'link)
10644 (let ((type (org-element-property :type context))
10645 (path (org-link-unescape (org-element-property :path context))))
10646 ;; Switch back to REFERENCE-BUFFER needed when called in
10647 ;; a temporary buffer through `org-open-link-from-string'.
10648 (with-current-buffer (or reference-buffer (current-buffer))
10649 (cond
10650 ((equal type "file")
10651 (if (string-match "[*?{]" (file-name-nondirectory path))
10652 (dired path)
10653 ;; Look into `org-link-parameters' in order to find
10654 ;; a DEDICATED-FUNCTION to open file. The function
10655 ;; will be applied on raw link instead of parsed
10656 ;; link due to the limitation in `org-add-link-type'
10657 ;; ("open" function called with a single argument).
10658 ;; If no such function is found, fallback to
10659 ;; `org-open-file'.
10660 (let* ((option (org-element-property :search-option context))
10661 (app (org-element-property :application context))
10662 (dedicated-function
10663 (org-link-get-parameter
10664 (if app (concat type "+" app) type)
10665 :follow)))
10666 (if dedicated-function
10667 (funcall dedicated-function
10668 (concat path
10669 (and option (concat "::" option))))
10670 (apply #'org-open-file
10671 path
10672 (cond (arg)
10673 ((equal app "emacs") 'emacs)
10674 ((equal app "sys") 'system))
10675 (cond ((not option) nil)
10676 ((string-match-p "\\`[0-9]+\\'" option)
10677 (list (string-to-number option)))
10678 (t (list nil
10679 (org-link-unescape option)))))))))
10680 ((functionp (org-link-get-parameter type :follow))
10681 (funcall (org-link-get-parameter type :follow) path))
10682 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10683 (unless (run-hook-with-args-until-success
10684 'org-open-link-functions path)
10685 (if (not arg) (org-mark-ring-push)
10686 (switch-to-buffer-other-window
10687 (org-get-buffer-for-internal-link (current-buffer))))
10688 (let ((destination
10689 (org-with-wide-buffer
10690 (if (equal type "radio")
10691 (org-search-radio-target
10692 (org-element-property :path context))
10693 (org-link-search
10694 (if (member type '("custom-id" "coderef"))
10695 (org-element-property :raw-link context)
10696 path)
10697 ;; Prevent fuzzy links from matching
10698 ;; themselves.
10699 (and (equal type "fuzzy")
10700 (+ 2 (org-element-property :begin context)))))
10701 (point))))
10702 (unless (and (<= (point-min) destination)
10703 (>= (point-max) destination))
10704 (widen))
10705 (goto-char destination))))
10706 (t (browse-url-at-point))))))
10707 (t (user-error "No link found")))))
10708 (run-hook-with-args 'org-follow-link-hook)))
10710 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10711 "Offer links in the current entry and return the selected link.
10712 If there is only one link, return it.
10713 If NTH is an integer, return the NTH link found.
10714 If ZERO is a string, check also this string for a link, and if
10715 there is one, return it."
10716 (with-current-buffer buffer
10717 (org-with-wide-buffer
10718 (goto-char marker)
10719 (let ((cnt ?0)
10720 have-zero end links link c)
10721 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10722 (push (match-string 0 zero) links)
10723 (setq cnt (1- cnt) have-zero t))
10724 (save-excursion
10725 (org-back-to-heading t)
10726 (setq end (save-excursion (outline-next-heading) (point)))
10727 (while (re-search-forward org-any-link-re end t)
10728 (push (match-string 0) links))
10729 (setq links (org-uniquify (reverse links))))
10730 (cond
10731 ((null links)
10732 (message "No links"))
10733 ((equal (length links) 1)
10734 (setq link (car links)))
10735 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10736 (setq link (nth (if have-zero nth (1- nth)) links)))
10737 (t ; we have to select a link
10738 (save-excursion
10739 (save-window-excursion
10740 (delete-other-windows)
10741 (with-output-to-temp-buffer "*Select Link*"
10742 (dolist (l links)
10743 (cond
10744 ((not (string-match org-bracket-link-regexp l))
10745 (princ (format "[%c] %s\n" (cl-incf cnt)
10746 (org-unbracket-string "<" ">" l))))
10747 ((match-end 3)
10748 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10749 (match-string 3 l) (match-string 1 l))))
10750 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10751 (match-string 1 l)))))))
10752 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10753 (message "Select link to open, RET to open all:")
10754 (setq c (read-char-exclusive))
10755 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10756 (when (equal c ?q) (user-error "Abort"))
10757 (if (equal c ?\C-m)
10758 (setq link links)
10759 (setq nth (- c ?0))
10760 (when have-zero (setq nth (1+ nth)))
10761 (unless (and (integerp nth) (>= (length links) nth))
10762 (user-error "Invalid link selection"))
10763 (setq link (nth (1- nth) links)))))
10764 (cons link end)))))
10766 ;; TODO: These functions are deprecated since `org-open-at-point'
10767 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10768 (defun org-open-file-with-system (path)
10769 "Open file at PATH using the system way of opening it."
10770 (org-open-file path 'system))
10771 (defun org-open-file-with-emacs (path)
10772 "Open file at PATH in Emacs."
10773 (org-open-file path 'emacs))
10776 ;;; File search
10778 (defvar org-create-file-search-functions nil
10779 "List of functions to construct the right search string for a file link.
10780 These functions are called in turn with point at the location to
10781 which the link should point.
10783 A function in the hook should first test if it would like to
10784 handle this file type, for example by checking the `major-mode'
10785 or the file extension. If it decides not to handle this file, it
10786 should just return nil to give other functions a chance. If it
10787 does handle the file, it must return the search string to be used
10788 when following the link. The search string will be part of the
10789 file link, given after a double colon, and `org-open-at-point'
10790 will automatically search for it. If special measures must be
10791 taken to make the search successful, another function should be
10792 added to the companion hook `org-execute-file-search-functions',
10793 which see.
10795 A function in this hook may also use `setq' to set the variable
10796 `description' to provide a suggestion for the descriptive text to
10797 be used for this link when it gets inserted into an Org buffer
10798 with \\[org-insert-link].")
10800 (defvar org-execute-file-search-functions nil
10801 "List of functions to execute a file search triggered by a link.
10803 Functions added to this hook must accept a single argument, the
10804 search string that was part of the file link, the part after the
10805 double colon. The function must first check if it would like to
10806 handle this search, for example by checking the `major-mode' or
10807 the file extension. If it decides not to handle this search, it
10808 should just return nil to give other functions a chance. If it
10809 does handle the search, it must return a non-nil value to keep
10810 other functions from trying.
10812 Each function can access the current prefix argument through the
10813 variable `current-prefix-arg'. Note that a single prefix is used
10814 to force opening a link in Emacs, so it may be good to only use a
10815 numeric or double prefix to guide the search function.
10817 In case this is needed, a function in this hook can also restore
10818 the window configuration before `org-open-at-point' was called using:
10820 (set-window-configuration org-window-config-before-follow-link)")
10822 (defun org-search-radio-target (target)
10823 "Search a radio target matching TARGET in current buffer.
10824 White spaces are not significant."
10825 (let ((re (format "<<<%s>>>"
10826 (mapconcat #'regexp-quote
10827 (split-string target)
10828 "[ \t]+\\(?:\n[ \t]*\\)?")))
10829 (origin (point)))
10830 (goto-char (point-min))
10831 (catch :radio-match
10832 (while (re-search-forward re nil t)
10833 (backward-char)
10834 (let ((object (org-element-context)))
10835 (when (eq (org-element-type object) 'radio-target)
10836 (goto-char (org-element-property :begin object))
10837 (org-show-context 'link-search)
10838 (throw :radio-match nil))))
10839 (goto-char origin)
10840 (user-error "No match for radio target: %s" target))))
10842 (defun org-link-search (s &optional avoid-pos stealth)
10843 "Search for a search string S.
10845 If S starts with \"#\", it triggers a custom ID search.
10847 If S is enclosed within parenthesis, it initiates a coderef
10848 search.
10850 If S is surrounded by forward slashes, it is interpreted as
10851 a regular expression. In Org mode files, this will create an
10852 `org-occur' sparse tree. In ordinary files, `occur' will be used
10853 to list matches. If the current buffer is in `dired-mode', grep
10854 will be used to search in all files.
10856 When AVOID-POS is given, ignore matches near that position.
10858 When optional argument STEALTH is non-nil, do not modify
10859 visibility around point, thus ignoring `org-show-context-detail'
10860 variable.
10862 Search is case-insensitive and ignores white spaces. Return type
10863 of matched result, which is either `dedicated' or `fuzzy'."
10864 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10865 (let* ((case-fold-search t)
10866 (origin (point))
10867 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10868 (starred (eq (string-to-char normalized) ?*))
10869 (words (split-string (if starred (substring s 1) s)))
10870 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10871 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10872 type)
10873 (cond
10874 ;; Check if there are any special search functions.
10875 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10876 ((eq (string-to-char s) ?#)
10877 ;; Look for a custom ID S if S starts with "#".
10878 (let* ((id (substring normalized 1))
10879 (match (org-find-property "CUSTOM_ID" id)))
10880 (if match (progn (goto-char match) (setf type 'dedicated))
10881 (error "No match for custom ID: %s" id))))
10882 ((string-match "\\`(\\(.*\\))\\'" normalized)
10883 ;; Look for coderef targets if S is enclosed within parenthesis.
10884 (let ((coderef (match-string-no-properties 1 normalized))
10885 (re (substring s-single-re 1 -1)))
10886 (goto-char (point-min))
10887 (catch :coderef-match
10888 (while (re-search-forward re nil t)
10889 (let ((element (org-element-at-point)))
10890 (when (and (memq (org-element-type element)
10891 '(example-block src-block))
10892 ;; Build proper regexp according to current
10893 ;; block's label format.
10894 (let ((label-fmt
10895 (regexp-quote
10896 (or (org-element-property :label-fmt element)
10897 org-coderef-label-format))))
10898 (save-excursion
10899 (beginning-of-line)
10900 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10901 (format label-fmt coderef))))))
10902 (setq type 'dedicated)
10903 (goto-char (match-beginning 1))
10904 (throw :coderef-match nil))))
10905 (goto-char origin)
10906 (error "No match for coderef: %s" coderef))))
10907 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10908 ;; Look for a regular expression.
10909 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10910 (match-string 1 s)))
10911 ;; From here, we handle fuzzy links.
10913 ;; Look for targets, only if not in a headline search.
10914 ((and (not starred)
10915 (let ((target (format "<<%s>>" s-multi-re)))
10916 (catch :target-match
10917 (goto-char (point-min))
10918 (while (re-search-forward target nil t)
10919 (backward-char)
10920 (let ((context (org-element-context)))
10921 (when (eq (org-element-type context) 'target)
10922 (setq type 'dedicated)
10923 (goto-char (org-element-property :begin context))
10924 (throw :target-match t))))
10925 nil))))
10926 ;; Look for elements named after S, only if not in a headline
10927 ;; search.
10928 ((and (not starred)
10929 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10930 (catch :name-match
10931 (goto-char (point-min))
10932 (while (re-search-forward name nil t)
10933 (let ((element (org-element-at-point)))
10934 (when (equal words
10935 (split-string
10936 (org-element-property :name element)))
10937 (setq type 'dedicated)
10938 (beginning-of-line)
10939 (throw :name-match t))))
10940 nil))))
10941 ;; Regular text search. Prefer headlines in Org mode buffers.
10942 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10943 ;; statistics cookies and tags.
10944 ((and (derived-mode-p 'org-mode)
10945 (let ((title-re
10946 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10947 org-outline-regexp-bol
10948 org-comment-string
10949 (mapconcat #'regexp-quote words ".+")))
10950 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10951 (comment-re (eval-when-compile
10952 (format "\\`%s[ \t]+" org-comment-string))))
10953 (goto-char (point-min))
10954 (catch :found
10955 (while (re-search-forward title-re nil t)
10956 (when (equal words
10957 (split-string
10958 (replace-regexp-in-string
10959 cookie-re ""
10960 (replace-regexp-in-string
10961 comment-re "" (org-get-heading t t t)))))
10962 (throw :found t)))
10963 nil)))
10964 (beginning-of-line)
10965 (setq type 'dedicated))
10966 ;; Offer to create non-existent headline depending on
10967 ;; `org-link-search-must-match-exact-headline'.
10968 ((and (derived-mode-p 'org-mode)
10969 (not org-link-search-inhibit-query)
10970 (eq org-link-search-must-match-exact-headline 'query-to-create)
10971 (yes-or-no-p "No match - create this as a new heading? "))
10972 (goto-char (point-max))
10973 (unless (bolp) (newline))
10974 (org-insert-heading nil t t)
10975 (insert s "\n")
10976 (beginning-of-line 0))
10977 ;; Only headlines are looked after. No need to process
10978 ;; further: throw an error.
10979 ((and (derived-mode-p 'org-mode)
10980 (or starred org-link-search-must-match-exact-headline))
10981 (goto-char origin)
10982 (error "No match for fuzzy expression: %s" normalized))
10983 ;; Regular text search.
10984 ((catch :fuzzy-match
10985 (goto-char (point-min))
10986 (while (re-search-forward s-multi-re nil t)
10987 ;; Skip match if it contains AVOID-POS or it is included in
10988 ;; a link with a description but outside the description.
10989 (unless (or (and avoid-pos
10990 (<= (match-beginning 0) avoid-pos)
10991 (> (match-end 0) avoid-pos))
10992 (and (save-match-data
10993 (org-in-regexp org-bracket-link-regexp))
10994 (match-beginning 3)
10995 (or (> (match-beginning 3) (point))
10996 (<= (match-end 3) (point)))
10997 (org-element-lineage
10998 (save-match-data (org-element-context))
10999 '(link) t)))
11000 (goto-char (match-beginning 0))
11001 (setq type 'fuzzy)
11002 (throw :fuzzy-match t)))
11003 nil))
11004 ;; All failed. Throw an error.
11005 (t (goto-char origin)
11006 (error "No match for fuzzy expression: %s" normalized)))
11007 ;; Disclose surroundings of match, if appropriate.
11008 (when (and (derived-mode-p 'org-mode) (not stealth))
11009 (org-show-context 'link-search))
11010 type))
11012 (defun org-get-buffer-for-internal-link (buffer)
11013 "Return a buffer to be used for displaying the link target of internal links."
11014 (cond
11015 ((not org-display-internal-link-with-indirect-buffer)
11016 buffer)
11017 ((string-suffix-p "(Clone)" (buffer-name buffer))
11018 (message "Buffer is already a clone, not making another one")
11019 ;; we also do not modify visibility in this case
11020 buffer)
11021 (t ; make a new indirect buffer for displaying the link
11022 (let* ((bn (buffer-name buffer))
11023 (ibn (concat bn "(Clone)"))
11024 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11025 (with-current-buffer ib (org-overview))
11026 ib))))
11028 (defun org-do-occur (regexp &optional cleanup)
11029 "Call the Emacs command `occur'.
11030 If CLEANUP is non-nil, remove the printout of the regular expression
11031 in the *Occur* buffer. This is useful if the regex is long and not useful
11032 to read."
11033 (occur regexp)
11034 (when cleanup
11035 (let ((cwin (selected-window)) win beg end)
11036 (when (setq win (get-buffer-window "*Occur*"))
11037 (select-window win))
11038 (goto-char (point-min))
11039 (when (re-search-forward "match[a-z]+" nil t)
11040 (setq beg (match-end 0))
11041 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11042 (setq end (1- (match-beginning 0)))))
11043 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11044 (goto-char (point-min))
11045 (select-window cwin))))
11047 ;;; The mark ring for links jumps
11049 (defvar org-mark-ring nil
11050 "Mark ring for positions before jumps in Org mode.")
11051 (defvar org-mark-ring-last-goto nil
11052 "Last position in the mark ring used to go back.")
11053 ;; Fill and close the ring
11054 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11055 (dotimes (_ org-mark-ring-length)
11056 (push (make-marker) org-mark-ring))
11057 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11058 org-mark-ring)
11060 (defun org-mark-ring-push (&optional pos buffer)
11061 "Put the current position or POS into the mark ring and rotate it."
11062 (interactive)
11063 (setq pos (or pos (point)))
11064 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11065 (move-marker (car org-mark-ring)
11066 (or pos (point))
11067 (or buffer (current-buffer)))
11068 (message "%s"
11069 (substitute-command-keys
11070 "Position saved to mark ring, go back with \
11071 `\\[org-mark-ring-goto]'.")))
11073 (defun org-mark-ring-goto (&optional n)
11074 "Jump to the previous position in the mark ring.
11075 With prefix arg N, jump back that many stored positions. When
11076 called several times in succession, walk through the entire ring.
11077 Org mode commands jumping to a different position in the current file,
11078 or to another Org file, automatically push the old position onto the ring."
11079 (interactive "p")
11080 (let (p m)
11081 (if (eq last-command this-command)
11082 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11083 (setq p org-mark-ring))
11084 (setq org-mark-ring-last-goto p)
11085 (setq m (car p))
11086 (pop-to-buffer-same-window (marker-buffer m))
11087 (goto-char m)
11088 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11090 (defun org-add-angle-brackets (s)
11091 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11092 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11095 ;;; Following specific links
11097 (defvar org-agenda-buffer-tmp-name)
11098 (defvar org-agenda-start-on-weekday)
11099 (defun org-follow-timestamp-link ()
11100 "Open an agenda view for the time-stamp date/range at point."
11101 (cond
11102 ((org-at-date-range-p t)
11103 (let ((org-agenda-start-on-weekday)
11104 (t1 (match-string 1))
11105 (t2 (match-string 2)) tt1 tt2)
11106 (setq tt1 (time-to-days (org-time-string-to-time t1))
11107 tt2 (time-to-days (org-time-string-to-time t2)))
11108 (let ((org-agenda-buffer-tmp-name
11109 (format "*Org Agenda(a:%s)"
11110 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11111 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11112 ((org-at-timestamp-p 'lax)
11113 (let ((org-agenda-buffer-tmp-name
11114 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11115 (org-agenda-list nil (time-to-days (org-time-string-to-time
11116 (substring (match-string 1) 0 10)))
11117 1)))
11118 (t (error "This should not happen"))))
11121 ;;; Following file links
11122 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11123 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11124 (declare-function mailcap-mime-info
11125 "mailcap" (string &optional request no-decode))
11126 (defvar org-wait nil)
11127 (defun org-open-file (path &optional in-emacs line search)
11128 "Open the file at PATH.
11129 First, this expands any special file name abbreviations. Then the
11130 configuration variable `org-file-apps' is checked if it contains an
11131 entry for this file type, and if yes, the corresponding command is launched.
11133 If no application is found, Emacs simply visits the file.
11135 With optional prefix argument IN-EMACS, Emacs will visit the file.
11136 With a double \\[universal-argument] \\[universal-argument] \
11137 prefix arg, Org tries to avoid opening in Emacs
11138 and to use an external application to visit the file.
11140 Optional LINE specifies a line to go to, optional SEARCH a string
11141 to search for. If LINE or SEARCH is given, the file will be
11142 opened in Emacs, unless an entry from org-file-apps that makes
11143 use of groups in a regexp matches.
11145 If you want to change the way frames are used when following a
11146 link, please customize `org-link-frame-setup'.
11148 If the file does not exist, an error is thrown."
11149 (let* ((file (if (equal path "")
11150 buffer-file-name
11151 (substitute-in-file-name (expand-file-name path))))
11152 (file-apps (append org-file-apps (org-default-apps)))
11153 (apps (cl-remove-if
11154 'org-file-apps-entry-match-against-dlink-p file-apps))
11155 (apps-dlink (cl-remove-if-not
11156 'org-file-apps-entry-match-against-dlink-p file-apps))
11157 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11158 (dirp (unless remp (file-directory-p file)))
11159 (file (if (and dirp org-open-directory-means-index-dot-org)
11160 (concat (file-name-as-directory file) "index.org")
11161 file))
11162 (a-m-a-p (assq 'auto-mode apps))
11163 (dfile (downcase file))
11164 ;; Reconstruct the original link from the PATH, LINE and
11165 ;; SEARCH args.
11166 (link (cond (line (concat file "::" (number-to-string line)))
11167 (search (concat file "::" search))
11168 (t file)))
11169 (dlink (downcase link))
11170 (ext
11171 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11172 (match-string 1 dfile)))
11173 (save-position-maybe
11174 (let ((old-buffer (current-buffer))
11175 (old-pos (point))
11176 (old-mode major-mode))
11177 (lambda ()
11178 (and (derived-mode-p 'org-mode)
11179 (eq old-mode 'org-mode)
11180 (or (not (eq old-buffer (current-buffer)))
11181 (not (eq old-pos (point))))
11182 (org-mark-ring-push old-pos old-buffer)))))
11183 cmd link-match-data)
11184 (cond
11185 ((member in-emacs '((16) system))
11186 (setq cmd (cdr (assq 'system apps))))
11187 (in-emacs (setq cmd 'emacs))
11189 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11190 (and dirp (cdr (assq 'directory apps)))
11191 ;; First, try matching against apps-dlink if we
11192 ;; get a match here, store the match data for
11193 ;; later.
11194 (let ((match (assoc-default dlink apps-dlink
11195 'string-match)))
11196 (if match
11197 (progn (setq link-match-data (match-data))
11198 match)
11199 (progn (setq in-emacs (or in-emacs line search))
11200 nil))) ; if we have no match in apps-dlink,
11201 ; always open the file in emacs if line or search
11202 ; is given (for backwards compatibility)
11203 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11204 'string-match)
11205 (cdr (assoc ext apps))
11206 (cdr (assq t apps))))))
11207 (when (eq cmd 'system)
11208 (setq cmd (cdr (assq 'system apps))))
11209 (when (eq cmd 'default)
11210 (setq cmd (cdr (assoc t apps))))
11211 (when (eq cmd 'mailcap)
11212 (require 'mailcap)
11213 (mailcap-parse-mailcaps)
11214 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11215 (command (mailcap-mime-info mime-type)))
11216 (if (stringp command)
11217 (setq cmd command)
11218 (setq cmd 'emacs))))
11219 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11220 (not (file-exists-p file))
11221 (not org-open-non-existing-files))
11222 (user-error "No such file: %s" file))
11223 (cond
11224 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11225 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11226 (while (string-match "['\"]%s['\"]" cmd)
11227 (setq cmd (replace-match "%s" t t cmd)))
11228 (setq cmd (replace-regexp-in-string
11229 "%s"
11230 (shell-quote-argument (convert-standard-filename file))
11232 nil t))
11234 ;; Replace "%1", "%2" etc. in command with group matches from regex
11235 (save-match-data
11236 (let ((match-index 1)
11237 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11238 (set-match-data link-match-data)
11239 (while (<= match-index number-of-groups)
11240 (let ((regex (concat "%" (number-to-string match-index)))
11241 (replace-with (match-string match-index dlink)))
11242 (while (string-match regex cmd)
11243 (setq cmd (replace-match replace-with t t cmd))))
11244 (setq match-index (+ match-index 1)))))
11246 (save-window-excursion
11247 (message "Running %s...done" cmd)
11248 (start-process-shell-command cmd nil cmd)
11249 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11250 ((or (stringp cmd)
11251 (eq cmd 'emacs))
11252 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11253 (widen)
11254 (cond (line (org-goto-line line)
11255 (when (derived-mode-p 'org-mode) (org-reveal)))
11256 (search (condition-case err
11257 (org-link-search search)
11258 ;; Save position before error-ing out so user
11259 ;; can easily move back to the original buffer.
11260 (error (funcall save-position-maybe)
11261 (error (nth 1 err)))))))
11262 ((functionp cmd)
11263 (save-match-data
11264 (set-match-data link-match-data)
11265 (condition-case nil
11266 (funcall cmd file link)
11267 ;; FIXME: Remove this check when most default installations
11268 ;; of Emacs have at least Org 9.0.
11269 ((debug wrong-number-of-arguments wrong-type-argument
11270 invalid-function)
11271 (user-error "Please see Org News for version 9.0 about \
11272 `org-file-apps'--Lisp error: %S" cmd)))))
11273 ((consp cmd)
11274 ;; FIXME: Remove this check when most default installations of
11275 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11276 ;; fall back to `org-link-frame-setup' for an old usage of
11277 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11278 (user-error "Please see Org News for version 9.0 about \
11279 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11280 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11281 (funcall save-position-maybe)))
11283 (defun org-file-apps-entry-match-against-dlink-p (entry)
11284 "This function returns non-nil if `entry' uses a regular
11285 expression which should be matched against the whole link by
11286 org-open-file.
11288 It assumes that is the case when the entry uses a regular
11289 expression which has at least one grouping construct and the
11290 action is either a lisp form or a command string containing
11291 `%1', i.e. using at least one subexpression match as a
11292 parameter."
11293 (let ((selector (car entry))
11294 (action (cdr entry)))
11295 (if (stringp selector)
11296 (and (> (regexp-opt-depth selector) 0)
11297 (or (and (stringp action)
11298 (string-match "%[0-9]" action))
11299 (consp action)))
11300 nil)))
11302 (defun org-default-apps ()
11303 "Return the default applications for this operating system."
11304 (cond
11305 ((eq system-type 'darwin)
11306 org-file-apps-defaults-macosx)
11307 ((eq system-type 'windows-nt)
11308 org-file-apps-defaults-windowsnt)
11309 (t org-file-apps-defaults-gnu)))
11311 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11312 "Convert extensions to regular expressions in the cars of LIST.
11313 Also, weed out any non-string entries, because the return value is used
11314 only for regexp matching.
11315 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11316 point to the symbol `emacs', indicating that the file should
11317 be opened in Emacs."
11318 (append
11319 (delq nil
11320 (mapcar (lambda (x)
11321 (unless (not (stringp (car x)))
11322 (if (string-match "\\W" (car x))
11324 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11325 list))
11326 (when add-auto-mode
11327 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11329 (defvar ange-ftp-name-format)
11330 (defun org-file-remote-p (file)
11331 "Test whether FILE specifies a location on a remote system.
11332 Return non-nil if the location is indeed remote.
11334 For example, the filename \"/user@host:/foo\" specifies a location
11335 on the system \"/user@host:\"."
11336 (cond ((fboundp 'file-remote-p)
11337 (file-remote-p file))
11338 ((fboundp 'tramp-handle-file-remote-p)
11339 (tramp-handle-file-remote-p file))
11340 ((and (boundp 'ange-ftp-name-format)
11341 (string-match (car ange-ftp-name-format) file))
11342 t)))
11345 ;;;; Refiling
11347 (defun org-get-org-file ()
11348 "Read a filename, with default directory `org-directory'."
11349 (let ((default (or org-default-notes-file remember-data-file)))
11350 (read-file-name (format "File name [%s]: " default)
11351 (file-name-as-directory org-directory)
11352 default)))
11354 (defun org-notes-order-reversed-p ()
11355 "Check if the current file should receive notes in reversed order."
11356 (cond
11357 ((not org-reverse-note-order) nil)
11358 ((eq t org-reverse-note-order) t)
11359 ((not (listp org-reverse-note-order)) nil)
11360 (t (catch 'exit
11361 (dolist (entry org-reverse-note-order)
11362 (when (string-match (car entry) buffer-file-name)
11363 (throw 'exit (cdr entry))))))))
11365 (defvar org-refile-target-table nil
11366 "The list of refile targets, created by `org-refile'.")
11368 (defvar org-agenda-new-buffers nil
11369 "Buffers created to visit agenda files.")
11371 (defvar org-refile-cache nil
11372 "Cache for refile targets.")
11374 (defvar org-refile-markers nil
11375 "All the markers used for caching refile locations.")
11377 (defun org-refile-marker (pos)
11378 "Get a new refile marker, but only if caching is in use."
11379 (if (not org-refile-use-cache)
11381 (let ((m (make-marker)))
11382 (move-marker m pos)
11383 (push m org-refile-markers)
11384 m)))
11386 (defun org-refile-cache-clear ()
11387 "Clear the refile cache and disable all the markers."
11388 (dolist (m org-refile-markers) (move-marker m nil))
11389 (setq org-refile-markers nil)
11390 (setq org-refile-cache nil)
11391 (message "Refile cache has been cleared"))
11393 (defun org-refile-cache-check-set (set)
11394 "Check if all the markers in the cache still have live buffers."
11395 (let (marker)
11396 (catch 'exit
11397 (while (and set (setq marker (nth 3 (pop set))))
11398 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11399 (when (and marker (null (marker-buffer marker)))
11400 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11401 (sit-for 3)
11402 (throw 'exit nil)))
11403 t)))
11405 (defun org-refile-cache-put (set &rest identifiers)
11406 "Push the refile targets SET into the cache, under IDENTIFIERS."
11407 (let* ((key (sha1 (prin1-to-string identifiers)))
11408 (entry (assoc key org-refile-cache)))
11409 (if entry
11410 (setcdr entry set)
11411 (push (cons key set) org-refile-cache))))
11413 (defun org-refile-cache-get (&rest identifiers)
11414 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11415 (cond
11416 ((not org-refile-cache) nil)
11417 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11419 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11420 org-refile-cache))))
11421 (and set (org-refile-cache-check-set set) set)))))
11423 (defvar org-outline-path-cache nil
11424 "Alist between buffer positions and outline paths.
11425 It value is an alist (POSITION . PATH) where POSITION is the
11426 buffer position at the beginning of an entry and PATH is a list
11427 of strings describing the outline path for that entry, in reverse
11428 order.")
11430 (defun org-refile-get-targets (&optional default-buffer)
11431 "Produce a table with refile targets."
11432 (let ((case-fold-search nil)
11433 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11434 (entries (or org-refile-targets '((nil . (:level . 1)))))
11435 targets tgs files desc descre)
11436 (message "Getting targets...")
11437 (with-current-buffer (or default-buffer (current-buffer))
11438 (dolist (entry entries)
11439 (setq files (car entry) desc (cdr entry))
11440 (cond
11441 ((null files) (setq files (list (current-buffer))))
11442 ((eq files 'org-agenda-files)
11443 (setq files (org-agenda-files 'unrestricted)))
11444 ((and (symbolp files) (fboundp files))
11445 (setq files (funcall files)))
11446 ((and (symbolp files) (boundp files))
11447 (setq files (symbol-value files))))
11448 (when (stringp files) (setq files (list files)))
11449 (cond
11450 ((eq (car desc) :tag)
11451 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11452 ((eq (car desc) :todo)
11453 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11454 ((eq (car desc) :regexp)
11455 (setq descre (cdr desc)))
11456 ((eq (car desc) :level)
11457 (setq descre (concat "^\\*\\{" (number-to-string
11458 (if org-odd-levels-only
11459 (1- (* 2 (cdr desc)))
11460 (cdr desc)))
11461 "\\}[ \t]")))
11462 ((eq (car desc) :maxlevel)
11463 (setq descre (concat "^\\*\\{1," (number-to-string
11464 (if org-odd-levels-only
11465 (1- (* 2 (cdr desc)))
11466 (cdr desc)))
11467 "\\}[ \t]")))
11468 (t (error "Bad refiling target description %s" desc)))
11469 (dolist (f files)
11470 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11472 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11473 (progn
11474 (when (bufferp f)
11475 (setq f (buffer-file-name (buffer-base-buffer f))))
11476 (setq f (and f (expand-file-name f)))
11477 (when (eq org-refile-use-outline-path 'file)
11478 (push (list (file-name-nondirectory f) f nil nil) tgs))
11479 (when (eq org-refile-use-outline-path 'buffer-name)
11480 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11481 (when (eq org-refile-use-outline-path 'full-file-path)
11482 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11483 (org-with-wide-buffer
11484 (goto-char (point-min))
11485 (setq org-outline-path-cache nil)
11486 (while (re-search-forward descre nil t)
11487 (beginning-of-line)
11488 (let ((case-fold-search nil))
11489 (looking-at org-complex-heading-regexp))
11490 (let ((begin (point))
11491 (heading (match-string-no-properties 4)))
11492 (unless (or (and
11493 org-refile-target-verify-function
11494 (not
11495 (funcall org-refile-target-verify-function)))
11496 (not heading))
11497 (let ((re (format org-complex-heading-regexp-format
11498 (regexp-quote heading)))
11499 (target
11500 (if (not org-refile-use-outline-path) heading
11501 (mapconcat
11502 #'identity
11503 (append
11504 (pcase org-refile-use-outline-path
11505 (`file (list (file-name-nondirectory
11506 (buffer-file-name
11507 (buffer-base-buffer)))))
11508 (`full-file-path
11509 (list (buffer-file-name
11510 (buffer-base-buffer))))
11511 (`buffer-name
11512 (list (buffer-name
11513 (buffer-base-buffer))))
11514 (_ nil))
11515 (mapcar (lambda (s) (replace-regexp-in-string
11516 "/" "\\/" s nil t))
11517 (org-get-outline-path t t)))
11518 "/"))))
11519 (push (list target f re (org-refile-marker (point)))
11520 tgs)))
11521 (when (= (point) begin)
11522 ;; Verification function has not moved point.
11523 (end-of-line)))))))
11524 (when org-refile-use-cache
11525 (org-refile-cache-put tgs (buffer-file-name) descre))
11526 (setq targets (append tgs targets))))))
11527 (message "Getting targets...done")
11528 (delete-dups (nreverse targets))))
11530 (defun org--get-outline-path-1 (&optional use-cache)
11531 "Return outline path to current headline.
11533 Outline path is a list of strings, in reverse order. When
11534 optional argument USE-CACHE is non-nil, make use of a cache. See
11535 `org-get-outline-path' for details.
11537 Assume buffer is widened and point is on a headline."
11538 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11539 (let ((p (point))
11540 (heading (let ((case-fold-search nil))
11541 (looking-at org-complex-heading-regexp)
11542 (if (not (match-end 4)) ""
11543 ;; Remove statistics cookies.
11544 (org-trim
11545 (org-link-display-format
11546 (replace-regexp-in-string
11547 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11548 (match-string-no-properties 4))))))))
11549 (if (org-up-heading-safe)
11550 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11551 (when use-cache
11552 (push (cons p path) org-outline-path-cache))
11553 path)
11554 ;; This is a new root node. Since we assume we are moving
11555 ;; forward, we can drop previous cache so as to limit number
11556 ;; of associations there.
11557 (let ((path (list heading)))
11558 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11559 path)))))
11561 (defun org-get-outline-path (&optional with-self use-cache)
11562 "Return the outline path to the current entry.
11564 An outline path is a list of ancestors for current headline, as
11565 a list of strings. Statistics cookies are removed and links are
11566 replaced with their description, if any, or their path otherwise.
11568 When optional argument WITH-SELF is non-nil, the path also
11569 includes the current headline.
11571 When optional argument USE-CACHE is non-nil, cache outline paths
11572 between calls to this function so as to avoid backtracking. This
11573 argument is useful when planning to find more than one outline
11574 path in the same document. In that case, there are two
11575 conditions to satisfy:
11576 - `org-outline-path-cache' is set to nil before starting the
11577 process;
11578 - outline paths are computed by increasing buffer positions."
11579 (org-with-wide-buffer
11580 (and (or (and with-self (org-back-to-heading t))
11581 (org-up-heading-safe))
11582 (reverse (org--get-outline-path-1 use-cache)))))
11584 (defun org-format-outline-path (path &optional width prefix separator)
11585 "Format the outline path PATH for display.
11586 WIDTH is the maximum number of characters that is available.
11587 PREFIX is a prefix to be included in the returned string,
11588 such as the file name.
11589 SEPARATOR is inserted between the different parts of the path,
11590 the default is \"/\"."
11591 (setq width (or width 79))
11592 (setq path (delq nil path))
11593 (unless (> width 0)
11594 (user-error "Argument `width' must be positive"))
11595 (setq separator (or separator "/"))
11596 (let* ((org-odd-levels-only nil)
11597 (fpath (concat
11598 prefix (and prefix path separator)
11599 (mapconcat
11600 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11601 (cl-loop for head in path
11602 for n from 0
11603 collect (org-add-props
11604 head nil 'face
11605 (nth (% n org-n-level-faces) org-level-faces)))
11606 separator))))
11607 (when (> (length fpath) width)
11608 (if (< width 7)
11609 ;; It's unlikely that `width' will be this small, but don't
11610 ;; waste characters by adding ".." if it is.
11611 (setq fpath (substring fpath 0 width))
11612 (setf (substring fpath (- width 2)) "..")))
11613 fpath))
11615 (defun org-display-outline-path (&optional file current separator just-return-string)
11616 "Display the current outline path in the echo area.
11618 If FILE is non-nil, prepend the output with the file name.
11619 If CURRENT is non-nil, append the current heading to the output.
11620 SEPARATOR is passed through to `org-format-outline-path'. It separates
11621 the different parts of the path and defaults to \"/\".
11622 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11623 (interactive "P")
11624 (let* (case-fold-search
11625 (bfn (buffer-file-name (buffer-base-buffer)))
11626 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11627 res)
11628 (when current (setq path (append path
11629 (save-excursion
11630 (org-back-to-heading t)
11631 (when (looking-at org-complex-heading-regexp)
11632 (list (match-string 4)))))))
11633 (setq res
11634 (org-format-outline-path
11635 path
11636 (1- (frame-width))
11637 (and file bfn (concat (file-name-nondirectory bfn) separator))
11638 separator))
11639 (if just-return-string
11640 (org-no-properties res)
11641 (org-unlogged-message "%s" res))))
11643 (defvar org-refile-history nil
11644 "History for refiling operations.")
11646 (defvar org-after-refile-insert-hook nil
11647 "Hook run after `org-refile' has inserted its stuff at the new location.
11648 Note that this is still *before* the stuff will be removed from
11649 the *old* location.")
11651 (defvar org-capture-last-stored-marker)
11652 (defvar org-refile-keep nil
11653 "Non-nil means `org-refile' will copy instead of refile.")
11655 (defun org-copy ()
11656 "Like `org-refile', but copy."
11657 (interactive)
11658 (let ((org-refile-keep t))
11659 (funcall 'org-refile nil nil nil "Copy")))
11661 (defun org-refile (&optional arg default-buffer rfloc msg)
11662 "Move the entry or entries at point to another heading.
11664 The list of target headings is compiled using the information in
11665 `org-refile-targets', which see.
11667 At the target location, the entry is filed as a subitem of the
11668 target heading. Depending on `org-reverse-note-order', the new
11669 subitem will either be the first or the last subitem.
11671 If there is an active region, all entries in that region will be
11672 refiled. However, the region must fulfill the requirement that
11673 the first heading sets the top-level of the moved text.
11675 With a `\\[universal-argument]' ARG, the command will only visit the target \
11676 location
11677 and not actually move anything.
11679 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11680 location where the last
11681 refiling operation has put the subtree.
11683 With a numeric prefix argument of `2', refile to the running clock.
11685 With a numeric prefix argument of `3', emulate `org-refile-keep'
11686 being set to t and copy to the target location, don't move it.
11687 Beware that keeping refiled entries may result in duplicated ID
11688 properties.
11690 RFLOC can be a refile location obtained in a different way.
11692 MSG is a string to replace \"Refile\" in the default prompt with
11693 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11695 See also `org-refile-use-outline-path'.
11697 If you are using target caching (see `org-refile-use-cache'), you
11698 have to clear the target cache in order to find new targets.
11699 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11700 prefix argument (`C-u C-u C-u C-c C-w')."
11701 (interactive "P")
11702 (if (member arg '(0 (64)))
11703 (org-refile-cache-clear)
11704 (let* ((actionmsg (cond (msg msg)
11705 ((equal arg 3) "Refile (and keep)")
11706 (t "Refile")))
11707 (regionp (org-region-active-p))
11708 (region-start (and regionp (region-beginning)))
11709 (region-end (and regionp (region-end)))
11710 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11711 pos it nbuf file level reversed)
11712 (setq last-command nil)
11713 (when regionp
11714 (goto-char region-start)
11715 (or (bolp) (goto-char (point-at-bol)))
11716 (setq region-start (point))
11717 (unless (or (org-kill-is-subtree-p
11718 (buffer-substring region-start region-end))
11719 (prog1 org-refile-active-region-within-subtree
11720 (let ((s (point-at-eol)))
11721 (org-toggle-heading)
11722 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11723 (user-error "The region is not a (sequence of) subtree(s)")))
11724 (if (equal arg '(16))
11725 (org-refile-goto-last-stored)
11726 (when (or
11727 (and (equal arg 2)
11728 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11729 (prog1
11730 (setq it (list (or org-clock-heading "running clock")
11731 (buffer-file-name
11732 (marker-buffer org-clock-hd-marker))
11734 (marker-position org-clock-hd-marker)))
11735 (setq arg nil)))
11736 (setq it
11737 (or rfloc
11738 (let (heading-text)
11739 (save-excursion
11740 (unless (and arg (listp arg))
11741 (org-back-to-heading t)
11742 (setq heading-text
11743 (replace-regexp-in-string
11744 org-bracket-link-regexp
11745 "\\3"
11746 (or (nth 4 (org-heading-components))
11747 ""))))
11748 (org-refile-get-location
11749 (cond ((and arg (listp arg)) "Goto")
11750 (regionp (concat actionmsg " region to"))
11751 (t (concat actionmsg " subtree \""
11752 heading-text "\" to")))
11753 default-buffer
11754 (and (not (equal '(4) arg))
11755 org-refile-allow-creating-parent-nodes)))))))
11756 (setq file (nth 1 it)
11757 pos (nth 3 it))
11758 (when (and (not arg)
11760 (equal (buffer-file-name) file)
11761 (if regionp
11762 (and (>= pos region-start)
11763 (<= pos region-end))
11764 (and (>= pos (point))
11765 (< pos (save-excursion
11766 (org-end-of-subtree t t))))))
11767 (error "Cannot refile to position inside the tree or region"))
11768 (setq nbuf (or (find-buffer-visiting file)
11769 (find-file-noselect file)))
11770 (if (and arg (not (equal arg 3)))
11771 (progn
11772 (pop-to-buffer-same-window nbuf)
11773 (goto-char (cond (pos)
11774 ((org-notes-order-reversed-p) (point-min))
11775 (t (point-max))))
11776 (org-show-context 'org-goto))
11777 (if regionp
11778 (progn
11779 (org-kill-new (buffer-substring region-start region-end))
11780 (org-save-markers-in-region region-start region-end))
11781 (org-copy-subtree 1 nil t))
11782 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11783 (find-file-noselect file)))
11784 (setq reversed (org-notes-order-reversed-p))
11785 (org-with-wide-buffer
11786 (if pos
11787 (progn
11788 (goto-char pos)
11789 (setq level (org-get-valid-level (funcall outline-level) 1))
11790 (goto-char
11791 (if reversed
11792 (or (outline-next-heading) (point-max))
11793 (or (save-excursion (org-get-next-sibling))
11794 (org-end-of-subtree t t)
11795 (point-max)))))
11796 (setq level 1)
11797 (if (not reversed)
11798 (goto-char (point-max))
11799 (goto-char (point-min))
11800 (or (outline-next-heading) (goto-char (point-max)))))
11801 (unless (bolp) (newline))
11802 (org-paste-subtree level nil nil t)
11803 (when org-log-refile
11804 (org-add-log-setup 'refile nil nil org-log-refile)
11805 (unless (eq org-log-refile 'note)
11806 (save-excursion (org-add-log-note))))
11807 (and org-auto-align-tags
11808 (let ((org-loop-over-headlines-in-active-region nil))
11809 (org-set-tags nil t)))
11810 (let ((bookmark-name (plist-get org-bookmark-names-plist
11811 :last-refile)))
11812 (when bookmark-name
11813 (with-demoted-errors
11814 (bookmark-set bookmark-name))))
11815 ;; If we are refiling for capture, make sure that the
11816 ;; last-capture pointers point here
11817 (when (bound-and-true-p org-capture-is-refiling)
11818 (let ((bookmark-name (plist-get org-bookmark-names-plist
11819 :last-capture-marker)))
11820 (when bookmark-name
11821 (with-demoted-errors
11822 (bookmark-set bookmark-name))))
11823 (move-marker org-capture-last-stored-marker (point)))
11824 (when (fboundp 'deactivate-mark) (deactivate-mark))
11825 (run-hooks 'org-after-refile-insert-hook)))
11826 (unless org-refile-keep
11827 (if regionp
11828 (delete-region (point) (+ (point) (- region-end region-start)))
11829 (delete-region
11830 (and (org-back-to-heading t) (point))
11831 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11832 (when (featurep 'org-inlinetask)
11833 (org-inlinetask-remove-END-maybe))
11834 (setq org-markers-to-move nil)
11835 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11837 (defun org-refile-goto-last-stored ()
11838 "Go to the location where the last refile was stored."
11839 (interactive)
11840 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11841 (message "This is the location of the last refile"))
11843 (defun org-refile--get-location (refloc tbl)
11844 "When user refile to REFLOC, find the associated target in TBL.
11845 Also check `org-refile-target-table'."
11846 (car (delq
11848 (mapcar
11849 (lambda (r) (or (assoc r tbl)
11850 (assoc r org-refile-target-table)))
11851 (list (replace-regexp-in-string "/$" "" refloc)
11852 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11854 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11855 "Prompt the user for a refile location, using PROMPT.
11856 PROMPT should not be suffixed with a colon and a space, because
11857 this function appends the default value from
11858 `org-refile-history' automatically, if that is not empty."
11859 (let ((org-refile-targets org-refile-targets)
11860 (org-refile-use-outline-path org-refile-use-outline-path))
11861 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11862 (unless org-refile-target-table
11863 (user-error "No refile targets"))
11864 (let* ((cbuf (current-buffer))
11865 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11866 (cfunc (if (and org-refile-use-outline-path
11867 org-outline-path-complete-in-steps)
11868 #'org-olpath-completing-read
11869 #'completing-read))
11870 (extra (if org-refile-use-outline-path "/" ""))
11871 (cbnex (concat (buffer-name) extra))
11872 (filename (and cfn (expand-file-name cfn)))
11873 (tbl (mapcar
11874 (lambda (x)
11875 (if (and (not (member org-refile-use-outline-path
11876 '(file full-file-path)))
11877 (not (equal filename (nth 1 x))))
11878 (cons (concat (car x) extra " ("
11879 (file-name-nondirectory (nth 1 x)) ")")
11880 (cdr x))
11881 (cons (concat (car x) extra) (cdr x))))
11882 org-refile-target-table))
11883 (completion-ignore-case t)
11884 cdef
11885 (prompt (concat prompt
11886 (or (and (car org-refile-history)
11887 (concat " (default " (car org-refile-history) ")"))
11888 (and (assoc cbnex tbl) (setq cdef cbnex)
11889 (concat " (default " cbnex ")"))) ": "))
11890 pa answ parent-target child parent old-hist)
11891 (setq old-hist org-refile-history)
11892 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11893 nil 'org-refile-history (or cdef (car org-refile-history))))
11894 (if (setq pa (org-refile--get-location answ tbl))
11895 (progn
11896 (org-refile-check-position pa)
11897 (when (or (not org-refile-history)
11898 (not (eq old-hist org-refile-history))
11899 (not (equal (car pa) (car org-refile-history))))
11900 (setq org-refile-history
11901 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11902 org-refile-history
11903 (cdr org-refile-history))))
11904 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11905 (pop org-refile-history)))
11907 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11908 (progn
11909 (setq parent (match-string 1 answ)
11910 child (match-string 2 answ))
11911 (setq parent-target (org-refile--get-location parent tbl))
11912 (when (and parent-target
11913 (or (eq new-nodes t)
11914 (and (eq new-nodes 'confirm)
11915 (y-or-n-p (format "Create new node \"%s\"? "
11916 child)))))
11917 (org-refile-new-child parent-target child)))
11918 (user-error "Invalid target location")))))
11920 (declare-function org-string-nw-p "org-macs" (s))
11921 (defun org-refile-check-position (refile-pointer)
11922 "Check if the refile pointer matches the headline to which it points."
11923 (let* ((file (nth 1 refile-pointer))
11924 (re (nth 2 refile-pointer))
11925 (pos (nth 3 refile-pointer))
11926 buffer)
11927 (if (and (not (markerp pos)) (not file))
11928 (user-error "Please indicate a target file in the refile path")
11929 (when (org-string-nw-p re)
11930 (setq buffer (if (markerp pos)
11931 (marker-buffer pos)
11932 (or (find-buffer-visiting file)
11933 (find-file-noselect file))))
11934 (with-current-buffer buffer
11935 (org-with-wide-buffer
11936 (goto-char pos)
11937 (beginning-of-line 1)
11938 (unless (looking-at-p re)
11939 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11941 (defun org-refile-new-child (parent-target child)
11942 "Use refile target PARENT-TARGET to add new CHILD below it."
11943 (unless parent-target
11944 (error "Cannot find parent for new node"))
11945 (let ((file (nth 1 parent-target))
11946 (pos (nth 3 parent-target))
11947 level)
11948 (with-current-buffer (or (find-buffer-visiting file)
11949 (find-file-noselect file))
11950 (org-with-wide-buffer
11951 (if pos
11952 (goto-char pos)
11953 (goto-char (point-max))
11954 (unless (bolp) (newline)))
11955 (when (looking-at org-outline-regexp)
11956 (setq level (funcall outline-level))
11957 (org-end-of-subtree t t))
11958 (org-back-over-empty-lines)
11959 (insert "\n" (make-string
11960 (if pos (org-get-valid-level level 1) 1) ?*)
11961 " " child "\n")
11962 (beginning-of-line 0)
11963 (list (concat (car parent-target) "/" child) file "" (point))))))
11965 (defun org-olpath-completing-read (prompt collection &rest args)
11966 "Read an outline path like a file name."
11967 (let ((thetable collection))
11968 (apply #'completing-read
11969 prompt
11970 (lambda (string predicate &optional flag)
11971 (cond
11972 ((eq flag nil) (try-completion string thetable))
11973 ((eq flag t)
11974 (let ((l (length string)))
11975 (mapcar (lambda (x)
11976 (let ((r (substring x l))
11977 (f (if (string-match " ([^)]*)$" x)
11978 (match-string 0 x)
11979 "")))
11980 (if (string-match "/" r)
11981 (concat string (substring r 0 (match-end 0)) f)
11982 x)))
11983 (all-completions string thetable predicate))))
11984 ;; Exact match?
11985 ((eq flag 'lambda) (assoc string thetable))))
11986 args)))
11988 ;;;; Dynamic blocks
11990 (defun org-find-dblock (name)
11991 "Find the first dynamic block with name NAME in the buffer.
11992 If not found, stay at current position and return nil."
11993 (let ((case-fold-search t) pos)
11994 (save-excursion
11995 (goto-char (point-min))
11996 (setq pos (and (re-search-forward
11997 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11998 (match-beginning 0))))
11999 (when pos (goto-char pos))
12000 pos))
12002 (defun org-create-dblock (plist)
12003 "Create a dynamic block section, with parameters taken from PLIST.
12004 PLIST must contain a :name entry which is used as the name of the block."
12005 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12006 (end-of-line 1)
12007 (newline))
12008 (let ((col (current-column))
12009 (name (plist-get plist :name)))
12010 (insert "#+BEGIN: " name)
12011 (while plist
12012 (if (eq (car plist) :name)
12013 (setq plist (cddr plist))
12014 (insert " " (prin1-to-string (pop plist)))))
12015 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12016 (beginning-of-line -2)))
12018 (defun org-prepare-dblock ()
12019 "Prepare dynamic block for refresh.
12020 This empties the block, puts the cursor at the insert position and returns
12021 the property list including an extra property :name with the block name."
12022 (unless (looking-at org-dblock-start-re)
12023 (user-error "Not at a dynamic block"))
12024 (let* ((begdel (1+ (match-end 0)))
12025 (name (org-no-properties (match-string 1)))
12026 (params (append (list :name name)
12027 (read (concat "(" (match-string 3) ")")))))
12028 (save-excursion
12029 (beginning-of-line 1)
12030 (skip-chars-forward " \t")
12031 (setq params (plist-put params :indentation-column (current-column))))
12032 (unless (re-search-forward org-dblock-end-re nil t)
12033 (error "Dynamic block not terminated"))
12034 (setq params
12035 (append params
12036 (list :content (buffer-substring
12037 begdel (match-beginning 0)))))
12038 (delete-region begdel (match-beginning 0))
12039 (goto-char begdel)
12040 (open-line 1)
12041 params))
12043 (defun org-map-dblocks (&optional command)
12044 "Apply COMMAND to all dynamic blocks in the current buffer.
12045 If COMMAND is not given, use `org-update-dblock'."
12046 (let ((cmd (or command 'org-update-dblock)))
12047 (save-excursion
12048 (goto-char (point-min))
12049 (while (re-search-forward org-dblock-start-re nil t)
12050 (goto-char (match-beginning 0))
12051 (save-excursion
12052 (condition-case nil
12053 (funcall cmd)
12054 (error (message "Error during update of dynamic block"))))
12055 (unless (re-search-forward org-dblock-end-re nil t)
12056 (error "Dynamic block not terminated"))))))
12058 (defun org-dblock-update (&optional arg)
12059 "User command for updating dynamic blocks.
12060 Update the dynamic block at point. With prefix ARG, update all dynamic
12061 blocks in the buffer."
12062 (interactive "P")
12063 (if arg
12064 (org-update-all-dblocks)
12065 (or (looking-at org-dblock-start-re)
12066 (org-beginning-of-dblock))
12067 (org-update-dblock)))
12069 (defun org-update-dblock ()
12070 "Update the dynamic block at point.
12071 This means to empty the block, parse for parameters and then call
12072 the correct writing function."
12073 (interactive)
12074 (save-excursion
12075 (let* ((win (selected-window))
12076 (pos (point))
12077 (line (org-current-line))
12078 (params (org-prepare-dblock))
12079 (name (plist-get params :name))
12080 (indent (plist-get params :indentation-column))
12081 (cmd (intern (concat "org-dblock-write:" name))))
12082 (message "Updating dynamic block `%s' at line %d..." name line)
12083 (funcall cmd params)
12084 (message "Updating dynamic block `%s' at line %d...done" name line)
12085 (goto-char pos)
12086 (when (and indent (> indent 0))
12087 (setq indent (make-string indent ?\ ))
12088 (save-excursion
12089 (select-window win)
12090 (org-beginning-of-dblock)
12091 (forward-line 1)
12092 (while (not (looking-at org-dblock-end-re))
12093 (insert indent)
12094 (beginning-of-line 2))
12095 (when (looking-at org-dblock-end-re)
12096 (and (looking-at "[ \t]+")
12097 (replace-match ""))
12098 (insert indent)))))))
12100 (defun org-beginning-of-dblock ()
12101 "Find the beginning of the dynamic block at point.
12102 Error if there is no such block at point."
12103 (let ((pos (point))
12104 beg)
12105 (end-of-line 1)
12106 (if (and (re-search-backward org-dblock-start-re nil t)
12107 (setq beg (match-beginning 0))
12108 (re-search-forward org-dblock-end-re nil t)
12109 (> (match-end 0) pos))
12110 (goto-char beg)
12111 (goto-char pos)
12112 (error "Not in a dynamic block"))))
12114 (defun org-update-all-dblocks ()
12115 "Update all dynamic blocks in the buffer.
12116 This function can be used in a hook."
12117 (interactive)
12118 (when (derived-mode-p 'org-mode)
12119 (org-map-dblocks 'org-update-dblock)))
12122 ;;;; Completion
12124 (declare-function org-export-backend-options "ox" (cl-x) t)
12125 (defun org-get-export-keywords ()
12126 "Return a list of all currently understood export keywords.
12127 Export keywords include options, block names, attributes and
12128 keywords relative to each registered export back-end."
12129 (let (keywords)
12130 (dolist (backend
12131 (bound-and-true-p org-export-registered-backends)
12132 (delq nil keywords))
12133 ;; Back-end name (for keywords, like #+LATEX:)
12134 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12135 (dolist (option-entry (org-export-backend-options backend))
12136 ;; Back-end options.
12137 (push (nth 1 option-entry) keywords)))))
12139 (defconst org-options-keywords
12140 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12141 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12142 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12143 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12144 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12146 (defcustom org-structure-template-alist
12147 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12148 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12149 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12150 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12151 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12152 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12153 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12154 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12155 ("L" "#+LaTeX: ")
12156 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12157 ("H" "#+HTML: ")
12158 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12159 ("A" "#+ASCII: ")
12160 ("i" "#+INDEX: ?")
12161 ("I" "#+INCLUDE: %file ?"))
12162 "Structure completion elements.
12163 This is a list of abbreviation keys and values. The value gets inserted
12164 if you type `<' followed by the key and then press the completion key,
12165 usually `TAB'. %file will be replaced by a file name after prompting
12166 for the file using completion. The cursor will be placed at the position
12167 of the `?' in the template.
12168 There are two templates for each key, the first uses the original Org syntax,
12169 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12170 the default when the /org-mtags.el/ module has been loaded. See also the
12171 variable `org-mtags-prefer-muse-templates'."
12172 :group 'org-completion
12173 :type '(repeat
12174 (list
12175 (string :tag "Key")
12176 (string :tag "Template")))
12177 :version "26.1"
12178 :package-version '(Org . "8.3"))
12180 (defun org-try-structure-completion ()
12181 "Try to complete a structure template before point.
12182 This looks for strings like \"<e\" on an otherwise empty line and
12183 expands them."
12184 (let ((l (buffer-substring (point-at-bol) (point)))
12186 (when (and (looking-at "[ \t]*$")
12187 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12188 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12189 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12190 (match-beginning 1)) a)
12191 t)))
12193 (defun org-complete-expand-structure-template (start cell)
12194 "Expand a structure template."
12195 (let ((rpl (nth 1 cell))
12196 (ind ""))
12197 (delete-region start (point))
12198 (when (string-match "\\`[ \t]*#\\+" rpl)
12199 (cond
12200 ((bolp))
12201 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12202 (setq ind (buffer-substring (point-at-bol) (point))))
12203 (t (newline))))
12204 (setq start (point))
12205 (when (string-match "%file" rpl)
12206 (setq rpl (replace-match
12207 (concat
12208 "\""
12209 (save-match-data
12210 (abbreviate-file-name (read-file-name "Include file: ")))
12211 "\"")
12212 t t rpl)))
12213 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12214 (concat "\n" ind)))
12215 (insert rpl)
12216 (when (re-search-backward "\\?" start t) (delete-char 1))))
12218 ;;;; TODO, DEADLINE, Comments
12220 (defun org-toggle-comment ()
12221 "Change the COMMENT state of an entry."
12222 (interactive)
12223 (save-excursion
12224 (org-back-to-heading)
12225 (let ((case-fold-search nil))
12226 (looking-at org-complex-heading-regexp))
12227 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12228 (skip-chars-forward " \t")
12229 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12230 (if (org-in-commented-heading-p t)
12231 (delete-region (point)
12232 (progn (search-forward " " (line-end-position) 'move)
12233 (skip-chars-forward " \t")
12234 (point)))
12235 (insert org-comment-string)
12236 (unless (eolp) (insert " ")))))
12238 (defvar org-last-todo-state-is-todo nil
12239 "This is non-nil when the last TODO state change led to a TODO state.
12240 If the last change removed the TODO tag or switched to DONE, then
12241 this is nil.")
12243 (defvar org-setting-tags nil) ; dynamically skipped
12245 (defvar org-todo-setup-filter-hook nil
12246 "Hook for functions that pre-filter todo specs.
12247 Each function takes a todo spec and returns either nil or the spec
12248 transformed into canonical form." )
12250 (defvar org-todo-get-default-hook nil
12251 "Hook for functions that get a default item for todo.
12252 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12253 nil or a string to be used for the todo mark." )
12255 (defvar org-agenda-headline-snapshot-before-repeat)
12257 (defun org-current-effective-time ()
12258 "Return current time adjusted for `org-extend-today-until' variable."
12259 (let* ((ct (org-current-time))
12260 (dct (decode-time ct))
12261 (ct1
12262 (cond
12263 (org-use-last-clock-out-time-as-effective-time
12264 (or (org-clock-get-last-clock-out-time) ct))
12265 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12266 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12267 (t ct))))
12268 ct1))
12270 (defun org-todo-yesterday (&optional arg)
12271 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12272 (interactive "P")
12273 (if (eq major-mode 'org-agenda-mode)
12274 (apply 'org-agenda-todo-yesterday arg)
12275 (let* ((org-use-effective-time t)
12276 (hour (nth 2 (decode-time (org-current-time))))
12277 (org-extend-today-until (1+ hour)))
12278 (org-todo arg))))
12280 (defvar org-block-entry-blocking ""
12281 "First entry preventing the TODO state change.")
12283 (defun org-cancel-repeater ()
12284 "Cancel a repeater by setting its numeric value to zero."
12285 (interactive)
12286 (save-excursion
12287 (org-back-to-heading t)
12288 (let ((bound1 (point))
12289 (bound0 (save-excursion (outline-next-heading) (point))))
12290 (when (and (re-search-forward
12291 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12292 org-deadline-time-regexp "\\)\\|\\("
12293 org-ts-regexp "\\)")
12294 bound0 t)
12295 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12296 bound1 t))
12297 (replace-match "0" t nil nil 1)))))
12299 (defvar org-state)
12300 (defvar org-blocked-by-checkboxes)
12301 (defun org-todo (&optional arg)
12302 "Change the TODO state of an item.
12304 The state of an item is given by a keyword at the start of the heading,
12305 like
12306 *** TODO Write paper
12307 *** DONE Call mom
12309 The different keywords are specified in the variable `org-todo-keywords'.
12310 By default the available states are \"TODO\" and \"DONE\". So, for this
12311 example: when the item starts with TODO, it is changed to DONE.
12312 When it starts with DONE, the DONE is removed. And when neither TODO nor
12313 DONE are present, add TODO at the beginning of the heading.
12315 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12316 state.
12317 With numeric prefix ARG, switch to that state.
12318 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12319 next set of TODO \
12320 keywords (nextset).
12321 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12322 prefix, circumvent any state blocking.
12323 With a numeric prefix arg of 0, inhibit note taking for the change.
12324 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12326 When called through ELisp, arg is also interpreted in the following way:
12327 `none' -> empty state
12328 \"\" -> switch to empty state
12329 `done' -> switch to DONE
12330 `nextset' -> switch to the next set of keywords
12331 `previousset' -> switch to the previous set of keywords
12332 \"WAITING\" -> switch to the specified keyword, but only if it
12333 really is a member of `org-todo-keywords'."
12334 (interactive "P")
12335 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12336 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12337 'region-start-level 'region))
12338 org-loop-over-headlines-in-active-region)
12339 (org-map-entries
12340 `(org-todo ,arg)
12341 org-loop-over-headlines-in-active-region
12342 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12343 (when (equal arg '(16)) (setq arg 'nextset))
12344 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12345 (let ((org-blocker-hook org-blocker-hook)
12346 commentp
12347 case-fold-search)
12348 (when (equal arg '(64))
12349 (setq arg nil org-blocker-hook nil))
12350 (when (and org-blocker-hook
12351 (or org-inhibit-blocking
12352 (org-entry-get nil "NOBLOCKING")))
12353 (setq org-blocker-hook nil))
12354 (save-excursion
12355 (catch 'exit
12356 (org-back-to-heading t)
12357 (when (org-in-commented-heading-p t)
12358 (org-toggle-comment)
12359 (setq commentp t))
12360 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12361 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12362 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12363 (let* ((match-data (match-data))
12364 (startpos (point-at-bol))
12365 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12366 (org-log-done org-log-done)
12367 (org-log-repeat org-log-repeat)
12368 (org-todo-log-states org-todo-log-states)
12369 (org-inhibit-logging
12370 (if (equal arg 0)
12371 (progn (setq arg nil) 'note) org-inhibit-logging))
12372 (this (match-string 1))
12373 (hl-pos (match-beginning 0))
12374 (head (org-get-todo-sequence-head this))
12375 (ass (assoc head org-todo-kwd-alist))
12376 (interpret (nth 1 ass))
12377 (done-word (nth 3 ass))
12378 (final-done-word (nth 4 ass))
12379 (org-last-state (or this ""))
12380 (completion-ignore-case t)
12381 (member (member this org-todo-keywords-1))
12382 (tail (cdr member))
12383 (org-state (cond
12384 ((and org-todo-key-trigger
12385 (or (and (equal arg '(4))
12386 (eq org-use-fast-todo-selection 'prefix))
12387 (and (not arg) org-use-fast-todo-selection
12388 (not (eq org-use-fast-todo-selection
12389 'prefix)))))
12390 ;; Use fast selection.
12391 (org-fast-todo-selection))
12392 ((and (equal arg '(4))
12393 (or (not org-use-fast-todo-selection)
12394 (not org-todo-key-trigger)))
12395 ;; Read a state with completion.
12396 (completing-read
12397 "State: " (mapcar #'list org-todo-keywords-1)
12398 nil t))
12399 ((eq arg 'right)
12400 (if this
12401 (if tail (car tail) nil)
12402 (car org-todo-keywords-1)))
12403 ((eq arg 'left)
12404 (unless (equal member org-todo-keywords-1)
12405 (if this
12406 (nth (- (length org-todo-keywords-1)
12407 (length tail) 2)
12408 org-todo-keywords-1)
12409 (org-last org-todo-keywords-1))))
12410 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12411 (setq arg nil))) ;hack to fall back to cycling
12412 (arg
12413 ;; User or caller requests a specific state.
12414 (cond
12415 ((equal arg "") nil)
12416 ((eq arg 'none) nil)
12417 ((eq arg 'done) (or done-word (car org-done-keywords)))
12418 ((eq arg 'nextset)
12419 (or (car (cdr (member head org-todo-heads)))
12420 (car org-todo-heads)))
12421 ((eq arg 'previousset)
12422 (let ((org-todo-heads (reverse org-todo-heads)))
12423 (or (car (cdr (member head org-todo-heads)))
12424 (car org-todo-heads))))
12425 ((car (member arg org-todo-keywords-1)))
12426 ((stringp arg)
12427 (user-error "State `%s' not valid in this file" arg))
12428 ((nth (1- (prefix-numeric-value arg))
12429 org-todo-keywords-1))))
12430 ((null member) (or head (car org-todo-keywords-1)))
12431 ((equal this final-done-word) nil) ;-> make empty
12432 ((null tail) nil) ;-> first entry
12433 ((memq interpret '(type priority))
12434 (if (eq this-command last-command)
12435 (car tail)
12436 (if (> (length tail) 0)
12437 (or done-word (car org-done-keywords))
12438 nil)))
12440 (car tail))))
12441 (org-state (or
12442 (run-hook-with-args-until-success
12443 'org-todo-get-default-hook org-state org-last-state)
12444 org-state))
12445 (next (if org-state (concat " " org-state " ") " "))
12446 (change-plist (list :type 'todo-state-change :from this :to org-state
12447 :position startpos))
12448 dolog now-done-p)
12449 (when org-blocker-hook
12450 (let (org-blocked-by-checkboxes block-reason)
12451 (setq org-last-todo-state-is-todo
12452 (not (member this org-done-keywords)))
12453 (unless (save-excursion
12454 (save-match-data
12455 (org-with-wide-buffer
12456 (run-hook-with-args-until-failure
12457 'org-blocker-hook change-plist))))
12458 (setq block-reason (if org-blocked-by-checkboxes
12459 "contained checkboxes"
12460 (format "\"%s\"" org-block-entry-blocking)))
12461 (if (called-interactively-p 'interactive)
12462 (user-error "TODO state change from %s to %s blocked (by %s)"
12463 this org-state block-reason)
12464 ;; Fail silently.
12465 (message "TODO state change from %s to %s blocked (by %s)"
12466 this org-state block-reason)
12467 (throw 'exit nil)))))
12468 (store-match-data match-data)
12469 (replace-match next t t)
12470 (cond ((equal this org-state)
12471 (message "TODO state was already %s" (org-trim next)))
12472 ((not (pos-visible-in-window-p hl-pos))
12473 (message "TODO state changed to %s" (org-trim next))))
12474 (unless head
12475 (setq head (org-get-todo-sequence-head org-state)
12476 ass (assoc head org-todo-kwd-alist)
12477 interpret (nth 1 ass)
12478 done-word (nth 3 ass)
12479 final-done-word (nth 4 ass)))
12480 (when (memq arg '(nextset previousset))
12481 (message "Keyword-Set %d/%d: %s"
12482 (- (length org-todo-sets) -1
12483 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12484 (length org-todo-sets)
12485 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12486 (setq org-last-todo-state-is-todo
12487 (not (member org-state org-done-keywords)))
12488 (setq now-done-p (and (member org-state org-done-keywords)
12489 (not (member this org-done-keywords))))
12490 (and logging (org-local-logging logging))
12491 (when (and (or org-todo-log-states org-log-done)
12492 (not (eq org-inhibit-logging t))
12493 (not (memq arg '(nextset previousset))))
12494 ;; We need to look at recording a time and note.
12495 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12496 (nth 2 (assoc this org-todo-log-states))))
12497 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12498 (setq dolog 'time))
12499 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12500 (and org-state
12501 (member org-state org-not-done-keywords)
12502 (not (member this org-not-done-keywords))))
12503 ;; This is now a todo state and was not one before
12504 ;; If there was a CLOSED time stamp, get rid of it.
12505 (org-add-planning-info nil nil 'closed))
12506 (when (and now-done-p org-log-done)
12507 ;; It is now done, and it was not done before.
12508 (org-add-planning-info 'closed (org-current-effective-time))
12509 (when (and (not dolog) (eq 'note org-log-done))
12510 (org-add-log-setup 'done org-state this 'note)))
12511 (when (and org-state dolog)
12512 ;; This is a non-nil state, and we need to log it.
12513 (org-add-log-setup 'state org-state this dolog)))
12514 ;; Fixup tag positioning.
12515 (org-todo-trigger-tag-changes org-state)
12516 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12517 (when org-provide-todo-statistics
12518 (org-update-parent-todo-statistics))
12519 (run-hooks 'org-after-todo-state-change-hook)
12520 (when (and arg (not (member org-state org-done-keywords)))
12521 (setq head (org-get-todo-sequence-head org-state)))
12522 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12523 ;; Do we need to trigger a repeat?
12524 (when now-done-p
12525 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12526 ;; This is for the agenda, take a snapshot of the headline.
12527 (save-match-data
12528 (setq org-agenda-headline-snapshot-before-repeat
12529 (org-get-heading))))
12530 (org-auto-repeat-maybe org-state))
12531 ;; Fixup cursor location if close to the keyword.
12532 (when (and (outline-on-heading-p)
12533 (not (bolp))
12534 (save-excursion (beginning-of-line 1)
12535 (looking-at org-todo-line-regexp))
12536 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12537 (goto-char (or (match-end 2) (match-end 1)))
12538 (and (looking-at " ") (just-one-space)))
12539 (when org-trigger-hook
12540 (save-excursion
12541 (run-hook-with-args 'org-trigger-hook change-plist)))
12542 (when commentp (org-toggle-comment))))))))
12544 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12545 "Block turning an entry into a TODO, using the hierarchy.
12546 This checks whether the current task should be blocked from state
12547 changes. Such blocking occurs when:
12549 1. The task has children which are not all in a completed state.
12551 2. A task has a parent with the property :ORDERED:, and there
12552 are siblings prior to the current task with incomplete
12553 status.
12555 3. The parent of the task is blocked because it has siblings that should
12556 be done first, or is child of a block grandparent TODO entry."
12558 (if (not org-enforce-todo-dependencies)
12559 t ; if locally turned off don't block
12560 (catch 'dont-block
12561 ;; If this is not a todo state change, or if this entry is already DONE,
12562 ;; do not block
12563 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12564 (member (plist-get change-plist :from)
12565 (cons 'done org-done-keywords))
12566 (member (plist-get change-plist :to)
12567 (cons 'todo org-not-done-keywords))
12568 (not (plist-get change-plist :to)))
12569 (throw 'dont-block t))
12570 ;; If this task has children, and any are undone, it's blocked
12571 (save-excursion
12572 (org-back-to-heading t)
12573 (let ((this-level (funcall outline-level)))
12574 (outline-next-heading)
12575 (let ((child-level (funcall outline-level)))
12576 (while (and (not (eobp))
12577 (> child-level this-level))
12578 ;; this todo has children, check whether they are all
12579 ;; completed
12580 (when (and (not (org-entry-is-done-p))
12581 (org-entry-is-todo-p))
12582 (setq org-block-entry-blocking (org-get-heading))
12583 (throw 'dont-block nil))
12584 (outline-next-heading)
12585 (setq child-level (funcall outline-level))))))
12586 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12587 ;; any previous siblings are undone, it's blocked
12588 (save-excursion
12589 (org-back-to-heading t)
12590 (let* ((pos (point))
12591 (parent-pos (and (org-up-heading-safe) (point)))
12592 (case-fold-search nil))
12593 (unless parent-pos (throw 'dont-block t)) ; no parent
12594 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12595 (forward-line 1)
12596 (re-search-forward org-not-done-heading-regexp pos t))
12597 (setq org-block-entry-blocking (match-string 0))
12598 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12599 ;; Search further up the hierarchy, to see if an ancestor is blocked
12600 (while t
12601 (goto-char parent-pos)
12602 (unless (looking-at org-not-done-heading-regexp)
12603 (throw 'dont-block t)) ; do not block, parent is not a TODO
12604 (setq pos (point))
12605 (setq parent-pos (and (org-up-heading-safe) (point)))
12606 (unless parent-pos (throw 'dont-block t)) ; no parent
12607 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12608 (forward-line 1)
12609 (re-search-forward org-not-done-heading-regexp pos t)
12610 (setq org-block-entry-blocking (org-get-heading)))
12611 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12613 (defcustom org-track-ordered-property-with-tag nil
12614 "Should the ORDERED property also be shown as a tag?
12615 The ORDERED property decides if an entry should require subtasks to be
12616 completed in sequence. Since a property is not very visible, setting
12617 this option means that toggling the ORDERED property with the command
12618 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12619 not relevant for the behavior, but it makes things more visible.
12621 Note that toggling the tag with tags commands will not change the property
12622 and therefore not influence behavior!
12624 This can be t, meaning the tag ORDERED should be used, It can also be a
12625 string to select a different tag for this task."
12626 :group 'org-todo
12627 :type '(choice
12628 (const :tag "No tracking" nil)
12629 (const :tag "Track with ORDERED tag" t)
12630 (string :tag "Use other tag")))
12632 (defun org-toggle-ordered-property ()
12633 "Toggle the ORDERED property of the current entry.
12634 For better visibility, you can track the value of this property with a tag.
12635 See variable `org-track-ordered-property-with-tag'."
12636 (interactive)
12637 (let* ((t1 org-track-ordered-property-with-tag)
12638 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12639 (save-excursion
12640 (org-back-to-heading)
12641 (if (org-entry-get nil "ORDERED")
12642 (progn
12643 (org-delete-property "ORDERED")
12644 (and tag (org-toggle-tag tag 'off))
12645 (message "Subtasks can be completed in arbitrary order"))
12646 (org-entry-put nil "ORDERED" "t")
12647 (and tag (org-toggle-tag tag 'on))
12648 (message "Subtasks must be completed in sequence")))))
12650 (defun org-block-todo-from-checkboxes (change-plist)
12651 "Block turning an entry into a TODO, using checkboxes.
12652 This checks whether the current task should be blocked from state
12653 changes because there are unchecked boxes in this entry."
12654 (if (not org-enforce-todo-checkbox-dependencies)
12655 t ; if locally turned off don't block
12656 (catch 'dont-block
12657 ;; If this is not a todo state change, or if this entry is already DONE,
12658 ;; do not block
12659 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12660 (member (plist-get change-plist :from)
12661 (cons 'done org-done-keywords))
12662 (member (plist-get change-plist :to)
12663 (cons 'todo org-not-done-keywords))
12664 (not (plist-get change-plist :to)))
12665 (throw 'dont-block t))
12666 ;; If this task has checkboxes that are not checked, it's blocked
12667 (save-excursion
12668 (org-back-to-heading t)
12669 (let ((beg (point)) end)
12670 (outline-next-heading)
12671 (setq end (point))
12672 (goto-char beg)
12673 (when (org-list-search-forward
12674 (concat (org-item-beginning-re)
12675 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12676 "\\[[- ]\\]")
12677 end t)
12678 (when (boundp 'org-blocked-by-checkboxes)
12679 (setq org-blocked-by-checkboxes t))
12680 (throw 'dont-block nil))))
12681 t))) ; do not block
12683 (defun org-entry-blocked-p ()
12684 "Non-nil if entry at point is blocked."
12685 (and (not (org-entry-get nil "NOBLOCKING"))
12686 (member (org-entry-get nil "TODO") org-not-done-keywords)
12687 (not (run-hook-with-args-until-failure
12688 'org-blocker-hook
12689 (list :type 'todo-state-change
12690 :position (point)
12691 :from 'todo
12692 :to 'done)))))
12694 (defun org-update-statistics-cookies (all)
12695 "Update the statistics cookie, either from TODO or from checkboxes.
12696 This should be called with the cursor in a line with a statistics
12697 cookie. When called with a \\[universal-argument] prefix, update
12698 all statistics cookies in the buffer."
12699 (interactive "P")
12700 (if all
12701 (progn
12702 (org-update-checkbox-count 'all)
12703 (org-map-entries 'org-update-parent-todo-statistics))
12704 (if (not (org-at-heading-p))
12705 (org-update-checkbox-count)
12706 (let ((pos (point-marker))
12707 end l1 l2)
12708 (ignore-errors (org-back-to-heading t))
12709 (if (not (org-at-heading-p))
12710 (org-update-checkbox-count)
12711 (setq l1 (org-outline-level))
12712 (setq end (save-excursion
12713 (outline-next-heading)
12714 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12715 (point)))
12716 (if (and (save-excursion
12717 (re-search-forward
12718 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12719 (not (save-excursion (re-search-forward
12720 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12721 (org-update-checkbox-count)
12722 (if (and l2 (> l2 l1))
12723 (progn
12724 (goto-char end)
12725 (org-update-parent-todo-statistics))
12726 (goto-char pos)
12727 (beginning-of-line 1)
12728 (while (re-search-forward
12729 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12730 (point-at-eol) t)
12731 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12732 (goto-char pos)
12733 (move-marker pos nil)))))
12735 (defvar org-entry-property-inherited-from) ;; defined below
12736 (defun org-update-parent-todo-statistics ()
12737 "Update any statistics cookie in the parent of the current headline.
12738 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12739 the entire subtree and this will travel up the hierarchy and update
12740 statistics everywhere."
12741 (let* ((prop (save-excursion (org-up-heading-safe)
12742 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12743 (recursive (or (not org-hierarchical-todo-statistics)
12744 (and prop (string-match "\\<recursive\\>" prop))))
12745 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12747 (first t)
12748 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12749 level ltoggle l1 new ndel
12750 (cnt-all 0) (cnt-done 0) is-percent kwd
12751 checkbox-beg cookie-present)
12752 (catch 'exit
12753 (save-excursion
12754 (beginning-of-line 1)
12755 (setq ltoggle (funcall outline-level))
12756 ;; Three situations are to consider:
12758 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12759 ;; to the top-level ancestor on the headline;
12761 ;; 2. If parent has "recursive" property, repeat up to the
12762 ;; headline setting that property, taking inheritance into
12763 ;; account;
12765 ;; 3. Else, move up to direct parent and proceed only once.
12766 (while (and (setq level (org-up-heading-safe))
12767 (or recursive first)
12768 (>= (point) lim))
12769 (setq first nil cookie-present nil)
12770 (unless (and level
12771 (not (string-match
12772 "\\<checkbox\\>"
12773 (downcase (or (org-entry-get nil "COOKIE_DATA")
12774 "")))))
12775 (throw 'exit nil))
12776 (while (re-search-forward box-re (point-at-eol) t)
12777 (setq cnt-all 0 cnt-done 0 cookie-present t)
12778 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12779 (save-match-data
12780 (unless (outline-next-heading) (throw 'exit nil))
12781 (while (and (looking-at org-complex-heading-regexp)
12782 (> (setq l1 (length (match-string 1))) level))
12783 (setq kwd (and (or recursive (= l1 ltoggle))
12784 (match-string 2)))
12785 (if (or (eq org-provide-todo-statistics 'all-headlines)
12786 (and (eq org-provide-todo-statistics t)
12787 (or (member kwd org-done-keywords)))
12788 (and (listp org-provide-todo-statistics)
12789 (stringp (car org-provide-todo-statistics))
12790 (or (member kwd org-provide-todo-statistics)
12791 (member kwd org-done-keywords)))
12792 (and (listp org-provide-todo-statistics)
12793 (listp (car org-provide-todo-statistics))
12794 (or (member kwd (car org-provide-todo-statistics))
12795 (and (member kwd org-done-keywords)
12796 (member kwd (cadr org-provide-todo-statistics))))))
12797 (setq cnt-all (1+ cnt-all))
12798 (and (eq org-provide-todo-statistics t)
12800 (setq cnt-all (1+ cnt-all))))
12801 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12802 (member kwd org-done-keywords))
12803 (and (listp org-provide-todo-statistics)
12804 (listp (car org-provide-todo-statistics))
12805 (member kwd org-done-keywords)
12806 (member kwd (cadr org-provide-todo-statistics)))
12807 (and (listp org-provide-todo-statistics)
12808 (stringp (car org-provide-todo-statistics))
12809 (member kwd org-done-keywords)))
12810 (setq cnt-done (1+ cnt-done)))
12811 (outline-next-heading)))
12812 (setq new
12813 (if is-percent
12814 (format "[%d%%]" (floor (* 100.0 cnt-done)
12815 (max 1 cnt-all)))
12816 (format "[%d/%d]" cnt-done cnt-all))
12817 ndel (- (match-end 0) checkbox-beg))
12818 (goto-char checkbox-beg)
12819 (insert new)
12820 (delete-region (point) (+ (point) ndel))
12821 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12822 (when cookie-present
12823 (run-hook-with-args 'org-after-todo-statistics-hook
12824 cnt-done (- cnt-all cnt-done))))))
12825 (run-hooks 'org-todo-statistics-hook)))
12827 (defvar org-after-todo-statistics-hook nil
12828 "Hook that is called after a TODO statistics cookie has been updated.
12829 Each function is called with two arguments: the number of not-done entries
12830 and the number of done entries.
12832 For example, the following function, when added to this hook, will switch
12833 an entry to DONE when all children are done, and back to TODO when new
12834 entries are set to a TODO status. Note that this hook is only called
12835 when there is a statistics cookie in the headline!
12837 (defun org-summary-todo (n-done n-not-done)
12838 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12839 (let (org-log-done org-log-states) ; turn off logging
12840 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12843 (defvar org-todo-statistics-hook nil
12844 "Hook that is run whenever Org thinks TODO statistics should be updated.
12845 This hook runs even if there is no statistics cookie present, in which case
12846 `org-after-todo-statistics-hook' would not run.")
12848 (defun org-todo-trigger-tag-changes (state)
12849 "Apply the changes defined in `org-todo-state-tags-triggers'."
12850 (let ((l org-todo-state-tags-triggers)
12851 changes)
12852 (when (or (not state) (equal state ""))
12853 (setq changes (append changes (cdr (assoc "" l)))))
12854 (when (and (stringp state) (> (length state) 0))
12855 (setq changes (append changes (cdr (assoc state l)))))
12856 (when (member state org-not-done-keywords)
12857 (setq changes (append changes (cdr (assq 'todo l)))))
12858 (when (member state org-done-keywords)
12859 (setq changes (append changes (cdr (assq 'done l)))))
12860 (dolist (c changes)
12861 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12863 (defun org-local-logging (value)
12864 "Get logging settings from a property VALUE."
12865 ;; Directly set the variables, they are already local.
12866 (setq org-log-done nil
12867 org-log-repeat nil
12868 org-todo-log-states nil)
12869 (dolist (w (split-string value))
12870 (let (a)
12871 (cond
12872 ((setq a (assoc w org-startup-options))
12873 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12874 (set (nth 1 a) (nth 2 a))))
12875 ((setq a (org-extract-log-state-settings w))
12876 (and (member (car a) org-todo-keywords-1)
12877 (push a org-todo-log-states)))))))
12879 (defun org-get-todo-sequence-head (kwd)
12880 "Return the head of the TODO sequence to which KWD belongs.
12881 If KWD is not set, check if there is a text property remembering the
12882 right sequence."
12883 (let (p)
12884 (cond
12885 ((not kwd)
12886 (or (get-text-property (point-at-bol) 'org-todo-head)
12887 (progn
12888 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12889 nil (point-at-eol)))
12890 (get-text-property p 'org-todo-head))))
12891 ((not (member kwd org-todo-keywords-1))
12892 (car org-todo-keywords-1))
12893 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12895 (defun org-fast-todo-selection ()
12896 "Fast TODO keyword selection with single keys.
12897 Returns the new TODO keyword, or nil if no state change should occur."
12898 (let* ((fulltable org-todo-key-alist)
12899 (done-keywords org-done-keywords) ;; needed for the faces.
12900 (maxlen (apply 'max (mapcar
12901 (lambda (x)
12902 (if (stringp (car x)) (string-width (car x)) 0))
12903 fulltable)))
12904 (expert nil)
12905 (fwidth (+ maxlen 3 1 3))
12906 (ncol (/ (- (window-width) 4) fwidth))
12907 tg cnt e c tbl
12908 groups ingroup)
12909 (save-excursion
12910 (save-window-excursion
12911 (if expert
12912 (set-buffer (get-buffer-create " *Org todo*"))
12913 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12914 (erase-buffer)
12915 (setq-local org-done-keywords done-keywords)
12916 (setq tbl fulltable cnt 0)
12917 (while (setq e (pop tbl))
12918 (cond
12919 ((equal e '(:startgroup))
12920 (push '() groups) (setq ingroup t)
12921 (unless (= cnt 0)
12922 (setq cnt 0)
12923 (insert "\n"))
12924 (insert "{ "))
12925 ((equal e '(:endgroup))
12926 (setq ingroup nil cnt 0)
12927 (insert "}\n"))
12928 ((equal e '(:newline))
12929 (unless (= cnt 0)
12930 (setq cnt 0)
12931 (insert "\n")
12932 (setq e (car tbl))
12933 (while (equal (car tbl) '(:newline))
12934 (insert "\n")
12935 (setq tbl (cdr tbl)))))
12937 (setq tg (car e) c (cdr e))
12938 (when ingroup (push tg (car groups)))
12939 (setq tg (org-add-props tg nil 'face
12940 (org-get-todo-face tg)))
12941 (when (and (= cnt 0) (not ingroup)) (insert " "))
12942 (insert "[" c "] " tg (make-string
12943 (- fwidth 4 (length tg)) ?\ ))
12944 (when (= (setq cnt (1+ cnt)) ncol)
12945 (insert "\n")
12946 (when ingroup (insert " "))
12947 (setq cnt 0)))))
12948 (insert "\n")
12949 (goto-char (point-min))
12950 (unless expert (org-fit-window-to-buffer))
12951 (message "[a-z..]:Set [SPC]:clear")
12952 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12953 (cond
12954 ((or (= c ?\C-g)
12955 (and (= c ?q) (not (rassoc c fulltable))))
12956 (setq quit-flag t))
12957 ((= c ?\ ) nil)
12958 ((setq e (rassoc c fulltable) tg (car e))
12960 (t (setq quit-flag t)))))))
12962 (defun org-entry-is-todo-p ()
12963 (member (org-get-todo-state) org-not-done-keywords))
12965 (defun org-entry-is-done-p ()
12966 (member (org-get-todo-state) org-done-keywords))
12968 (defun org-get-todo-state ()
12969 "Return the TODO keyword of the current subtree."
12970 (save-excursion
12971 (org-back-to-heading t)
12972 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12973 (match-end 2)
12974 (match-string 2))))
12976 (defun org-at-date-range-p (&optional inactive-ok)
12977 "Non-nil if point is inside a date range.
12979 When optional argument INACTIVE-OK is non-nil, also consider
12980 inactive time ranges.
12982 When this function returns a non-nil value, match data is set
12983 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12984 on INACTIVE-OK."
12985 (interactive)
12986 (save-excursion
12987 (catch 'exit
12988 (let ((pos (point)))
12989 (skip-chars-backward "^[<\r\n")
12990 (skip-chars-backward "<[")
12991 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12992 (>= (match-end 0) pos)
12993 (throw 'exit t))
12994 (skip-chars-backward "^<[\r\n")
12995 (skip-chars-backward "<[")
12996 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12997 (>= (match-end 0) pos)
12998 (throw 'exit t)))
12999 nil)))
13001 (defun org-get-repeat (&optional timestamp)
13002 "Check if there is a time-stamp with repeater in this entry.
13004 Return the repeater, as a string, or nil. Also return nil when
13005 this function is called before first heading.
13007 When optional argument TIMESTAMP is a string, extract the
13008 repeater from there instead."
13009 (save-match-data
13010 (cond (timestamp
13011 (and (string-match org-repeat-re timestamp)
13012 (match-string-no-properties 1 timestamp)))
13013 ((org-before-first-heading-p) nil)
13015 (save-excursion
13016 (org-back-to-heading t)
13017 (let ((end (org-entry-end-position)))
13018 (catch :repeat
13019 (while (re-search-forward org-repeat-re end t)
13020 (when (save-match-data (org-at-timestamp-p 'agenda))
13021 (throw :repeat (match-string-no-properties 1)))))))))))
13023 (defvar org-last-changed-timestamp)
13024 (defvar org-last-inserted-timestamp)
13025 (defvar org-log-post-message)
13026 (defvar org-log-note-purpose)
13027 (defvar org-log-note-how nil)
13028 (defvar org-log-note-extra)
13029 (defun org-auto-repeat-maybe (done-word)
13030 "Check if the current headline contains a repeated time-stamp.
13032 If yes, set TODO state back to what it was and change the base date
13033 of repeating deadline/scheduled time stamps to new date.
13035 This function is run automatically after each state change to a DONE state."
13036 (let* ((repeat (org-get-repeat))
13037 (aa (assoc org-last-state org-todo-kwd-alist))
13038 (interpret (nth 1 aa))
13039 (head (nth 2 aa))
13040 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13041 (msg "Entry repeats: ")
13042 (org-log-done nil)
13043 (org-todo-log-states nil)
13044 (end (copy-marker (org-entry-end-position))))
13045 (unwind-protect
13046 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13047 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13048 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13049 org-todo-repeat-to-state)))
13050 (org-todo (cond
13051 ((and to-state (member to-state org-todo-keywords-1))
13052 to-state)
13053 ((eq interpret 'type) org-last-state)
13054 (head)
13055 (t 'none))))
13056 (org-back-to-heading t)
13057 (org-add-planning-info nil nil 'closed)
13058 ;; When `org-log-repeat' is non-nil or entry contains
13059 ;; a clock, set LAST_REPEAT property.
13060 (when (or org-log-repeat
13061 (catch :clock
13062 (save-excursion
13063 (while (re-search-forward org-clock-line-re end t)
13064 (when (org-at-clock-log-p) (throw :clock t))))))
13065 (org-entry-put nil "LAST_REPEAT" (format-time-string
13066 (org-time-stamp-format t t)
13067 (current-time))))
13068 (when org-log-repeat
13069 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13070 (memq 'org-add-log-note post-command-hook))
13071 ;; We are already setup for some record.
13072 (when (eq org-log-repeat 'note)
13073 ;; Make sure we take a note, not only a time stamp.
13074 (setq org-log-note-how 'note))
13075 ;; Set up for taking a record.
13076 (org-add-log-setup 'state
13077 (or done-word (car org-done-keywords))
13078 org-last-state
13079 org-log-repeat)))
13080 (let ((planning-re (regexp-opt
13081 (list org-scheduled-string org-deadline-string))))
13082 (while (re-search-forward org-ts-regexp end t)
13083 (let* ((ts (match-string 0))
13084 (planning? (org-at-planning-p))
13085 (type (if (not planning?) "Plain:"
13086 (save-excursion
13087 (re-search-backward
13088 planning-re (line-beginning-position) t)
13089 (match-string 0)))))
13090 (cond
13091 ;; Ignore fake time-stamps (e.g., within comments).
13092 ((not (org-at-timestamp-p 'agenda)))
13093 ;; Time-stamps without a repeater are usually
13094 ;; skipped. However, a SCHEDULED time-stamp without
13095 ;; one is removed, as they are no longer relevant.
13096 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13097 ts))
13098 (when (equal type org-scheduled-string)
13099 (org-remove-timestamp-with-keyword type)))
13101 (let ((n (string-to-number (match-string 2 ts)))
13102 (what (match-string 3 ts)))
13103 (when (equal what "w") (setq n (* n 7) what "d"))
13104 (when (and (equal what "h")
13105 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13106 ts)))
13107 (user-error
13108 "Cannot repeat in Repeat in %d hour(s) because no hour \
13109 has been set"
13111 ;; Preparation, see if we need to modify the start
13112 ;; date for the change.
13113 (when (match-end 1)
13114 (let ((time (save-match-data
13115 (org-time-string-to-time ts))))
13116 (cond
13117 ((equal (match-string 1 ts) ".")
13118 ;; Shift starting date to today
13119 (org-timestamp-change
13120 (- (org-today) (time-to-days time))
13121 'day))
13122 ((equal (match-string 1 ts) "+")
13123 (let ((nshiftmax 10)
13124 (nshift 0))
13125 (while (or (= nshift 0)
13126 (not (time-less-p (current-time) time)))
13127 (when (= (cl-incf nshift) nshiftmax)
13128 (or (y-or-n-p
13129 (format "%d repeater intervals were not \
13130 enough to shift date past today. Continue? "
13131 nshift))
13132 (user-error "Abort")))
13133 (org-timestamp-change n (cdr (assoc what whata)))
13134 (org-in-regexp org-ts-regexp3)
13135 (setq ts (match-string 1))
13136 (setq time
13137 (save-match-data
13138 (org-time-string-to-time ts)))))
13139 (org-timestamp-change (- n) (cdr (assoc what whata)))
13140 ;; Rematch, so that we have everything in place
13141 ;; for the real shift.
13142 (org-in-regexp org-ts-regexp3)
13143 (setq ts (match-string 1))
13144 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13145 ts)))))
13146 (save-excursion
13147 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13148 (setq msg
13149 (concat
13150 msg type " " org-last-changed-timestamp " "))))))))
13151 (setq org-log-post-message msg)
13152 (message "%s" msg))
13153 (set-marker end nil))))
13155 (defun org-show-todo-tree (arg)
13156 "Make a compact tree which shows all headlines marked with TODO.
13157 The tree will show the lines where the regexp matches, and all higher
13158 headlines above the match.
13159 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13160 With a numeric prefix N, construct a sparse tree for the Nth element
13161 of `org-todo-keywords-1'."
13162 (interactive "P")
13163 (let ((case-fold-search nil)
13164 (kwd-re
13165 (cond ((null arg) org-not-done-regexp)
13166 ((equal arg '(4))
13167 (let ((kwd
13168 (completing-read "Keyword (or KWD1|KWD2|...): "
13169 (mapcar #'list org-todo-keywords-1))))
13170 (concat "\\("
13171 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13172 "\\)\\>")))
13173 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13174 (regexp-quote (nth (1- (prefix-numeric-value arg))
13175 org-todo-keywords-1)))
13176 (t (user-error "Invalid prefix argument: %s" arg)))))
13177 (message "%d TODO entries found"
13178 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13180 (defun org--deadline-or-schedule (arg type time)
13181 "Insert DEADLINE or SCHEDULE information in current entry.
13182 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13183 `org-schedule' for information about ARG and TIME arguments."
13184 (let* ((deadline? (eq type 'deadline))
13185 (keyword (if deadline? org-deadline-string org-scheduled-string))
13186 (log (if deadline? org-log-redeadline org-log-reschedule))
13187 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13188 (old-date-time (and old-date (org-time-string-to-time old-date)))
13189 ;; Save repeater cookie from either TIME or current scheduled
13190 ;; time stamp. We are going to insert it back at the end of
13191 ;; the process.
13192 (repeater (or (and (org-string-nw-p time)
13193 ;; We use `org-repeat-re' because we need
13194 ;; to tell the difference between a real
13195 ;; repeater and a time delta, e.g. "+2d".
13196 (string-match org-repeat-re time)
13197 (match-string 1 time))
13198 (and (org-string-nw-p old-date)
13199 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13200 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13201 old-date)
13202 (match-string 1 old-date)))))
13203 (pcase arg
13204 (`(4)
13205 (when (and old-date log)
13206 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13207 nil old-date log))
13208 (org-remove-timestamp-with-keyword keyword)
13209 (message (if deadline? "Item no longer has a deadline."
13210 "Item is no longer scheduled.")))
13211 (`(16)
13212 (save-excursion
13213 (org-back-to-heading t)
13214 (let ((regexp (if deadline? org-deadline-time-regexp
13215 org-scheduled-time-regexp)))
13216 (if (not (re-search-forward regexp (line-end-position 2) t))
13217 (user-error (if deadline? "No deadline information to update"
13218 "No scheduled information to update"))
13219 (let* ((rpl0 (match-string 1))
13220 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13221 (msg (if deadline? "Warn starting from" "Delay until")))
13222 (replace-match
13223 (concat keyword
13224 " <" rpl
13225 (format " -%dd"
13226 (abs (- (time-to-days
13227 (save-match-data
13228 (org-read-date
13229 nil t nil msg old-date-time)))
13230 (time-to-days old-date-time))))
13231 ">") t t))))))
13233 (org-add-planning-info type time 'closed)
13234 (when (and old-date
13236 (not (equal old-date org-last-inserted-timestamp)))
13237 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13238 org-last-inserted-timestamp
13239 old-date
13240 log))
13241 (when repeater
13242 (save-excursion
13243 (org-back-to-heading t)
13244 (when (re-search-forward
13245 (concat keyword " " org-last-inserted-timestamp)
13246 (line-end-position 2)
13248 (goto-char (1- (match-end 0)))
13249 (insert " " repeater)
13250 (setq org-last-inserted-timestamp
13251 (concat (substring org-last-inserted-timestamp 0 -1)
13252 " " repeater
13253 (substring org-last-inserted-timestamp -1))))))
13254 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13255 org-last-inserted-timestamp)))))
13257 (defun org-deadline (arg &optional time)
13258 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13259 With one universal prefix argument, remove any deadline from the item.
13260 With two universal prefix arguments, prompt for a warning delay.
13261 With argument TIME, set the deadline at the corresponding date. TIME
13262 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13263 (interactive "P")
13264 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13265 (org-map-entries
13266 (lambda () (org--deadline-or-schedule arg 'deadline time))
13268 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13269 'region-start-level
13270 'region)
13271 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13272 (org--deadline-or-schedule arg 'deadline time)))
13274 (defun org-schedule (arg &optional time)
13275 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13276 With one universal prefix argument, remove any scheduling date from the item.
13277 With two universal prefix arguments, prompt for a delay cookie.
13278 With argument TIME, scheduled at the corresponding date. TIME can
13279 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13280 (interactive "P")
13281 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13282 (org-map-entries
13283 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13285 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13286 'region-start-level
13287 'region)
13288 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13289 (org--deadline-or-schedule arg 'scheduled time)))
13291 (defun org-get-scheduled-time (pom &optional inherit)
13292 "Get the scheduled time as a time tuple, of a format suitable
13293 for calling org-schedule with, or if there is no scheduling,
13294 returns nil."
13295 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13296 (when time
13297 (apply 'encode-time (org-parse-time-string time)))))
13299 (defun org-get-deadline-time (pom &optional inherit)
13300 "Get the deadline as a time tuple, of a format suitable for
13301 calling org-deadline with, or if there is no scheduling, returns
13302 nil."
13303 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13304 (when time
13305 (apply 'encode-time (org-parse-time-string time)))))
13307 (defun org-remove-timestamp-with-keyword (keyword)
13308 "Remove all time stamps with KEYWORD in the current entry."
13309 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13310 beg)
13311 (save-excursion
13312 (org-back-to-heading t)
13313 (setq beg (point))
13314 (outline-next-heading)
13315 (while (re-search-backward re beg t)
13316 (replace-match "")
13317 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13318 (equal (char-before) ?\ ))
13319 (backward-delete-char 1)
13320 (when (string-match "^[ \t]*$" (buffer-substring
13321 (point-at-bol) (point-at-eol)))
13322 (delete-region (point-at-bol)
13323 (min (point-max) (1+ (point-at-eol))))))))))
13325 (defvar org-time-was-given) ; dynamically scoped parameter
13326 (defvar org-end-time-was-given) ; dynamically scoped parameter
13328 (defun org-at-planning-p ()
13329 "Non-nil when point is on a planning info line."
13330 ;; This is as accurate and faster than `org-element-at-point' since
13331 ;; planning info location is fixed in the section.
13332 (org-with-wide-buffer
13333 (beginning-of-line)
13334 (and (looking-at-p org-planning-line-re)
13335 (eq (point)
13336 (ignore-errors
13337 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13338 (org-back-to-heading t)
13339 (org-with-limited-levels (org-back-to-heading t)))
13340 (line-beginning-position 2))))))
13342 (defun org-add-planning-info (what &optional time &rest remove)
13343 "Insert new timestamp with keyword in the planning line.
13344 WHAT indicates what kind of time stamp to add. It is a symbol
13345 among `closed', `deadline', `scheduled' and nil. TIME indicates
13346 the time to use. If none is given, the user is prompted for
13347 a date. REMOVE indicates what kind of entries to remove. An old
13348 WHAT entry will also be removed."
13349 (let (org-time-was-given org-end-time-was-given default-time default-input)
13350 (catch 'exit
13351 (when (and (memq what '(scheduled deadline))
13352 (or (not time)
13353 (and (stringp time)
13354 (string-match "^[-+]+[0-9]" time))))
13355 ;; Try to get a default date/time from existing timestamp
13356 (save-excursion
13357 (org-back-to-heading t)
13358 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13359 (when (re-search-forward (if (eq what 'scheduled)
13360 org-scheduled-time-regexp
13361 org-deadline-time-regexp)
13362 end t)
13363 (setq ts (match-string 1)
13364 default-time (apply 'encode-time (org-parse-time-string ts))
13365 default-input (and ts (org-get-compact-tod ts)))))))
13366 (when what
13367 (setq time
13368 (if (stringp time)
13369 ;; This is a string (relative or absolute), set
13370 ;; proper date.
13371 (apply #'encode-time
13372 (org-read-date-analyze
13373 time default-time (decode-time default-time)))
13374 ;; If necessary, get the time from the user
13375 (or time (org-read-date nil 'to-time nil nil
13376 default-time default-input)))))
13378 (org-with-wide-buffer
13379 (org-back-to-heading t)
13380 (forward-line)
13381 (unless (bolp) (insert "\n"))
13382 (cond ((looking-at-p org-planning-line-re)
13383 ;; Move to current indentation.
13384 (skip-chars-forward " \t")
13385 ;; Check if we have to remove something.
13386 (dolist (type (if what (cons what remove) remove))
13387 (save-excursion
13388 (when (re-search-forward
13389 (cl-case type
13390 (closed org-closed-time-regexp)
13391 (deadline org-deadline-time-regexp)
13392 (scheduled org-scheduled-time-regexp)
13393 (otherwise
13394 (error "Invalid planning type: %s" type)))
13395 (line-end-position) t)
13396 ;; Delete until next keyword or end of line.
13397 (delete-region
13398 (match-beginning 0)
13399 (if (re-search-forward org-keyword-time-not-clock-regexp
13400 (line-end-position)
13402 (match-beginning 0)
13403 (line-end-position))))))
13404 ;; If there is nothing more to add and no more keyword
13405 ;; is left, remove the line completely.
13406 (if (and (looking-at-p "[ \t]*$") (not what))
13407 (delete-region (line-beginning-position)
13408 (line-beginning-position 2))
13409 ;; If we removed last keyword, do not leave trailing
13410 ;; white space at the end of line.
13411 (let ((p (point)))
13412 (save-excursion
13413 (end-of-line)
13414 (unless (= (skip-chars-backward " \t" p) 0)
13415 (delete-region (point) (line-end-position)))))))
13416 ((not what) (throw 'exit nil)) ; Nothing to do.
13417 (t (insert-before-markers "\n")
13418 (backward-char 1)
13419 (when org-adapt-indentation
13420 (indent-to-column (1+ (org-outline-level))))))
13421 (when what
13422 ;; Insert planning keyword.
13423 (insert (cl-case what
13424 (closed org-closed-string)
13425 (deadline org-deadline-string)
13426 (scheduled org-scheduled-string)
13427 (otherwise (error "Invalid planning type: %s" what)))
13428 " ")
13429 ;; Insert associated timestamp.
13430 (let ((ts (org-insert-time-stamp
13431 time
13432 (or org-time-was-given
13433 (and (eq what 'closed) org-log-done-with-time))
13434 (eq what 'closed)
13435 nil nil (list org-end-time-was-given))))
13436 (unless (eolp) (insert " "))
13437 ts))))))
13439 (defvar org-log-note-marker (make-marker)
13440 "Marker pointing at the entry where the note is to be inserted.")
13441 (defvar org-log-note-purpose nil)
13442 (defvar org-log-note-state nil)
13443 (defvar org-log-note-previous-state nil)
13444 (defvar org-log-note-extra nil)
13445 (defvar org-log-note-window-configuration nil)
13446 (defvar org-log-note-return-to (make-marker))
13447 (defvar org-log-note-effective-time nil
13448 "Remembered current time so that dynamically scoped
13449 `org-extend-today-until' affects timestamps in state change log")
13451 (defvar org-log-post-message nil
13452 "Message to be displayed after a log note has been stored.
13453 The auto-repeater uses this.")
13455 (defun org-add-note ()
13456 "Add a note to the current entry.
13457 This is done in the same way as adding a state change note."
13458 (interactive)
13459 (org-add-log-setup 'note))
13461 (defun org-log-beginning (&optional create)
13462 "Return expected start of log notes in current entry.
13463 When optional argument CREATE is non-nil, the function creates
13464 a drawer to store notes, if necessary. Returned position ignores
13465 narrowing."
13466 (org-with-wide-buffer
13467 (let ((drawer (org-log-into-drawer)))
13468 (cond
13469 (drawer
13470 (org-end-of-meta-data)
13471 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13472 (end (if (org-at-heading-p) (point)
13473 (save-excursion (outline-next-heading) (point))))
13474 (case-fold-search t))
13475 (catch 'exit
13476 ;; Try to find existing drawer.
13477 (while (re-search-forward regexp end t)
13478 (let ((element (org-element-at-point)))
13479 (when (eq (org-element-type element) 'drawer)
13480 (let ((cend (org-element-property :contents-end element)))
13481 (when (and (not org-log-states-order-reversed) cend)
13482 (goto-char cend)))
13483 (throw 'exit nil))))
13484 ;; No drawer found. Create one, if permitted.
13485 (when create
13486 (unless (bolp) (insert "\n"))
13487 (let ((beg (point)))
13488 (insert ":" drawer ":\n:END:\n")
13489 (org-indent-region beg (point)))
13490 (end-of-line -1)))))
13492 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13493 (skip-chars-forward " \t\n")
13494 (beginning-of-line)
13495 (unless org-log-states-order-reversed
13496 (org-skip-over-state-notes)
13497 (skip-chars-backward " \t\n")
13498 (forward-line)))))
13499 (if (bolp) (point) (line-beginning-position 2))))
13501 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13502 "Set up the post command hook to take a note.
13503 If this is about to TODO state change, the new state is expected in STATE.
13504 HOW is an indicator what kind of note should be created.
13505 EXTRA is additional text that will be inserted into the notes buffer."
13506 (move-marker org-log-note-marker (point))
13507 (setq org-log-note-purpose purpose
13508 org-log-note-state state
13509 org-log-note-previous-state prev-state
13510 org-log-note-how how
13511 org-log-note-extra extra
13512 org-log-note-effective-time (org-current-effective-time))
13513 (add-hook 'post-command-hook 'org-add-log-note 'append))
13515 (defun org-skip-over-state-notes ()
13516 "Skip past the list of State notes in an entry."
13517 (when (ignore-errors (goto-char (org-in-item-p)))
13518 (let* ((struct (org-list-struct))
13519 (prevs (org-list-prevs-alist struct))
13520 (regexp
13521 (concat "[ \t]*- +"
13522 (replace-regexp-in-string
13523 " +" " +"
13524 (org-replace-escapes
13525 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13526 `(("%d" . ,org-ts-regexp-inactive)
13527 ("%D" . ,org-ts-regexp)
13528 ("%s" . "\"\\S-+\"")
13529 ("%S" . "\"\\S-+\"")
13530 ("%t" . ,org-ts-regexp-inactive)
13531 ("%T" . ,org-ts-regexp)
13532 ("%u" . ".*?")
13533 ("%U" . ".*?")))))))
13534 (while (looking-at-p regexp)
13535 (goto-char (or (org-list-get-next-item (point) struct prevs)
13536 (org-list-get-item-end (point) struct)))))))
13538 (defun org-add-log-note (&optional _purpose)
13539 "Pop up a window for taking a note, and add this note later."
13540 (remove-hook 'post-command-hook 'org-add-log-note)
13541 (setq org-log-note-window-configuration (current-window-configuration))
13542 (delete-other-windows)
13543 (move-marker org-log-note-return-to (point))
13544 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13545 (goto-char org-log-note-marker)
13546 (org-switch-to-buffer-other-window "*Org Note*")
13547 (erase-buffer)
13548 (if (memq org-log-note-how '(time state))
13549 (org-store-log-note)
13550 (let ((org-inhibit-startup t)) (org-mode))
13551 (insert (format "# Insert note for %s.
13552 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13553 (cond
13554 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13555 ((eq org-log-note-purpose 'done) "closed todo item")
13556 ((eq org-log-note-purpose 'state)
13557 (format "state change from \"%s\" to \"%s\""
13558 (or org-log-note-previous-state "")
13559 (or org-log-note-state "")))
13560 ((eq org-log-note-purpose 'reschedule)
13561 "rescheduling")
13562 ((eq org-log-note-purpose 'delschedule)
13563 "no longer scheduled")
13564 ((eq org-log-note-purpose 'redeadline)
13565 "changing deadline")
13566 ((eq org-log-note-purpose 'deldeadline)
13567 "removing deadline")
13568 ((eq org-log-note-purpose 'refile)
13569 "refiling")
13570 ((eq org-log-note-purpose 'note)
13571 "this entry")
13572 (t (error "This should not happen")))))
13573 (when org-log-note-extra (insert org-log-note-extra))
13574 (setq-local org-finish-function 'org-store-log-note)
13575 (run-hooks 'org-log-buffer-setup-hook)))
13577 (defvar org-note-abort nil) ; dynamically scoped
13578 (defun org-store-log-note ()
13579 "Finish taking a log note, and insert it to where it belongs."
13580 (let ((txt (prog1 (buffer-string)
13581 (kill-buffer)))
13582 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13583 lines)
13584 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13585 (setq txt (replace-match "" t t txt)))
13586 (when (string-match "\\s-+\\'" txt)
13587 (setq txt (replace-match "" t t txt)))
13588 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13589 (when (org-string-nw-p note)
13590 (setq note
13591 (org-replace-escapes
13592 note
13593 (list (cons "%u" (user-login-name))
13594 (cons "%U" user-full-name)
13595 (cons "%t" (format-time-string
13596 (org-time-stamp-format 'long 'inactive)
13597 org-log-note-effective-time))
13598 (cons "%T" (format-time-string
13599 (org-time-stamp-format 'long nil)
13600 org-log-note-effective-time))
13601 (cons "%d" (format-time-string
13602 (org-time-stamp-format nil 'inactive)
13603 org-log-note-effective-time))
13604 (cons "%D" (format-time-string
13605 (org-time-stamp-format nil nil)
13606 org-log-note-effective-time))
13607 (cons "%s" (cond
13608 ((not org-log-note-state) "")
13609 ((string-match-p org-ts-regexp
13610 org-log-note-state)
13611 (format "\"[%s]\""
13612 (substring org-log-note-state 1 -1)))
13613 (t (format "\"%s\"" org-log-note-state))))
13614 (cons "%S"
13615 (cond
13616 ((not org-log-note-previous-state) "")
13617 ((string-match-p org-ts-regexp
13618 org-log-note-previous-state)
13619 (format "\"[%s]\""
13620 (substring
13621 org-log-note-previous-state 1 -1)))
13622 (t (format "\"%s\""
13623 org-log-note-previous-state)))))))
13624 (when lines (setq note (concat note " \\\\")))
13625 (push note lines))
13626 (when (and lines (not org-note-abort))
13627 (with-current-buffer (marker-buffer org-log-note-marker)
13628 (org-with-wide-buffer
13629 ;; Find location for the new note.
13630 (goto-char org-log-note-marker)
13631 (set-marker org-log-note-marker nil)
13632 ;; Note associated to a clock is to be located right after
13633 ;; the clock. Do not move point.
13634 (unless (eq org-log-note-purpose 'clock-out)
13635 (goto-char (org-log-beginning t)))
13636 ;; Make sure point is at the beginning of an empty line.
13637 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13638 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13639 ;; In an existing list, add a new item at the top level.
13640 ;; Otherwise, indent line like a regular one.
13641 (let ((itemp (org-in-item-p)))
13642 (if itemp
13643 (indent-line-to
13644 (let ((struct (save-excursion
13645 (goto-char itemp) (org-list-struct))))
13646 (org-list-get-ind (org-list-get-top-point struct) struct)))
13647 (org-indent-line)))
13648 (insert (org-list-bullet-string "-") (pop lines))
13649 (let ((ind (org-list-item-body-column (line-beginning-position))))
13650 (dolist (line lines)
13651 (insert "\n")
13652 (indent-line-to ind)
13653 (insert line)))
13654 (message "Note stored")
13655 (org-back-to-heading t)
13656 (org-cycle-hide-drawers 'children))
13657 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13658 ;; from within `org-add-log-note' because `buffer-undo-list'
13659 ;; is then modified outside of `org-with-remote-undo'.
13660 (when (eq this-command 'org-agenda-todo)
13661 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13662 ;; Don't add undo information when called from `org-agenda-todo'.
13663 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13664 (set-window-configuration org-log-note-window-configuration)
13665 (with-current-buffer (marker-buffer org-log-note-return-to)
13666 (goto-char org-log-note-return-to))
13667 (move-marker org-log-note-return-to nil)
13668 (when org-log-post-message (message "%s" org-log-post-message))))
13670 (defun org-remove-empty-drawer-at (pos)
13671 "Remove an empty drawer at position POS.
13672 POS may also be a marker."
13673 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13674 (org-with-wide-buffer
13675 (goto-char pos)
13676 (let ((drawer (org-element-at-point)))
13677 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13678 (not (org-element-property :contents-begin drawer)))
13679 (delete-region (org-element-property :begin drawer)
13680 (progn (goto-char (org-element-property :end drawer))
13681 (skip-chars-backward " \r\t\n")
13682 (forward-line)
13683 (point))))))))
13685 (defvar org-ts-type nil)
13686 (defun org-sparse-tree (&optional arg type)
13687 "Create a sparse tree, prompt for the details.
13688 This command can create sparse trees. You first need to select the type
13689 of match used to create the tree:
13691 t Show all TODO entries.
13692 T Show entries with a specific TODO keyword.
13693 m Show entries selected by a tags/property match.
13694 p Enter a property name and its value (both with completion on existing
13695 names/values) and show entries with that property.
13696 r Show entries matching a regular expression (`/' can be used as well).
13697 b Show deadlines and scheduled items before a date.
13698 a Show deadlines and scheduled items after a date.
13699 d Show deadlines due within `org-deadline-warning-days'.
13700 D Show deadlines and scheduled items between a date range."
13701 (interactive "P")
13702 (setq type (or type org-sparse-tree-default-date-type))
13703 (setq org-ts-type type)
13704 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13705 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13706 \[c]ycle through date types: %s"
13707 (cl-case type
13708 (all "all timestamps")
13709 (scheduled "only scheduled")
13710 (deadline "only deadline")
13711 (active "only active timestamps")
13712 (inactive "only inactive timestamps")
13713 (closed "with a closed time-stamp")
13714 (otherwise "scheduled/deadline")))
13715 (let ((answer (read-char-exclusive)))
13716 (cl-case answer
13718 (org-sparse-tree
13720 (cadr
13721 (memq type '(nil all scheduled deadline active inactive closed)))))
13722 (?d (call-interactively 'org-check-deadlines))
13723 (?b (call-interactively 'org-check-before-date))
13724 (?a (call-interactively 'org-check-after-date))
13725 (?D (call-interactively 'org-check-dates-range))
13726 (?t (call-interactively 'org-show-todo-tree))
13727 (?T (org-show-todo-tree '(4)))
13728 (?m (call-interactively 'org-match-sparse-tree))
13729 ((?p ?P)
13730 (let* ((kwd (completing-read
13731 "Property: " (mapcar #'list (org-buffer-property-keys))))
13732 (value (completing-read
13733 "Value: " (mapcar #'list (org-property-values kwd)))))
13734 (unless (string-match "\\`{.*}\\'" value)
13735 (setq value (concat "\"" value "\"")))
13736 (org-match-sparse-tree arg (concat kwd "=" value))))
13737 ((?r ?R ?/) (call-interactively 'org-occur))
13738 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13740 (defvar-local org-occur-highlights nil
13741 "List of overlays used for occur matches.")
13742 (defvar-local org-occur-parameters nil
13743 "Parameters of the active org-occur calls.
13744 This is a list, each call to org-occur pushes as cons cell,
13745 containing the regular expression and the callback, onto the list.
13746 The list can contain several entries if `org-occur' has been called
13747 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13748 will only contain one set of parameters. When the highlights are
13749 removed (for example with `C-c C-c', or with the next edit (depending
13750 on `org-remove-highlights-with-change'), this variable is emptied
13751 as well.")
13753 (defun org-occur (regexp &optional keep-previous callback)
13754 "Make a compact tree which shows all matches of REGEXP.
13756 The tree will show the lines where the regexp matches, and any other context
13757 defined in `org-show-context-detail', which see.
13759 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13760 done by a previous call to `org-occur' will be kept, to allow stacking of
13761 calls to this command.
13763 Optional argument CALLBACK can be a function of no argument. In this case,
13764 it is called with point at the end of the match, match data being set
13765 accordingly. Current match is shown only if the return value is non-nil.
13766 The function must neither move point nor alter narrowing."
13767 (interactive "sRegexp: \nP")
13768 (when (equal regexp "")
13769 (user-error "Regexp cannot be empty"))
13770 (unless keep-previous
13771 (org-remove-occur-highlights nil nil t))
13772 (push (cons regexp callback) org-occur-parameters)
13773 (let ((cnt 0))
13774 (save-excursion
13775 (goto-char (point-min))
13776 (when (or (not keep-previous) ; do not want to keep
13777 (not org-occur-highlights)) ; no previous matches
13778 ;; hide everything
13779 (org-overview))
13780 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13781 (isearch-no-upper-case-p regexp t)
13782 org-occur-case-fold-search)))
13783 (while (re-search-forward regexp nil t)
13784 (when (or (not callback)
13785 (save-match-data (funcall callback)))
13786 (setq cnt (1+ cnt))
13787 (when org-highlight-sparse-tree-matches
13788 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13789 (org-show-context 'occur-tree)))))
13790 (when org-remove-highlights-with-change
13791 (add-hook 'before-change-functions 'org-remove-occur-highlights
13792 nil 'local))
13793 (unless org-sparse-tree-open-archived-trees
13794 (org-hide-archived-subtrees (point-min) (point-max)))
13795 (run-hooks 'org-occur-hook)
13796 (when (called-interactively-p 'interactive)
13797 (message "%d match(es) for regexp %s" cnt regexp))
13798 cnt))
13800 (defun org-occur-next-match (&optional n _reset)
13801 "Function for `next-error-function' to find sparse tree matches.
13802 N is the number of matches to move, when negative move backwards.
13803 This function always goes back to the starting point when no
13804 match is found."
13805 (let* ((limit (if (< n 0) (point-min) (point-max)))
13806 (search-func (if (< n 0)
13807 'previous-single-char-property-change
13808 'next-single-char-property-change))
13809 (n (abs n))
13810 (pos (point))
13812 (catch 'exit
13813 (while (setq p1 (funcall search-func (point) 'org-type))
13814 (when (equal p1 limit)
13815 (goto-char pos)
13816 (user-error "No more matches"))
13817 (when (equal (get-char-property p1 'org-type) 'org-occur)
13818 (setq n (1- n))
13819 (when (= n 0)
13820 (goto-char p1)
13821 (throw 'exit (point))))
13822 (goto-char p1))
13823 (goto-char p1)
13824 (user-error "No more matches"))))
13826 (defun org-show-context (&optional key)
13827 "Make sure point and context are visible.
13828 Optional argument KEY, when non-nil, is a symbol. See
13829 `org-show-context-detail' for allowed values and how much is to
13830 be shown."
13831 (org-show-set-visibility
13832 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13833 ((cdr (assq key org-show-context-detail)))
13834 (t (cdr (assq 'default org-show-context-detail))))))
13836 (defun org-show-set-visibility (detail)
13837 "Set visibility around point according to DETAIL.
13838 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13839 `tree', `canonical' or t. See `org-show-context-detail' for more
13840 information."
13841 ;; Show current heading and possibly its entry, following headline
13842 ;; or all children.
13843 (if (and (org-at-heading-p) (not (eq detail 'local)))
13844 (org-flag-heading nil)
13845 (org-show-entry)
13846 ;; If point is hidden within a drawer or a block, make sure to
13847 ;; expose it.
13848 (dolist (o (overlays-at (point)))
13849 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13850 (delete-overlay o)))
13851 (unless (org-before-first-heading-p)
13852 (org-with-limited-levels
13853 (cl-case detail
13854 ((tree canonical t) (org-show-children))
13855 ((nil minimal ancestors))
13856 (t (save-excursion
13857 (outline-next-heading)
13858 (org-flag-heading nil)))))))
13859 ;; Show all siblings.
13860 (when (eq detail 'lineage) (org-show-siblings))
13861 ;; Show ancestors, possibly with their children.
13862 (when (memq detail '(ancestors lineage tree canonical t))
13863 (save-excursion
13864 (while (org-up-heading-safe)
13865 (org-flag-heading nil)
13866 (when (memq detail '(canonical t)) (org-show-entry))
13867 (when (memq detail '(tree canonical t)) (org-show-children))))))
13869 (defvar org-reveal-start-hook nil
13870 "Hook run before revealing a location.")
13872 (defun org-reveal (&optional siblings)
13873 "Show current entry, hierarchy above it, and the following headline.
13875 This can be used to show a consistent set of context around
13876 locations exposed with `org-show-context'.
13878 With optional argument SIBLINGS, on each level of the hierarchy all
13879 siblings are shown. This repairs the tree structure to what it would
13880 look like when opened with hierarchical calls to `org-cycle'.
13882 With a \\[universal-argument] \\[universal-argument] prefix, \
13883 go to the parent and show the entire tree."
13884 (interactive "P")
13885 (run-hooks 'org-reveal-start-hook)
13886 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13887 ((equal siblings '(16))
13888 (save-excursion
13889 (when (org-up-heading-safe)
13890 (org-show-subtree)
13891 (run-hook-with-args 'org-cycle-hook 'subtree))))
13892 (t (org-show-set-visibility 'lineage))))
13894 (defun org-highlight-new-match (beg end)
13895 "Highlight from BEG to END and mark the highlight is an occur headline."
13896 (let ((ov (make-overlay beg end)))
13897 (overlay-put ov 'face 'secondary-selection)
13898 (overlay-put ov 'org-type 'org-occur)
13899 (push ov org-occur-highlights)))
13901 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13902 "Remove the occur highlights from the buffer.
13903 BEG and END are ignored. If NOREMOVE is nil, remove this function
13904 from the `before-change-functions' in the current buffer."
13905 (interactive)
13906 (unless org-inhibit-highlight-removal
13907 (mapc #'delete-overlay org-occur-highlights)
13908 (setq org-occur-highlights nil)
13909 (setq org-occur-parameters nil)
13910 (unless noremove
13911 (remove-hook 'before-change-functions
13912 'org-remove-occur-highlights 'local))))
13914 ;;;; Priorities
13916 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13917 "Regular expression matching the priority indicator.")
13919 (defvar org-remove-priority-next-time nil)
13921 (defun org-priority-up ()
13922 "Increase the priority of the current item."
13923 (interactive)
13924 (org-priority 'up))
13926 (defun org-priority-down ()
13927 "Decrease the priority of the current item."
13928 (interactive)
13929 (org-priority 'down))
13931 (defun org-priority (&optional action _show)
13932 "Change the priority of an item.
13933 ACTION can be `set', `up', `down', or a character."
13934 (interactive "P")
13935 (if (equal action '(4))
13936 (org-show-priority)
13937 (unless org-enable-priority-commands
13938 (user-error "Priority commands are disabled"))
13939 (setq action (or action 'set))
13940 (let (current new news have remove)
13941 (save-excursion
13942 (org-back-to-heading t)
13943 (when (looking-at org-priority-regexp)
13944 (setq current (string-to-char (match-string 2))
13945 have t))
13946 (cond
13947 ((eq action 'remove)
13948 (setq remove t new ?\ ))
13949 ((or (eq action 'set)
13950 (integerp action))
13951 (if (not (eq action 'set))
13952 (setq new action)
13953 (message "Priority %c-%c, SPC to remove: "
13954 org-highest-priority org-lowest-priority)
13955 (save-match-data
13956 (setq new (read-char-exclusive))))
13957 (when (and (= (upcase org-highest-priority) org-highest-priority)
13958 (= (upcase org-lowest-priority) org-lowest-priority))
13959 (setq new (upcase new)))
13960 (cond ((equal new ?\ ) (setq remove t))
13961 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13962 (user-error "Priority must be between `%c' and `%c'"
13963 org-highest-priority org-lowest-priority))))
13964 ((eq action 'up)
13965 (setq new (if have
13966 (1- current) ; normal cycling
13967 ;; last priority was empty
13968 (if (eq last-command this-command)
13969 org-lowest-priority ; wrap around empty to lowest
13970 ;; default
13971 (if org-priority-start-cycle-with-default
13972 org-default-priority
13973 (1- org-default-priority))))))
13974 ((eq action 'down)
13975 (setq new (if have
13976 (1+ current) ; normal cycling
13977 ;; last priority was empty
13978 (if (eq last-command this-command)
13979 org-highest-priority ; wrap around empty to highest
13980 ;; default
13981 (if org-priority-start-cycle-with-default
13982 org-default-priority
13983 (1+ org-default-priority))))))
13984 (t (user-error "Invalid action")))
13985 (when (or (< (upcase new) org-highest-priority)
13986 (> (upcase new) org-lowest-priority))
13987 (if (and (memq action '(up down))
13988 (not have) (not (eq last-command this-command)))
13989 ;; `new' is from default priority
13990 (error
13991 "The default can not be set, see `org-default-priority' why")
13992 ;; normal cycling: `new' is beyond highest/lowest priority
13993 ;; and is wrapped around to the empty priority
13994 (setq remove t)))
13995 (setq news (format "%c" new))
13996 (if have
13997 (if remove
13998 (replace-match "" t t nil 1)
13999 (replace-match news t t nil 2))
14000 (if remove
14001 (user-error "No priority cookie found in line")
14002 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14003 (if (match-end 2)
14004 (progn
14005 (goto-char (match-end 2))
14006 (insert " [#" news "]"))
14007 (goto-char (match-beginning 3))
14008 (insert "[#" news "] "))))
14009 (org-set-tags nil 'align))
14010 (if remove
14011 (message "Priority removed")
14012 (message "Priority of current item set to %s" news)))))
14014 (defun org-show-priority ()
14015 "Show the priority of the current item.
14016 This priority is composed of the main priority given with the [#A] cookies,
14017 and by additional input from the age of a schedules or deadline entry."
14018 (interactive)
14019 (let ((pri (if (eq major-mode 'org-agenda-mode)
14020 (org-get-at-bol 'priority)
14021 (save-excursion
14022 (save-match-data
14023 (beginning-of-line)
14024 (and (looking-at org-heading-regexp)
14025 (org-get-priority (match-string 0))))))))
14026 (message "Priority is %d" (if pri pri -1000))))
14028 (defun org-get-priority (s)
14029 "Find priority cookie and return priority."
14030 (save-match-data
14031 (if (functionp org-get-priority-function)
14032 (funcall org-get-priority-function)
14033 (if (not (string-match org-priority-regexp s))
14034 (* 1000 (- org-lowest-priority org-default-priority))
14035 (* 1000 (- org-lowest-priority
14036 (string-to-char (match-string 2 s))))))))
14038 ;;;; Tags
14040 (defvar org-agenda-archives-mode)
14041 (defvar org-map-continue-from nil
14042 "Position from where mapping should continue.
14043 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14045 (defvar org-scanner-tags nil
14046 "The current tag list while the tags scanner is running.")
14048 (defvar org-trust-scanner-tags nil
14049 "Should `org-get-tags-at' use the tags for the scanner.
14050 This is for internal dynamical scoping only.
14051 When this is non-nil, the function `org-get-tags-at' will return the value
14052 of `org-scanner-tags' instead of building the list by itself. This
14053 can lead to large speed-ups when the tags scanner is used in a file with
14054 many entries, and when the list of tags is retrieved, for example to
14055 obtain a list of properties. Building the tags list for each entry in such
14056 a file becomes an N^2 operation - but with this variable set, it scales
14057 as N.")
14059 (defvar org--matcher-tags-todo-only nil)
14061 (defun org-scan-tags (action matcher todo-only &optional start-level)
14062 "Scan headline tags with inheritance and produce output ACTION.
14064 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14065 or `agenda' to produce an entry list for an agenda view. It can also be
14066 a Lisp form or a function that should be called at each matched headline, in
14067 this case the return value is a list of all return values from these calls.
14069 MATCHER is a function accepting three arguments, returning
14070 a non-nil value whenever a given set of tags qualifies a headline
14071 for inclusion. See `org-make-tags-matcher' for more information.
14072 As a special case, it can also be set to t (respectively nil) in
14073 order to match all (respectively none) headline.
14075 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14076 included in the output.
14078 START-LEVEL can be a string with asterisks, reducing the scope to
14079 headlines matching this string."
14080 (require 'org-agenda)
14081 (let* ((re (concat "^"
14082 (if start-level
14083 ;; Get the correct level to match
14084 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14085 org-outline-regexp)
14086 " *\\(\\<\\("
14087 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14088 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14089 (props (list 'face 'default
14090 'done-face 'org-agenda-done
14091 'undone-face 'default
14092 'mouse-face 'highlight
14093 'org-not-done-regexp org-not-done-regexp
14094 'org-todo-regexp org-todo-regexp
14095 'org-complex-heading-regexp org-complex-heading-regexp
14096 'help-echo
14097 (format "mouse-2 or RET jump to org file %s"
14098 (abbreviate-file-name
14099 (or (buffer-file-name (buffer-base-buffer))
14100 (buffer-name (buffer-base-buffer)))))))
14101 (org-map-continue-from nil)
14102 lspos tags tags-list
14103 (tags-alist (list (cons 0 org-file-tags)))
14104 (llast 0) rtn rtn1 level category i txt
14105 todo marker entry priority
14106 ts-date ts-date-type ts-date-pair)
14107 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14108 (setq action (list 'lambda nil action)))
14109 (save-excursion
14110 (goto-char (point-min))
14111 (when (eq action 'sparse-tree)
14112 (org-overview)
14113 (org-remove-occur-highlights))
14114 (while (let (case-fold-search)
14115 (re-search-forward re nil t))
14116 (setq org-map-continue-from nil)
14117 (catch :skip
14118 (setq todo
14119 ;; TODO: is the 1-2 difference a bug?
14120 (when (match-end 1) (match-string-no-properties 2))
14121 tags (when (match-end 4) (match-string-no-properties 4)))
14122 (goto-char (setq lspos (match-beginning 0)))
14123 (setq level (org-reduced-level (org-outline-level))
14124 category (org-get-category))
14125 (when (eq action 'agenda)
14126 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14127 ts-date (car ts-date-pair)
14128 ts-date-type (cdr ts-date-pair)))
14129 (setq i llast llast level)
14130 ;; remove tag lists from same and sublevels
14131 (while (>= i level)
14132 (when (setq entry (assoc i tags-alist))
14133 (setq tags-alist (delete entry tags-alist)))
14134 (setq i (1- i)))
14135 ;; add the next tags
14136 (when tags
14137 (setq tags (org-split-string tags ":")
14138 tags-alist
14139 (cons (cons level tags) tags-alist)))
14140 ;; compile tags for current headline
14141 (setq tags-list
14142 (if org-use-tag-inheritance
14143 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14144 tags)
14145 org-scanner-tags tags-list)
14146 (when org-use-tag-inheritance
14147 (setcdr (car tags-alist)
14148 (mapcar (lambda (x)
14149 (setq x (copy-sequence x))
14150 (org-add-prop-inherited x))
14151 (cdar tags-alist))))
14152 (when (and tags org-use-tag-inheritance
14153 (or (not (eq t org-use-tag-inheritance))
14154 org-tags-exclude-from-inheritance))
14155 ;; Selective inheritance, remove uninherited ones.
14156 (setcdr (car tags-alist)
14157 (org-remove-uninherited-tags (cdar tags-alist))))
14158 (when (and
14160 ;; eval matcher only when the todo condition is OK
14161 (and (or (not todo-only) (member todo org-todo-keywords-1))
14162 (if (functionp matcher)
14163 (let ((case-fold-search t) (org-trust-scanner-tags t))
14164 (funcall matcher todo tags-list level))
14165 matcher))
14167 ;; Call the skipper, but return t if it does not
14168 ;; skip, so that the `and' form continues evaluating.
14169 (progn
14170 (unless (eq action 'sparse-tree) (org-agenda-skip))
14173 ;; Check if timestamps are deselecting this entry
14174 (or (not todo-only)
14175 (and (member todo org-todo-keywords-1)
14176 (or (not org-agenda-tags-todo-honor-ignore-options)
14177 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14179 ;; select this headline
14180 (cond
14181 ((eq action 'sparse-tree)
14182 (and org-highlight-sparse-tree-matches
14183 (org-get-heading) (match-end 0)
14184 (org-highlight-new-match
14185 (match-beginning 1) (match-end 1)))
14186 (org-show-context 'tags-tree))
14187 ((eq action 'agenda)
14188 (setq txt (org-agenda-format-item
14190 (concat
14191 (if (eq org-tags-match-list-sublevels 'indented)
14192 (make-string (1- level) ?.) "")
14193 (org-get-heading))
14194 (make-string level ?\s)
14195 category
14196 tags-list)
14197 priority (org-get-priority txt))
14198 (goto-char lspos)
14199 (setq marker (org-agenda-new-marker))
14200 (org-add-props txt props
14201 'org-marker marker 'org-hd-marker marker 'org-category category
14202 'todo-state todo
14203 'ts-date ts-date
14204 'priority priority
14205 'type (concat "tagsmatch" ts-date-type))
14206 (push txt rtn))
14207 ((functionp action)
14208 (setq org-map-continue-from nil)
14209 (save-excursion
14210 (setq rtn1 (funcall action))
14211 (push rtn1 rtn)))
14212 (t (user-error "Invalid action")))
14214 ;; if we are to skip sublevels, jump to end of subtree
14215 (unless org-tags-match-list-sublevels
14216 (org-end-of-subtree t)
14217 (backward-char 1))))
14218 ;; Get the correct position from where to continue
14219 (if org-map-continue-from
14220 (goto-char org-map-continue-from)
14221 (and (= (point) lspos) (end-of-line 1)))))
14222 (when (and (eq action 'sparse-tree)
14223 (not org-sparse-tree-open-archived-trees))
14224 (org-hide-archived-subtrees (point-min) (point-max)))
14225 (nreverse rtn)))
14227 (defun org-remove-uninherited-tags (tags)
14228 "Remove all tags that are not inherited from the list TAGS."
14229 (cond
14230 ((eq org-use-tag-inheritance t)
14231 (if org-tags-exclude-from-inheritance
14232 (org-delete-all org-tags-exclude-from-inheritance tags)
14233 tags))
14234 ((not org-use-tag-inheritance) nil)
14235 ((stringp org-use-tag-inheritance)
14236 (delq nil (mapcar
14237 (lambda (x)
14238 (if (and (string-match org-use-tag-inheritance x)
14239 (not (member x org-tags-exclude-from-inheritance)))
14240 x nil))
14241 tags)))
14242 ((listp org-use-tag-inheritance)
14243 (delq nil (mapcar
14244 (lambda (x)
14245 (if (member x org-use-tag-inheritance) x nil))
14246 tags)))))
14248 (defun org-match-sparse-tree (&optional todo-only match)
14249 "Create a sparse tree according to tags string MATCH.
14251 MATCH is a string with match syntax. It can contain a selection
14252 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14253 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14254 those. See the manual for details.
14256 If optional argument TODO-ONLY is non-nil, only select lines that
14257 are also TODO tasks."
14258 (interactive "P")
14259 (org-agenda-prepare-buffers (list (current-buffer)))
14260 (let ((org--matcher-tags-todo-only todo-only))
14261 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14262 org--matcher-tags-todo-only)))
14264 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14266 (defvar org-cached-props nil)
14267 (defun org-cached-entry-get (pom property)
14268 (if (or (eq t org-use-property-inheritance)
14269 (and (stringp org-use-property-inheritance)
14270 (let ((case-fold-search t))
14271 (string-match-p org-use-property-inheritance property)))
14272 (and (listp org-use-property-inheritance)
14273 (member-ignore-case property org-use-property-inheritance)))
14274 ;; Caching is not possible, check it directly.
14275 (org-entry-get pom property 'inherit)
14276 ;; Get all properties, so we can do complicated checks easily.
14277 (cdr (assoc-string property
14278 (or org-cached-props
14279 (setq org-cached-props (org-entry-properties pom)))
14280 t))))
14282 (defun org-global-tags-completion-table (&optional files)
14283 "Return the list of all tags in all agenda buffer/files.
14284 Optional FILES argument is a list of files which can be used
14285 instead of the agenda files."
14286 (save-excursion
14287 (org-uniquify
14288 (delq nil
14289 (apply #'append
14290 (mapcar
14291 (lambda (file)
14292 (set-buffer (find-file-noselect file))
14293 (mapcar (lambda (x)
14294 (and (stringp (car-safe x))
14295 (list (car-safe x))))
14296 (or org-current-tag-alist (org-get-buffer-tags))))
14297 (if (car-safe files) files
14298 (org-agenda-files))))))))
14300 (defun org-make-tags-matcher (match)
14301 "Create the TAGS/TODO matcher form for the selection string MATCH.
14303 Returns a cons of the selection string MATCH and a function
14304 implementing the matcher.
14306 The matcher is to be called at an Org entry, with point on the
14307 headline, and returns non-nil if the entry matches the selection
14308 string MATCH. It must be called with three arguments: the TODO
14309 keyword at the entry (or nil if none), the list of all tags at
14310 the entry including inherited ones and the reduced level of the
14311 headline. Additionally, the category of the entry, if any, must
14312 be specified as the text property `org-category' on the headline.
14314 This function sets the variable `org--matcher-tags-todo-only' to
14315 a non-nil value if the matcher restricts matching to TODO
14316 entries, otherwise it is not touched.
14318 See also `org-scan-tags'."
14319 (unless match
14320 ;; Get a new match request, with completion against the global
14321 ;; tags table and the local tags in current buffer.
14322 (let ((org-last-tags-completion-table
14323 (org-uniquify
14324 (delq nil (append (org-get-buffer-tags)
14325 (org-global-tags-completion-table))))))
14326 (setq match
14327 (completing-read
14328 "Match: "
14329 'org-tags-completion-function nil nil nil 'org-tags-history))))
14331 (let ((match0 match)
14332 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14333 (start 0)
14334 tagsmatch todomatch tagsmatcher todomatcher)
14336 ;; Expand group tags.
14337 (setq match (org-tags-expand match))
14339 ;; Check if there is a TODO part of this match, which would be the
14340 ;; part after a "/". To make sure that this slash is not part of
14341 ;; a property value to be matched against, we also check that
14342 ;; there is no / after that slash. First, find the last slash.
14343 (let ((s 0))
14344 (while (string-match "/+" match s)
14345 (setq start (match-beginning 0))
14346 (setq s (match-end 0))))
14347 (if (and (string-match "/+" match start)
14348 (not (string-match-p "\"" match start)))
14349 ;; Match contains also a TODO-matching request.
14350 (progn
14351 (setq tagsmatch (substring match 0 (match-beginning 0)))
14352 (setq todomatch (substring match (match-end 0)))
14353 (when (string-prefix-p "!" todomatch)
14354 (setq org--matcher-tags-todo-only t)
14355 (setq todomatch (substring todomatch 1)))
14356 (when (string-match "\\`\\s-*\\'" todomatch)
14357 (setq todomatch nil)))
14358 ;; Only matching tags.
14359 (setq tagsmatch match)
14360 (setq todomatch nil))
14362 ;; Make the tags matcher.
14363 (when (org-string-nw-p tagsmatch)
14364 (let ((orlist nil)
14365 (orterms (org-split-string tagsmatch "|"))
14366 term)
14367 (while (setq term (pop orterms))
14368 (while (and (equal (substring term -1) "\\") orterms)
14369 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14370 (while (string-match re term)
14371 (let* ((rest (substring term (match-end 0)))
14372 (minus (and (match-end 1)
14373 (equal (match-string 1 term) "-")))
14374 (tag (save-match-data
14375 (replace-regexp-in-string
14376 "\\\\-" "-" (match-string 2 term))))
14377 (regexp (eq (string-to-char tag) ?{))
14378 (levelp (match-end 4))
14379 (propp (match-end 5))
14381 (cond
14382 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14383 (levelp
14384 `(,(org-op-to-function (match-string 3 term))
14385 level
14386 ,(string-to-number (match-string 4 term))))
14387 (propp
14388 (let* ((gv (pcase (upcase (match-string 5 term))
14389 ("CATEGORY"
14390 '(get-text-property (point) 'org-category))
14391 ("TODO" 'todo)
14392 (p `(org-cached-entry-get nil ,p))))
14393 (pv (match-string 7 term))
14394 (regexp (eq (string-to-char pv) ?{))
14395 (strp (eq (string-to-char pv) ?\"))
14396 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14397 (po (org-op-to-function (match-string 6 term)
14398 (if timep 'time strp))))
14399 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14400 (when timep (setq pv (org-matcher-time pv)))
14401 (cond ((and regexp (eq po 'org<>))
14402 `(not (string-match ,pv (or ,gv ""))))
14403 (regexp `(string-match ,pv (or ,gv "")))
14404 (strp `(,po (or ,gv "") ,pv))
14406 `(,po
14407 (string-to-number (or ,gv ""))
14408 ,(string-to-number pv))))))
14409 (t `(member ,tag tags-list)))))
14410 (push (if minus `(not ,mm) mm) tagsmatcher)
14411 (setq term rest)))
14412 (push `(and ,@tagsmatcher) orlist)
14413 (setq tagsmatcher nil))
14414 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14416 ;; Make the TODO matcher.
14417 (when (org-string-nw-p todomatch)
14418 (let ((orlist nil))
14419 (dolist (term (org-split-string todomatch "|"))
14420 (while (string-match re term)
14421 (let* ((minus (and (match-end 1)
14422 (equal (match-string 1 term) "-")))
14423 (kwd (match-string 2 term))
14424 (regexp (eq (string-to-char kwd) ?{))
14425 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14426 `(equal todo ,kwd))))
14427 (push (if minus `(not ,mm) mm) todomatcher))
14428 (setq term (substring term (match-end 0))))
14429 (push (if (> (length todomatcher) 1)
14430 (cons 'and todomatcher)
14431 (car todomatcher))
14432 orlist)
14433 (setq todomatcher nil))
14434 (setq todomatcher (cons 'or orlist))))
14436 ;; Return the string and function of the matcher. If no
14437 ;; tags-specific or todo-specific matcher exists, match
14438 ;; everything.
14439 (let ((matcher (if (and tagsmatcher todomatcher)
14440 `(and ,tagsmatcher ,todomatcher)
14441 (or tagsmatcher todomatcher t))))
14442 (when org--matcher-tags-todo-only
14443 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14444 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14446 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14447 "Expand group tags in MATCH.
14449 This replaces every group tag in MATCH with a regexp tag search.
14450 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14451 will be replaced like this:
14453 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14454 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14455 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14457 Replacing by a regexp preserves the structure of the match.
14458 E.g., this expansion
14460 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14462 will match anything tagged with \"Lab\" and \"Home\", or tagged
14463 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14465 A group tag in MATCH can contain regular expressions of its own.
14466 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14467 will be replaced like this:
14469 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14471 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14472 assumed to be a single group tag, and the function will return
14473 the list of tags in this group.
14475 When DOWNCASE is non-nil, expand downcased TAGS."
14476 (if org-group-tags
14477 (let* ((case-fold-search t)
14478 (stable org-mode-syntax-table)
14479 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14480 (taggroups (if downcased
14481 (mapcar (lambda (tg) (mapcar #'downcase tg))
14482 taggroups)
14483 taggroups))
14484 (taggroups-keys (mapcar #'car taggroups))
14485 (return-match (if downcased (downcase match) match))
14486 (count 0)
14487 (work-already-expanded tags-already-expanded)
14488 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14489 ;; @ and _ are allowed as word-components in tags.
14490 (modify-syntax-entry ?@ "w" stable)
14491 (modify-syntax-entry ?_ "w" stable)
14492 ;; Temporarily replace regexp-expressions in the match-expression.
14493 (while (string-match "{.+?}" return-match)
14494 (cl-incf count)
14495 (push (match-string 0 return-match) regexps-in-match)
14496 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14497 (while (and taggroups-keys
14498 (with-syntax-table stable
14499 (string-match
14500 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14501 (regexp-opt taggroups-keys) "\\>\\)")
14502 return-match)))
14503 (let* ((dir (match-string 1 return-match))
14504 (tag (match-string 2 return-match))
14505 (tag (if downcased (downcase tag) tag)))
14506 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14507 (member tag work-already-expanded))
14508 (setq tags-in-group (assoc tag taggroups))
14509 (push tag work-already-expanded)
14510 ;; Recursively expand each tag in the group, if the tag hasn't
14511 ;; already been expanded. Restore the match-data after all recursive calls.
14512 (save-match-data
14513 (let (tags-expanded)
14514 (dolist (x (cdr tags-in-group))
14515 (if (and (member x taggroups-keys)
14516 (not (member x work-already-expanded)))
14517 (setq tags-expanded
14518 (delete-dups
14519 (append
14520 (org-tags-expand x t downcased
14521 work-already-expanded)
14522 tags-expanded)))
14523 (setq tags-expanded
14524 (append (list x) tags-expanded)))
14525 (setq work-already-expanded
14526 (delete-dups
14527 (append tags-expanded
14528 work-already-expanded))))
14529 (setq tags-in-group
14530 (delete-dups (cons (car tags-in-group)
14531 tags-expanded)))))
14532 ;; Filter tag-regexps from tags.
14533 (setq regexp-in-group-escaped
14534 (delq nil (mapcar (lambda (x)
14535 (if (stringp x)
14536 (and (equal "{" (substring x 0 1))
14537 (equal "}" (substring x -1))
14540 tags-in-group))
14541 regexp-in-group
14542 (mapcar (lambda (x)
14543 (substring x 1 -1))
14544 regexp-in-group-escaped)
14545 tags-in-group
14546 (delq nil (mapcar (lambda (x)
14547 (if (stringp x)
14548 (and (not (equal "{" (substring x 0 1)))
14549 (not (equal "}" (substring x -1)))
14552 tags-in-group)))
14553 ;; If single-as-list, do no more in the while-loop.
14554 (if (not single-as-list)
14555 (progn
14556 (when regexp-in-group
14557 (setq regexp-in-group
14558 (concat "\\|"
14559 (mapconcat 'identity regexp-in-group
14560 "\\|"))))
14561 (setq tags-in-group
14562 (concat dir
14563 "{\\<"
14564 (regexp-opt tags-in-group)
14565 "\\>"
14566 regexp-in-group
14567 "}"))
14568 (when (stringp tags-in-group)
14569 (org-add-props tags-in-group '(grouptag t)))
14570 (setq return-match
14571 (replace-match tags-in-group t t return-match)))
14572 (setq tags-in-group
14573 (append regexp-in-group-escaped tags-in-group))))
14574 (setq taggroups-keys (delete tag taggroups-keys))))
14575 ;; Add the regular expressions back into the match-expression again.
14576 (while regexps-in-match
14577 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14578 (pop regexps-in-match)
14579 return-match t t))
14580 (cl-decf count))
14581 (if single-as-list
14582 (if tags-in-group tags-in-group (list return-match))
14583 return-match))
14584 (if single-as-list
14585 (list (if downcased (downcase match) match))
14586 match)))
14588 (defun org-op-to-function (op &optional stringp)
14589 "Turn an operator into the appropriate function."
14590 (setq op
14591 (cond
14592 ((equal op "<" ) '(< string< org-time<))
14593 ((equal op ">" ) '(> org-string> org-time>))
14594 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14595 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14596 ((member op '("=" "==")) '(= string= org-time=))
14597 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14598 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14600 (defun org<> (a b) (not (= a b)))
14601 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14602 (defun org-string>= (a b) (not (string< a b)))
14603 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14604 (defun org-string<> (a b) (not (string= a b)))
14605 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14606 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14607 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14608 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14609 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14610 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14611 (defun org-2ft (s)
14612 "Convert S to a floating point time.
14613 If S is already a number, just return it. If it is a string, parse
14614 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14615 (cond
14616 ((numberp s) s)
14617 ((stringp s)
14618 (condition-case nil
14619 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14620 (error 0.)))
14621 (t 0.)))
14623 (defun org-time-today ()
14624 "Time in seconds today at 0:00.
14625 Returns the float number of seconds since the beginning of the
14626 epoch to the beginning of today (00:00)."
14627 (float-time (apply 'encode-time
14628 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14630 (defun org-matcher-time (s)
14631 "Interpret a time comparison value."
14632 (save-match-data
14633 (cond
14634 ((string= s "<now>") (float-time))
14635 ((string= s "<today>") (org-time-today))
14636 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14637 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14638 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14639 (+ (org-time-today)
14640 (* (string-to-number (match-string 1 s))
14641 (cdr (assoc (match-string 2 s)
14642 '(("d" . 86400.0) ("w" . 604800.0)
14643 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14644 (t (org-2ft s)))))
14646 (defun org-match-any-p (re list)
14647 "Does re match any element of list?"
14648 (setq list (mapcar (lambda (x) (string-match re x)) list))
14649 (delq nil list))
14651 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14652 (defvar org-tags-overlay (make-overlay 1 1))
14653 (delete-overlay org-tags-overlay)
14655 (defun org-get-local-tags-at (&optional pos)
14656 "Get a list of tags defined in the current headline."
14657 (org-get-tags-at pos 'local))
14659 (defun org-get-local-tags ()
14660 "Get a list of tags defined in the current headline."
14661 (org-get-tags-at nil 'local))
14663 (defun org-get-tags-at (&optional pos local)
14664 "Get a list of all headline tags applicable at POS.
14665 POS defaults to point. If tags are inherited, the list contains
14666 the targets in the same sequence as the headlines appear, i.e.
14667 the tags of the current headline come last.
14668 When LOCAL is non-nil, only return tags from the current headline,
14669 ignore inherited ones."
14670 (interactive)
14671 (if (and org-trust-scanner-tags
14672 (or (not pos) (equal pos (point)))
14673 (not local))
14674 org-scanner-tags
14675 (let (tags ltags lastpos parent)
14676 (save-excursion
14677 (save-restriction
14678 (widen)
14679 (goto-char (or pos (point)))
14680 (save-match-data
14681 (catch 'done
14682 (condition-case nil
14683 (progn
14684 (org-back-to-heading t)
14685 (while (not (equal lastpos (point)))
14686 (setq lastpos (point))
14687 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14688 (setq ltags (org-split-string
14689 (match-string-no-properties 1) ":"))
14690 (when parent
14691 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14692 (setq tags (append
14693 (if parent
14694 (org-remove-uninherited-tags ltags)
14695 ltags)
14696 tags)))
14697 (or org-use-tag-inheritance (throw 'done t))
14698 (when local (throw 'done t))
14699 (or (org-up-heading-safe) (error nil))
14700 (setq parent t)))
14701 (error nil)))))
14702 (if local
14703 tags
14704 (reverse (delete-dups
14705 (reverse (append
14706 (org-remove-uninherited-tags
14707 org-file-tags)
14708 tags)))))))))
14710 (defun org-add-prop-inherited (s)
14711 (add-text-properties 0 (length s) '(inherited t) s)
14714 (defun org-toggle-tag (tag &optional onoff)
14715 "Toggle the tag TAG for the current line.
14716 If ONOFF is `on' or `off', don't toggle but set to this state."
14717 (save-excursion
14718 (org-back-to-heading t)
14719 (let ((current
14720 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14721 (line-end-position) t)
14722 (let ((tags (match-string 1)))
14723 ;; Clear current tags.
14724 (replace-match "")
14725 ;; Reverse the tags list so any new tag is appended to
14726 ;; the current list of tags.
14727 (nreverse (org-split-string tags ":")))))
14728 res)
14729 (pcase onoff
14730 (`off (setq current (delete tag current)))
14731 ((or `on (guard (not (member tag current))))
14732 (setq res t)
14733 (cl-pushnew tag current :test #'equal))
14734 (_ (setq current (delete tag current))))
14735 (end-of-line)
14736 (if current
14737 (progn
14738 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14739 (org-set-tags nil t))
14740 (delete-horizontal-space))
14741 (run-hooks 'org-after-tags-change-hook)
14742 res)))
14744 (defun org--align-tags-here (to-col)
14745 "Align tags on the current headline to TO-COL.
14746 Assume point is on a headline."
14747 (let ((pos (point)))
14748 (beginning-of-line)
14749 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14750 (>= pos (match-beginning 2)))
14751 ;; No tags or point within tags: do not align.
14752 (goto-char pos)
14753 (goto-char (match-beginning 1))
14754 (let ((shift (max (- (if (>= to-col 0) to-col
14755 (- (abs to-col) (string-width (match-string 2))))
14756 (current-column))
14757 1)))
14758 (replace-match (make-string shift ?\s) nil nil nil 1)
14759 ;; Preserve initial position, if possible. In any case, stop
14760 ;; before tags.
14761 (when (< pos (point)) (goto-char pos))))))
14763 (defun org-set-tags-command (&optional arg just-align)
14764 "Call the set-tags command for the current entry."
14765 (interactive "P")
14766 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14767 (org-set-tags arg just-align)
14768 (save-excursion
14769 (unless (and (org-region-active-p)
14770 org-loop-over-headlines-in-active-region)
14771 (org-back-to-heading t))
14772 (org-set-tags arg just-align))))
14774 (defun org-set-tags-to (data)
14775 "Set the tags of the current entry to DATA, replacing the current tags.
14776 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14777 If DATA is nil or the empty string, any tags will be removed."
14778 (interactive "sTags: ")
14779 (setq data
14780 (cond
14781 ((eq data nil) "")
14782 ((equal data "") "")
14783 ((stringp data)
14784 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14785 ":"))
14786 ((listp data)
14787 (concat ":" (mapconcat 'identity data ":") ":"))))
14788 (when data
14789 (save-excursion
14790 (org-back-to-heading t)
14791 (when (let ((case-fold-search nil))
14792 (looking-at org-complex-heading-regexp))
14793 (if (match-end 5)
14794 (progn
14795 (goto-char (match-beginning 5))
14796 (insert data)
14797 (delete-region (point) (point-at-eol))
14798 (org-set-tags nil 'align))
14799 (goto-char (point-at-eol))
14800 (insert " " data)
14801 (org-set-tags nil 'align)))
14802 (beginning-of-line 1)
14803 (when (looking-at ".*?\\([ \t]+\\)$")
14804 (delete-region (match-beginning 1) (match-end 1))))))
14806 (defun org-align-all-tags ()
14807 "Align the tags in all headings."
14808 (interactive)
14809 (save-excursion
14810 (or (ignore-errors (org-back-to-heading t))
14811 (outline-next-heading))
14812 (if (org-at-heading-p)
14813 (org-set-tags t)
14814 (message "No headings"))))
14816 (defvar org-indent-indentation-per-level)
14817 (defun org-set-tags (&optional arg just-align)
14818 "Set the tags for the current headline.
14819 With prefix ARG, realign all tags in headings in the current buffer.
14820 When JUST-ALIGN is non-nil, only align tags."
14821 (interactive "P")
14822 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14823 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14824 'region-start-level
14825 'region))
14826 org-loop-over-headlines-in-active-region)
14827 (org-map-entries
14828 ;; We don't use ARG and JUST-ALIGN here because these args
14829 ;; are not useful when looping over headlines.
14830 #'org-set-tags
14831 org-loop-over-headlines-in-active-region
14833 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14834 (let ((org-setting-tags t))
14835 (if arg
14836 (save-excursion
14837 (goto-char (point-min))
14838 (while (re-search-forward org-outline-regexp-bol nil t)
14839 (org-set-tags nil t)
14840 (end-of-line))
14841 (message "All tags realigned to column %d" org-tags-column))
14842 (let* ((current (org-get-tags-string))
14843 (tags
14844 (if just-align current
14845 ;; Get a new set of tags from the user.
14846 (save-excursion
14847 (let* ((seen)
14848 (table
14849 (setq
14850 org-last-tags-completion-table
14851 ;; Uniquify tags in alists, yet preserve
14852 ;; structure (i.e., keywords).
14853 (delq nil
14854 (mapcar
14855 (lambda (pair)
14856 (let ((head (car pair)))
14857 (cond ((symbolp head) pair)
14858 ((member head seen) nil)
14859 (t (push head seen)
14860 pair))))
14861 (append
14862 (or org-current-tag-alist
14863 (org-get-buffer-tags))
14864 (and
14865 org-complete-tags-always-offer-all-agenda-tags
14866 (org-global-tags-completion-table
14867 (org-agenda-files))))))))
14868 (current-tags (org-split-string current ":"))
14869 (inherited-tags
14870 (nreverse (nthcdr (length current-tags)
14871 (nreverse (org-get-tags-at))))))
14872 (replace-regexp-in-string
14873 "\\([-+&]+\\|,\\)"
14875 (if (or (eq t org-use-fast-tag-selection)
14876 (and org-use-fast-tag-selection
14877 (delq nil (mapcar #'cdr table))))
14878 (org-fast-tag-selection
14879 current-tags inherited-tags table
14880 (and org-fast-tag-selection-include-todo
14881 org-todo-key-alist))
14882 (let ((org-add-colon-after-tag-completion
14883 (< 1 (length table))))
14884 (org-trim
14885 (completing-read
14886 "Tags: "
14887 #'org-tags-completion-function
14888 nil nil current 'org-tags-history))))))))))
14890 (when org-tags-sort-function
14891 (setq tags
14892 (mapconcat
14893 #'identity
14894 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14895 org-tags-sort-function)
14896 ":")))
14898 (if (or (string= ":" tags)
14899 (string= "::" tags))
14900 (setq tags ""))
14901 (if (not (org-string-nw-p tags)) (setq tags "")
14902 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14903 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14905 ;; Insert new tags at the correct column.
14906 (unless (equal current tags)
14907 (save-excursion
14908 (beginning-of-line)
14909 (let ((case-fold-search nil))
14910 (looking-at org-complex-heading-regexp))
14911 ;; Remove current tags, if any.
14912 (when (match-end 5) (replace-match "" nil nil nil 5))
14913 ;; Insert new tags, if any. Otherwise, remove trailing
14914 ;; white spaces.
14915 (end-of-line)
14916 (if (not (equal tags ""))
14917 ;; When text is being inserted on an invisible
14918 ;; region boundary, it can be inadvertently sucked
14919 ;; into invisibility.
14920 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14921 (skip-chars-backward " \t")
14922 (delete-region (point) (line-end-position)))))
14923 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14924 ;; is on.
14925 (unless (equal tags "")
14926 (let* ((level (save-excursion
14927 (beginning-of-line)
14928 (skip-chars-forward "\\*")))
14929 (offset (if (bound-and-true-p org-indent-mode)
14930 (* (1- org-indent-indentation-per-level)
14931 (1- level))
14933 (tags-column
14934 (+ org-tags-column
14935 (if (> org-tags-column 0) (- offset) offset))))
14936 (org--align-tags-here tags-column))))
14937 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14939 (defun org-change-tag-in-region (beg end tag off)
14940 "Add or remove TAG for each entry in the region.
14941 This works in the agenda, and also in an Org buffer."
14942 (interactive
14943 (list (region-beginning) (region-end)
14944 (let ((org-last-tags-completion-table
14945 (if (derived-mode-p 'org-mode)
14946 (org-uniquify
14947 (delq nil (append (org-get-buffer-tags)
14948 (org-global-tags-completion-table))))
14949 (org-global-tags-completion-table))))
14950 (completing-read
14951 "Tag: " 'org-tags-completion-function nil nil nil
14952 'org-tags-history))
14953 (progn
14954 (message "[s]et or [r]emove? ")
14955 (equal (read-char-exclusive) ?r))))
14956 (when (fboundp 'deactivate-mark) (deactivate-mark))
14957 (let ((agendap (equal major-mode 'org-agenda-mode))
14958 l1 l2 m buf pos newhead (cnt 0))
14959 (goto-char end)
14960 (setq l2 (1- (org-current-line)))
14961 (goto-char beg)
14962 (setq l1 (org-current-line))
14963 (cl-loop for l from l1 to l2 do
14964 (org-goto-line l)
14965 (setq m (get-text-property (point) 'org-hd-marker))
14966 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14967 (and agendap m))
14968 (setq buf (if agendap (marker-buffer m) (current-buffer))
14969 pos (if agendap m (point)))
14970 (with-current-buffer buf
14971 (save-excursion
14972 (save-restriction
14973 (goto-char pos)
14974 (setq cnt (1+ cnt))
14975 (org-toggle-tag tag (if off 'off 'on))
14976 (setq newhead (org-get-heading)))))
14977 (and agendap (org-agenda-change-all-lines newhead m))))
14978 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14980 (defun org-tags-completion-function (string _predicate &optional flag)
14981 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14982 (confirm (lambda (x) (stringp (car x)))))
14983 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14984 (setq s1 (match-string 1 string)
14985 s2 (match-string 2 string))
14986 (setq s1 "" s2 string))
14987 (cond
14988 ((eq flag nil)
14989 ;; try completion
14990 (setq rtn (try-completion s2 ctable confirm))
14991 (when (stringp rtn)
14992 (setq rtn
14993 (concat s1 s2 (substring rtn (length s2))
14994 (if (and org-add-colon-after-tag-completion
14995 (assoc rtn ctable))
14996 ":" ""))))
14997 rtn)
14998 ((eq flag t)
14999 ;; all-completions
15000 (all-completions s2 ctable confirm))
15001 ((eq flag 'lambda)
15002 ;; exact match?
15003 (assoc s2 ctable)))))
15005 (defun org-fast-tag-insert (kwd tags face &optional end)
15006 "Insert KDW, and the TAGS, the latter with face FACE.
15007 Also insert END."
15008 (insert (format "%-12s" (concat kwd ":"))
15009 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15010 (or end "")))
15012 (defun org-fast-tag-show-exit (flag)
15013 (save-excursion
15014 (org-goto-line 3)
15015 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15016 (replace-match ""))
15017 (when flag
15018 (end-of-line 1)
15019 (org-move-to-column (- (window-width) 19) t)
15020 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15022 (defun org-set-current-tags-overlay (current prefix)
15023 "Add an overlay to CURRENT tag with PREFIX."
15024 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15025 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15026 (org-overlay-display org-tags-overlay (concat prefix s))))
15028 (defvar org-last-tag-selection-key nil)
15029 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15030 "Fast tag selection with single keys.
15031 CURRENT is the current list of tags in the headline, INHERITED is the
15032 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15033 possibly with grouping information. TODO-TABLE is a similar table with
15034 TODO keywords, should these have keys assigned to them.
15035 If the keys are nil, a-z are automatically assigned.
15036 Returns the new tags string, or nil to not change the current settings."
15037 (let* ((fulltable (append table todo-table))
15038 (maxlen (apply 'max (mapcar
15039 (lambda (x)
15040 (if (stringp (car x)) (string-width (car x)) 0))
15041 fulltable)))
15042 (buf (current-buffer))
15043 (expert (eq org-fast-tag-selection-single-key 'expert))
15044 (buffer-tags nil)
15045 (fwidth (+ maxlen 3 1 3))
15046 (ncol (/ (- (window-width) 4) fwidth))
15047 (i-face 'org-done)
15048 (c-face 'org-todo)
15049 tg cnt e c char c1 c2 ntable tbl rtn
15050 ov-start ov-end ov-prefix
15051 (exit-after-next org-fast-tag-selection-single-key)
15052 (done-keywords org-done-keywords)
15053 groups ingroup intaggroup)
15054 (save-excursion
15055 (beginning-of-line 1)
15056 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15057 (setq ov-start (match-beginning 1)
15058 ov-end (match-end 1)
15059 ov-prefix "")
15060 (setq ov-start (1- (point-at-eol))
15061 ov-end (1+ ov-start))
15062 (skip-chars-forward "^\n\r")
15063 (setq ov-prefix
15064 (concat
15065 (buffer-substring (1- (point)) (point))
15066 (if (> (current-column) org-tags-column)
15068 (make-string (- org-tags-column (current-column)) ?\ ))))))
15069 (move-overlay org-tags-overlay ov-start ov-end)
15070 (save-window-excursion
15071 (if expert
15072 (set-buffer (get-buffer-create " *Org tags*"))
15073 (delete-other-windows)
15074 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15075 (org-switch-to-buffer-other-window " *Org tags*"))
15076 (erase-buffer)
15077 (setq-local org-done-keywords done-keywords)
15078 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15079 (org-fast-tag-insert "Current" current c-face "\n\n")
15080 (org-fast-tag-show-exit exit-after-next)
15081 (org-set-current-tags-overlay current ov-prefix)
15082 (setq tbl fulltable char ?a cnt 0)
15083 (while (setq e (pop tbl))
15084 (cond
15085 ((eq (car e) :startgroup)
15086 (push '() groups) (setq ingroup t)
15087 (unless (zerop cnt)
15088 (setq cnt 0)
15089 (insert "\n"))
15090 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15091 ((eq (car e) :endgroup)
15092 (setq ingroup nil cnt 0)
15093 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15094 ((eq (car e) :startgrouptag)
15095 (setq intaggroup t)
15096 (unless (zerop cnt)
15097 (setq cnt 0)
15098 (insert "\n"))
15099 (insert "[ "))
15100 ((eq (car e) :endgrouptag)
15101 (setq intaggroup nil cnt 0)
15102 (insert "]\n"))
15103 ((equal e '(:newline))
15104 (unless (zerop cnt)
15105 (setq cnt 0)
15106 (insert "\n")
15107 (setq e (car tbl))
15108 (while (equal (car tbl) '(:newline))
15109 (insert "\n")
15110 (setq tbl (cdr tbl)))))
15111 ((equal e '(:grouptags)) (insert " : "))
15113 (setq tg (copy-sequence (car e)) c2 nil)
15114 (if (cdr e)
15115 (setq c (cdr e))
15116 ;; automatically assign a character.
15117 (setq c1 (string-to-char
15118 (downcase (substring
15119 tg (if (= (string-to-char tg) ?@) 1 0)))))
15120 (if (or (rassoc c1 ntable) (rassoc c1 table))
15121 (while (or (rassoc char ntable) (rassoc char table))
15122 (setq char (1+ char)))
15123 (setq c2 c1))
15124 (setq c (or c2 char)))
15125 (when ingroup (push tg (car groups)))
15126 (setq tg (org-add-props tg nil 'face
15127 (cond
15128 ((not (assoc tg table))
15129 (org-get-todo-face tg))
15130 ((member tg current) c-face)
15131 ((member tg inherited) i-face))))
15132 (when (equal (caar tbl) :grouptags)
15133 (org-add-props tg nil 'face 'org-tag-group))
15134 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15135 (insert "[" c "] " tg (make-string
15136 (- fwidth 4 (length tg)) ?\ ))
15137 (push (cons tg c) ntable)
15138 (when (= (cl-incf cnt) ncol)
15139 (insert "\n")
15140 (when (or ingroup intaggroup) (insert " "))
15141 (setq cnt 0)))))
15142 (setq ntable (nreverse ntable))
15143 (insert "\n")
15144 (goto-char (point-min))
15145 (unless expert (org-fit-window-to-buffer))
15146 (setq rtn
15147 (catch 'exit
15148 (while t
15149 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15150 (if (not groups) "no " "")
15151 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15152 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15153 (setq org-last-tag-selection-key c)
15154 (cond
15155 ((= c ?\r) (throw 'exit t))
15156 ((= c ?!)
15157 (setq groups (not groups))
15158 (goto-char (point-min))
15159 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15160 ((= c ?\C-c)
15161 (if (not expert)
15162 (org-fast-tag-show-exit
15163 (setq exit-after-next (not exit-after-next)))
15164 (setq expert nil)
15165 (delete-other-windows)
15166 (set-window-buffer (split-window-vertically) " *Org tags*")
15167 (org-switch-to-buffer-other-window " *Org tags*")
15168 (org-fit-window-to-buffer)))
15169 ((or (= c ?\C-g)
15170 (and (= c ?q) (not (rassoc c ntable))))
15171 (delete-overlay org-tags-overlay)
15172 (setq quit-flag t))
15173 ((= c ?\ )
15174 (setq current nil)
15175 (when exit-after-next (setq exit-after-next 'now)))
15176 ((= c ?\t)
15177 (condition-case nil
15178 (setq tg (completing-read
15179 "Tag: "
15180 (or buffer-tags
15181 (with-current-buffer buf
15182 (setq buffer-tags
15183 (org-get-buffer-tags))))))
15184 (quit (setq tg "")))
15185 (when (string-match "\\S-" tg)
15186 (cl-pushnew (list tg) buffer-tags :test #'equal)
15187 (if (member tg current)
15188 (setq current (delete tg current))
15189 (push tg current)))
15190 (when exit-after-next (setq exit-after-next 'now)))
15191 ((setq e (rassoc c todo-table) tg (car e))
15192 (with-current-buffer buf
15193 (save-excursion (org-todo tg)))
15194 (when exit-after-next (setq exit-after-next 'now)))
15195 ((setq e (rassoc c ntable) tg (car e))
15196 (if (member tg current)
15197 (setq current (delete tg current))
15198 (cl-loop for g in groups do
15199 (when (member tg g)
15200 (dolist (x g) (setq current (delete x current)))))
15201 (push tg current))
15202 (when exit-after-next (setq exit-after-next 'now))))
15204 ;; Create a sorted list
15205 (setq current
15206 (sort current
15207 (lambda (a b)
15208 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15209 (when (eq exit-after-next 'now) (throw 'exit t))
15210 (goto-char (point-min))
15211 (beginning-of-line 2)
15212 (delete-region (point) (point-at-eol))
15213 (org-fast-tag-insert "Current" current c-face)
15214 (org-set-current-tags-overlay current ov-prefix)
15215 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15216 (setq tg (match-string 1))
15217 (add-text-properties
15218 (match-beginning 1) (match-end 1)
15219 (list 'face
15220 (cond
15221 ((member tg current) c-face)
15222 ((member tg inherited) i-face)
15223 (t (get-text-property (match-beginning 1) 'face))))))
15224 (goto-char (point-min)))))
15225 (delete-overlay org-tags-overlay)
15226 (if rtn
15227 (mapconcat 'identity current ":")
15228 nil))))
15230 (defun org-get-tags-string ()
15231 "Get the TAGS string in the current headline."
15232 (unless (org-at-heading-p t)
15233 (user-error "Not on a heading"))
15234 (save-excursion
15235 (beginning-of-line 1)
15236 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15237 (match-string-no-properties 1)
15238 "")))
15240 (defun org-get-tags ()
15241 "Get the list of tags specified in the current headline."
15242 (org-split-string (org-get-tags-string) ":"))
15244 (defun org-get-buffer-tags ()
15245 "Get a table of all tags used in the buffer, for completion."
15246 (org-with-wide-buffer
15247 (goto-char (point-min))
15248 (let ((tag-re (concat org-outline-regexp-bol
15249 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15250 tags)
15251 (while (re-search-forward tag-re nil t)
15252 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15253 (push tag tags)))
15254 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15256 ;;;; The mapping API
15258 (defvar org-agenda-skip-comment-trees)
15259 (defvar org-agenda-skip-function)
15260 (defun org-map-entries (func &optional match scope &rest skip)
15261 "Call FUNC at each headline selected by MATCH in SCOPE.
15263 FUNC is a function or a lisp form. The function will be called without
15264 arguments, with the cursor positioned at the beginning of the headline.
15265 The return values of all calls to the function will be collected and
15266 returned as a list.
15268 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15269 does not need to preserve point. After evaluation, the cursor will be
15270 moved to the end of the line (presumably of the headline of the
15271 processed entry) and search continues from there. Under some
15272 circumstances, this may not produce the wanted results. For example,
15273 if you have removed (e.g. archived) the current (sub)tree it could
15274 mean that the next entry will be skipped entirely. In such cases, you
15275 can specify the position from where search should continue by making
15276 FUNC set the variable `org-map-continue-from' to the desired buffer
15277 position.
15279 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15280 Only headlines that are matched by this query will be considered during
15281 the iteration. When MATCH is nil or t, all headlines will be
15282 visited by the iteration.
15284 SCOPE determines the scope of this command. It can be any of:
15286 nil The current buffer, respecting the restriction if any
15287 tree The subtree started with the entry at point
15288 region The entries within the active region, if any
15289 region-start-level
15290 The entries within the active region, but only those at
15291 the same level than the first one.
15292 file The current buffer, without restriction
15293 file-with-archives
15294 The current buffer, and any archives associated with it
15295 agenda All agenda files
15296 agenda-with-archives
15297 All agenda files with any archive files associated with them
15298 \(file1 file2 ...)
15299 If this is a list, all files in the list will be scanned
15301 The remaining args are treated as settings for the skipping facilities of
15302 the scanner. The following items can be given here:
15304 archive skip trees with the archive tag
15305 comment skip trees with the COMMENT keyword
15306 function or Emacs Lisp form:
15307 will be used as value for `org-agenda-skip-function', so
15308 whenever the function returns a position, FUNC will not be
15309 called for that entry and search will continue from the
15310 position returned
15312 If your function needs to retrieve the tags including inherited tags
15313 at the *current* entry, you can use the value of the variable
15314 `org-scanner-tags' which will be much faster than getting the value
15315 with `org-get-tags-at'. If your function gets properties with
15316 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15317 to t around the call to `org-entry-properties' to get the same speedup.
15318 Note that if your function moves around to retrieve tags and properties at
15319 a *different* entry, you cannot use these techniques."
15320 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15321 (not (org-region-active-p)))
15322 (let* ((org-agenda-archives-mode nil) ; just to make sure
15323 (org-agenda-skip-archived-trees (memq 'archive skip))
15324 (org-agenda-skip-comment-trees (memq 'comment skip))
15325 (org-agenda-skip-function
15326 (car (org-delete-all '(comment archive) skip)))
15327 (org-tags-match-list-sublevels t)
15328 (start-level (eq scope 'region-start-level))
15329 matcher res
15330 org-todo-keywords-for-agenda
15331 org-done-keywords-for-agenda
15332 org-todo-keyword-alist-for-agenda
15333 org-tag-alist-for-agenda
15334 org--matcher-tags-todo-only)
15336 (cond
15337 ((eq match t) (setq matcher t))
15338 ((eq match nil) (setq matcher t))
15339 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15341 (save-excursion
15342 (save-restriction
15343 (cond ((eq scope 'tree)
15344 (org-back-to-heading t)
15345 (org-narrow-to-subtree)
15346 (setq scope nil))
15347 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15348 (org-region-active-p))
15349 ;; If needed, set start-level to a string like "2"
15350 (when start-level
15351 (save-excursion
15352 (goto-char (region-beginning))
15353 (unless (org-at-heading-p) (outline-next-heading))
15354 (setq start-level (org-current-level))))
15355 (narrow-to-region (region-beginning)
15356 (save-excursion
15357 (goto-char (region-end))
15358 (unless (and (bolp) (org-at-heading-p))
15359 (outline-next-heading))
15360 (point)))
15361 (setq scope nil)))
15363 (if (not scope)
15364 (progn
15365 (org-agenda-prepare-buffers
15366 (and buffer-file-name (list buffer-file-name)))
15367 (setq res
15368 (org-scan-tags
15369 func matcher org--matcher-tags-todo-only start-level)))
15370 ;; Get the right scope
15371 (cond
15372 ((and scope (listp scope) (symbolp (car scope)))
15373 (setq scope (eval scope)))
15374 ((eq scope 'agenda)
15375 (setq scope (org-agenda-files t)))
15376 ((eq scope 'agenda-with-archives)
15377 (setq scope (org-agenda-files t))
15378 (setq scope (org-add-archive-files scope)))
15379 ((eq scope 'file)
15380 (setq scope (and buffer-file-name (list buffer-file-name))))
15381 ((eq scope 'file-with-archives)
15382 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15383 (org-agenda-prepare-buffers scope)
15384 (dolist (file scope)
15385 (with-current-buffer (org-find-base-buffer-visiting file)
15386 (org-with-wide-buffer
15387 (goto-char (point-min))
15388 (setq res
15389 (append
15391 (org-scan-tags
15392 func matcher org--matcher-tags-todo-only)))))))))
15393 res)))
15395 ;;; Properties API
15397 (defconst org-special-properties
15398 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15399 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15400 "The special properties valid in Org mode.
15401 These are properties that are not defined in the property drawer,
15402 but in some other way.")
15404 (defconst org-default-properties
15405 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15406 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15407 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15408 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15409 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15410 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15411 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15412 "Some properties that are used by Org mode for various purposes.
15413 Being in this list makes sure that they are offered for completion.")
15415 (defun org--valid-property-p (property)
15416 "Non nil when string PROPERTY is a valid property name."
15417 (not
15418 (or (equal property "")
15419 (string-match-p "\\s-" property))))
15421 (defun org--update-property-plist (key val props)
15422 "Associate KEY to VAL in alist PROPS.
15423 Modifications are made by side-effect. Return new alist."
15424 (let* ((appending (string= (substring key -1) "+"))
15425 (key (if appending (substring key 0 -1) key))
15426 (old (assoc-string key props t)))
15427 (if (not old) (cons (cons key val) props)
15428 (setcdr old (if appending (concat (cdr old) " " val) val))
15429 props)))
15431 (defun org-get-property-block (&optional beg force)
15432 "Return the (beg . end) range of the body of the property drawer.
15433 BEG is the beginning of the current subtree, or of the part
15434 before the first headline. If it is not given, it will be found.
15435 If the drawer does not exist, create it if FORCE is non-nil, or
15436 return nil."
15437 (org-with-wide-buffer
15438 (when beg (goto-char beg))
15439 (unless (org-before-first-heading-p)
15440 (let ((beg (cond (beg)
15441 ((or (not (featurep 'org-inlinetask))
15442 (org-inlinetask-in-task-p))
15443 (org-back-to-heading t))
15444 (t (org-with-limited-levels (org-back-to-heading t))))))
15445 (forward-line)
15446 (when (looking-at-p org-planning-line-re) (forward-line))
15447 (cond ((looking-at org-property-drawer-re)
15448 (forward-line)
15449 (cons (point) (progn (goto-char (match-end 0))
15450 (line-beginning-position))))
15451 (force
15452 (goto-char beg)
15453 (org-insert-property-drawer)
15454 (let ((pos (save-excursion (search-forward ":END:")
15455 (line-beginning-position))))
15456 (cons pos pos))))))))
15458 (defun org-at-property-p ()
15459 "Non-nil when point is inside a property drawer.
15460 See `org-property-re' for match data, if applicable."
15461 (save-excursion
15462 (beginning-of-line)
15463 (and (looking-at org-property-re)
15464 (let ((property-drawer (save-match-data (org-get-property-block))))
15465 (and property-drawer
15466 (>= (point) (car property-drawer))
15467 (< (point) (cdr property-drawer)))))))
15469 (defun org-property-action ()
15470 "Do an action on properties."
15471 (interactive)
15472 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15473 (let ((c (read-char-exclusive)))
15474 (cl-case c
15475 (?s (call-interactively #'org-set-property))
15476 (?d (call-interactively #'org-delete-property))
15477 (?D (call-interactively #'org-delete-property-globally))
15478 (?c (call-interactively #'org-compute-property-at-point))
15479 (otherwise (user-error "No such property action %c" c)))))
15481 (defun org-inc-effort ()
15482 "Increment the value of the effort property in the current entry."
15483 (interactive)
15484 (org-set-effort nil t))
15486 (defvar org-clock-effort) ; Defined in org-clock.el.
15487 (defvar org-clock-current-task) ; Defined in org-clock.el.
15488 (defun org-set-effort (&optional value increment)
15489 "Set the effort property of the current entry.
15490 With numerical prefix arg, use the nth allowed value, 0 stands for the
15491 10th allowed value.
15493 When INCREMENT is non-nil, set the property to the next allowed value."
15494 (interactive "P")
15495 (when (equal value 0) (setq value 10))
15496 (let* ((completion-ignore-case t)
15497 (prop org-effort-property)
15498 (cur (org-entry-get nil prop))
15499 (allowed (org-property-get-allowed-values nil prop 'table))
15500 (existing (mapcar 'list (org-property-values prop)))
15501 (heading (nth 4 (org-heading-components)))
15503 (val (cond
15504 ((stringp value) value)
15505 ((and allowed (integerp value))
15506 (or (car (nth (1- value) allowed))
15507 (car (org-last allowed))))
15508 ((and allowed increment)
15509 (or (cl-caadr (member (list cur) allowed))
15510 (user-error "Allowed effort values are not set")))
15511 (allowed
15512 (message "Select 1-9,0, [RET%s]: %s"
15513 (if cur (concat "=" cur) "")
15514 (mapconcat 'car allowed " "))
15515 (setq rpl (read-char-exclusive))
15516 (if (equal rpl ?\r)
15518 (setq rpl (- rpl ?0))
15519 (when (equal rpl 0) (setq rpl 10))
15520 (if (and (> rpl 0) (<= rpl (length allowed)))
15521 (car (nth (1- rpl) allowed))
15522 (org-completing-read "Effort: " allowed nil))))
15524 (org-completing-read
15525 (concat "Effort" (and cur (string-match "\\S-" cur)
15526 (concat " [" cur "]"))
15527 ": ")
15528 existing nil nil "" nil cur)))))
15529 (unless (equal (org-entry-get nil prop) val)
15530 (org-entry-put nil prop val))
15531 (org-refresh-property
15532 '((effort . identity)
15533 (effort-minutes . org-duration-to-minutes))
15534 val)
15535 (when (equal heading (bound-and-true-p org-clock-current-task))
15536 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15537 (org-clock-update-mode-line))
15538 (message "%s is now %s" prop val)))
15540 (defun org-entry-properties (&optional pom which)
15541 "Get all properties of the current entry.
15543 When POM is a buffer position, get all properties from the entry
15544 there instead.
15546 This includes the TODO keyword, the tags, time strings for
15547 deadline, scheduled, and clocking, and any additional properties
15548 defined in the entry.
15550 If WHICH is nil or `all', get all properties. If WHICH is
15551 `special' or `standard', only get that subclass. If WHICH is
15552 a string, only get that property.
15554 Return value is an alist. Keys are properties, as upcased
15555 strings."
15556 (org-with-point-at pom
15557 (when (and (derived-mode-p 'org-mode)
15558 (ignore-errors (org-back-to-heading t)))
15559 (catch 'exit
15560 (let* ((beg (point))
15561 (specific (and (stringp which) (upcase which)))
15562 (which (cond ((not specific) which)
15563 ((member specific org-special-properties) 'special)
15564 (t 'standard)))
15565 props)
15566 ;; Get the special properties, like TODO and TAGS.
15567 (when (memq which '(nil all special))
15568 (when (or (not specific) (string= specific "CLOCKSUM"))
15569 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15570 (when clocksum
15571 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15572 props)))
15573 (when specific (throw 'exit props)))
15574 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15575 (let ((clocksumt (get-text-property (point)
15576 :org-clock-minutes-today)))
15577 (when clocksumt
15578 (push (cons "CLOCKSUM_T"
15579 (org-duration-from-minutes clocksumt))
15580 props)))
15581 (when specific (throw 'exit props)))
15582 (when (or (not specific) (string= specific "ITEM"))
15583 (let ((case-fold-search nil))
15584 (when (looking-at org-complex-heading-regexp)
15585 (push (cons "ITEM"
15586 (let ((title (match-string-no-properties 4)))
15587 (if (org-string-nw-p title)
15588 (org-remove-tabs title)
15589 "")))
15590 props)))
15591 (when specific (throw 'exit props)))
15592 (when (or (not specific) (string= specific "TODO"))
15593 (let ((case-fold-search nil))
15594 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15595 (push (cons "TODO" (match-string-no-properties 2)) props)))
15596 (when specific (throw 'exit props)))
15597 (when (or (not specific) (string= specific "PRIORITY"))
15598 (push (cons "PRIORITY"
15599 (if (looking-at org-priority-regexp)
15600 (match-string-no-properties 2)
15601 (char-to-string org-default-priority)))
15602 props)
15603 (when specific (throw 'exit props)))
15604 (when (or (not specific) (string= specific "FILE"))
15605 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15606 props)
15607 (when specific (throw 'exit props)))
15608 (when (or (not specific) (string= specific "TAGS"))
15609 (let ((value (org-string-nw-p (org-get-tags-string))))
15610 (when value (push (cons "TAGS" value) props)))
15611 (when specific (throw 'exit props)))
15612 (when (or (not specific) (string= specific "ALLTAGS"))
15613 (let ((value (org-get-tags-at)))
15614 (when value
15615 (push (cons "ALLTAGS"
15616 (format ":%s:" (mapconcat #'identity value ":")))
15617 props)))
15618 (when specific (throw 'exit props)))
15619 (when (or (not specific) (string= specific "BLOCKED"))
15620 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15621 (when specific (throw 'exit props)))
15622 (when (or (not specific)
15623 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15624 (forward-line)
15625 (when (looking-at-p org-planning-line-re)
15626 (end-of-line)
15627 (let ((bol (line-beginning-position))
15628 ;; Backward compatibility: time keywords used to
15629 ;; be configurable (before 8.3). Make sure we
15630 ;; get the correct keyword.
15631 (key-assoc `(("CLOSED" . ,org-closed-string)
15632 ("DEADLINE" . ,org-deadline-string)
15633 ("SCHEDULED" . ,org-scheduled-string))))
15634 (dolist (pair (if specific (list (assoc specific key-assoc))
15635 key-assoc))
15636 (save-excursion
15637 (when (search-backward (cdr pair) bol t)
15638 (goto-char (match-end 0))
15639 (skip-chars-forward " \t")
15640 (and (looking-at org-ts-regexp-both)
15641 (push (cons (car pair)
15642 (match-string-no-properties 0))
15643 props)))))))
15644 (when specific (throw 'exit props)))
15645 (when (or (not specific)
15646 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15647 (let ((find-ts
15648 (lambda (end ts)
15649 ;; Fix next time-stamp before END. TS is the
15650 ;; list of time-stamps found so far.
15651 (let ((ts ts)
15652 (regexp (cond
15653 ((string= specific "TIMESTAMP")
15654 org-ts-regexp)
15655 ((string= specific "TIMESTAMP_IA")
15656 org-ts-regexp-inactive)
15657 ((assoc "TIMESTAMP_IA" ts)
15658 org-ts-regexp)
15659 ((assoc "TIMESTAMP" ts)
15660 org-ts-regexp-inactive)
15661 (t org-ts-regexp-both))))
15662 (catch 'next
15663 (while (re-search-forward regexp end t)
15664 (backward-char)
15665 (let ((object (org-element-context)))
15666 ;; Accept to match timestamps in node
15667 ;; properties, too.
15668 (when (memq (org-element-type object)
15669 '(node-property timestamp))
15670 (let ((type
15671 (org-element-property :type object)))
15672 (cond
15673 ((and (memq type '(active active-range))
15674 (not (equal specific "TIMESTAMP_IA")))
15675 (unless (assoc "TIMESTAMP" ts)
15676 (push (cons "TIMESTAMP"
15677 (org-element-property
15678 :raw-value object))
15680 (when specific (throw 'exit ts))))
15681 ((and (memq type '(inactive inactive-range))
15682 (not (string= specific "TIMESTAMP")))
15683 (unless (assoc "TIMESTAMP_IA" ts)
15684 (push (cons "TIMESTAMP_IA"
15685 (org-element-property
15686 :raw-value object))
15688 (when specific (throw 'exit ts))))))
15689 ;; Both timestamp types are found,
15690 ;; move to next part.
15691 (when (= (length ts) 2) (throw 'next ts)))))
15692 ts)))))
15693 (goto-char beg)
15694 ;; First look for timestamps within headline.
15695 (let ((ts (funcall find-ts (line-end-position) nil)))
15696 (if (= (length ts) 2) (setq props (nconc ts props))
15697 ;; Then find timestamps in the section, skipping
15698 ;; planning line.
15699 (let ((end (save-excursion (outline-next-heading))))
15700 (forward-line)
15701 (when (looking-at-p org-planning-line-re) (forward-line))
15702 (setq props (nconc (funcall find-ts end ts) props))))))))
15703 ;; Get the standard properties, like :PROP:.
15704 (when (memq which '(nil all standard))
15705 ;; If we are looking after a specific property, delegate
15706 ;; to `org-entry-get', which is faster. However, make an
15707 ;; exception for "CATEGORY", since it can be also set
15708 ;; through keywords (i.e. #+CATEGORY).
15709 (if (and specific (not (equal specific "CATEGORY")))
15710 (let ((value (org-entry-get beg specific nil t)))
15711 (throw 'exit (and value (list (cons specific value)))))
15712 (let ((range (org-get-property-block beg)))
15713 (when range
15714 (let ((end (cdr range)) seen-base)
15715 (goto-char (car range))
15716 ;; Unlike to `org--update-property-plist', we
15717 ;; handle the case where base values is found
15718 ;; after its extension. We also forbid standard
15719 ;; properties to be named as special properties.
15720 (while (re-search-forward org-property-re end t)
15721 (let* ((key (upcase (match-string-no-properties 2)))
15722 (extendp (string-match-p "\\+\\'" key))
15723 (key-base (if extendp (substring key 0 -1) key))
15724 (value (match-string-no-properties 3)))
15725 (cond
15726 ((member-ignore-case key-base org-special-properties))
15727 (extendp
15728 (setq props
15729 (org--update-property-plist key value props)))
15730 ((member key seen-base))
15731 (t (push key seen-base)
15732 (let ((p (assoc-string key props t)))
15733 (if p (setcdr p (concat value " " (cdr p)))
15734 (push (cons key value) props))))))))))))
15735 (unless (assoc "CATEGORY" props)
15736 (push (cons "CATEGORY" (org-get-category beg)) props)
15737 (when (string= specific "CATEGORY") (throw 'exit props)))
15738 ;; Return value.
15739 props)))))
15741 (defun org--property-local-values (property literal-nil)
15742 "Return value for PROPERTY in current entry.
15743 Value is a list whose car is the base value for PROPERTY and cdr
15744 a list of accumulated values. Return nil if neither is found in
15745 the entry. Also return nil when PROPERTY is set to \"nil\",
15746 unless LITERAL-NIL is non-nil."
15747 (let ((range (org-get-property-block)))
15748 (when range
15749 (goto-char (car range))
15750 (let* ((case-fold-search t)
15751 (end (cdr range))
15752 (value
15753 ;; Base value.
15754 (save-excursion
15755 (let ((v (and (re-search-forward
15756 (org-re-property property nil t) end t)
15757 (match-string-no-properties 3))))
15758 (list (if literal-nil v (org-not-nil v)))))))
15759 ;; Find additional values.
15760 (let* ((property+ (org-re-property (concat property "+") nil t)))
15761 (while (re-search-forward property+ end t)
15762 (push (match-string-no-properties 3) value)))
15763 ;; Return final values.
15764 (and (not (equal value '(nil))) (nreverse value))))))
15766 (defun org--property-global-value (property literal-nil)
15767 "Return value for PROPERTY in current buffer.
15768 Return value is a string. Return nil if property is not set
15769 globally. Also return nil when PROPERTY is set to \"nil\",
15770 unless LITERAL-NIL is non-nil."
15771 (let ((global
15772 (cdr (or (assoc-string property org-file-properties t)
15773 (assoc-string property org-global-properties t)
15774 (assoc-string property org-global-properties-fixed t)))))
15775 (if literal-nil global (org-not-nil global))))
15777 (defun org-entry-get (pom property &optional inherit literal-nil)
15778 "Get value of PROPERTY for entry or content at point-or-marker POM.
15780 If INHERIT is non-nil and the entry does not have the property,
15781 then also check higher levels of the hierarchy. If INHERIT is
15782 the symbol `selective', use inheritance only if the setting in
15783 `org-use-property-inheritance' selects PROPERTY for inheritance.
15785 If the property is present but empty, the return value is the
15786 empty string. If the property is not present at all, nil is
15787 returned. In any other case, return the value as a string.
15788 Search is case-insensitive.
15790 If LITERAL-NIL is set, return the string value \"nil\" as
15791 a string, do not interpret it as the list atom nil. This is used
15792 for inheritance when a \"nil\" value can supersede a non-nil
15793 value higher up the hierarchy."
15794 (org-with-point-at pom
15795 (cond
15796 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15797 ;; We need a special property. Use `org-entry-properties' to
15798 ;; retrieve it, but specify the wanted property.
15799 (cdr (assoc-string property (org-entry-properties nil property))))
15800 ((and inherit
15801 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15802 (org-entry-get-with-inheritance property literal-nil))
15804 (let* ((local (org--property-local-values property literal-nil))
15805 (value (and local (mapconcat #'identity (delq nil local) " "))))
15806 (if literal-nil value (org-not-nil value)))))))
15808 (defun org-property-or-variable-value (var &optional inherit)
15809 "Check if there is a property fixing the value of VAR.
15810 If yes, return this value. If not, return the current value of the variable."
15811 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15812 (if (and prop (stringp prop) (string-match "\\S-" prop))
15813 (read prop)
15814 (symbol-value var))))
15816 (defun org-entry-delete (pom property)
15817 "Delete PROPERTY from entry at point-or-marker POM.
15818 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15819 non-nil when a property was removed."
15820 (org-with-point-at pom
15821 (pcase (org-get-property-block)
15822 (`(,begin . ,origin)
15823 (let* ((end (copy-marker origin))
15824 (re (org-re-property
15825 (concat (regexp-quote property) "\\+?") t t)))
15826 (goto-char begin)
15827 (while (re-search-forward re end t)
15828 (delete-region (match-beginning 0) (line-beginning-position 2)))
15829 ;; If drawer is empty, remove it altogether.
15830 (when (= begin end)
15831 (delete-region (line-beginning-position 0)
15832 (line-beginning-position 2)))
15833 ;; Return non-nil if some property was removed.
15834 (prog1 (/= end origin) (set-marker end nil))))
15835 (_ nil))))
15837 ;; Multi-values properties are properties that contain multiple values
15838 ;; These values are assumed to be single words, separated by whitespace.
15839 (defun org-entry-add-to-multivalued-property (pom property value)
15840 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15841 (let* ((old (org-entry-get pom property))
15842 (values (and old (split-string old))))
15843 (setq value (org-entry-protect-space value))
15844 (unless (member value values)
15845 (setq values (append values (list value)))
15846 (org-entry-put pom property (mapconcat #'identity values " ")))))
15848 (defun org-entry-remove-from-multivalued-property (pom property value)
15849 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15850 (let* ((old (org-entry-get pom property))
15851 (values (and old (split-string old))))
15852 (setq value (org-entry-protect-space value))
15853 (when (member value values)
15854 (setq values (delete value values))
15855 (org-entry-put pom property (mapconcat #'identity values " ")))))
15857 (defun org-entry-member-in-multivalued-property (pom property value)
15858 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15859 (let* ((old (org-entry-get pom property))
15860 (values (and old (split-string old))))
15861 (setq value (org-entry-protect-space value))
15862 (member value values)))
15864 (defun org-entry-get-multivalued-property (pom property)
15865 "Return a list of values in a multivalued property."
15866 (let* ((value (org-entry-get pom property))
15867 (values (and value (split-string value))))
15868 (mapcar #'org-entry-restore-space values)))
15870 (defun org-entry-put-multivalued-property (pom property &rest values)
15871 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15872 VALUES should be a list of strings. Spaces will be protected."
15873 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15874 (let* ((value (org-entry-get pom property))
15875 (values (and value (split-string value))))
15876 (mapcar #'org-entry-restore-space values)))
15878 (defun org-entry-protect-space (s)
15879 "Protect spaces and newline in string S."
15880 (while (string-match " " s)
15881 (setq s (replace-match "%20" t t s)))
15882 (while (string-match "\n" s)
15883 (setq s (replace-match "%0A" t t s)))
15886 (defun org-entry-restore-space (s)
15887 "Restore spaces and newline in string S."
15888 (while (string-match "%20" s)
15889 (setq s (replace-match " " t t s)))
15890 (while (string-match "%0A" s)
15891 (setq s (replace-match "\n" t t s)))
15894 (defvar org-entry-property-inherited-from (make-marker)
15895 "Marker pointing to the entry from where a property was inherited.
15896 Each call to `org-entry-get-with-inheritance' will set this marker to the
15897 location of the entry where the inheritance search matched. If there was
15898 no match, the marker will point nowhere.
15899 Note that also `org-entry-get' calls this function, if the INHERIT flag
15900 is set.")
15902 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15903 "Get PROPERTY of entry or content at point, search higher levels if needed.
15904 The search will stop at the first ancestor which has the property defined.
15905 If the value found is \"nil\", return nil to show that the property
15906 should be considered as undefined (this is the meaning of nil here).
15907 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15908 (move-marker org-entry-property-inherited-from nil)
15909 (org-with-wide-buffer
15910 (let (value)
15911 (catch 'exit
15912 (while t
15913 (let ((v (org--property-local-values property literal-nil)))
15914 (when v
15915 (setq value
15916 (concat (mapconcat #'identity (delq nil v) " ")
15917 (and value " ")
15918 value)))
15919 (cond
15920 ((car v)
15921 (org-back-to-heading t)
15922 (move-marker org-entry-property-inherited-from (point))
15923 (throw 'exit nil))
15924 ((org-up-heading-safe))
15926 (let ((global (org--property-global-value property literal-nil)))
15927 (cond ((not global))
15928 (value (setq value (concat global " " value)))
15929 (t (setq value global))))
15930 (throw 'exit nil))))))
15931 (if literal-nil value (org-not-nil value)))))
15933 (defvar org-property-changed-functions nil
15934 "Hook called when the value of a property has changed.
15935 Each hook function should accept two arguments, the name of the property
15936 and the new value.")
15938 (defun org-entry-put (pom property value)
15939 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15941 If the value is nil, it is converted to the empty string. If it
15942 is not a string, an error is raised. Also raise an error on
15943 invalid property names.
15945 PROPERTY can be any regular property (see
15946 `org-special-properties'). It can also be \"TODO\",
15947 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15949 For the last two properties, VALUE may have any of the special
15950 values \"earlier\" and \"later\". The function then increases or
15951 decreases scheduled or deadline date by one day."
15952 (cond ((null value) (setq value ""))
15953 ((not (stringp value)) (error "Properties values should be strings"))
15954 ((not (org--valid-property-p property))
15955 (user-error "Invalid property name: \"%s\"" property)))
15956 (org-with-point-at pom
15957 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15958 (org-back-to-heading t)
15959 (org-with-limited-levels (org-back-to-heading t)))
15960 (let ((beg (point)))
15961 (cond
15962 ((equal property "TODO")
15963 (cond ((not (org-string-nw-p value)) (setq value 'none))
15964 ((not (member value org-todo-keywords-1))
15965 (user-error "\"%s\" is not a valid TODO state" value)))
15966 (org-todo value)
15967 (org-set-tags nil 'align))
15968 ((equal property "PRIORITY")
15969 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15970 (org-set-tags nil 'align))
15971 ((equal property "SCHEDULED")
15972 (forward-line)
15973 (if (and (looking-at-p org-planning-line-re)
15974 (re-search-forward
15975 org-scheduled-time-regexp (line-end-position) t))
15976 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15977 ((string= value "later") (org-timestamp-change 1 'day))
15978 ((string= value "") (org-schedule '(4)))
15979 (t (org-schedule nil value)))
15980 (if (member value '("earlier" "later" ""))
15981 (call-interactively #'org-schedule)
15982 (org-schedule nil value))))
15983 ((equal property "DEADLINE")
15984 (forward-line)
15985 (if (and (looking-at-p org-planning-line-re)
15986 (re-search-forward
15987 org-deadline-time-regexp (line-end-position) t))
15988 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15989 ((string= value "later") (org-timestamp-change 1 'day))
15990 ((string= value "") (org-deadline '(4)))
15991 (t (org-deadline nil value)))
15992 (if (member value '("earlier" "later" ""))
15993 (call-interactively #'org-deadline)
15994 (org-deadline nil value))))
15995 ((member property org-special-properties)
15996 (error "The %s property cannot be set with `org-entry-put'" property))
15998 (let* ((range (org-get-property-block beg 'force))
15999 (end (cdr range))
16000 (case-fold-search t))
16001 (goto-char (car range))
16002 (if (re-search-forward (org-re-property property nil t) end t)
16003 (progn (delete-region (match-beginning 0) (match-end 0))
16004 (goto-char (match-beginning 0)))
16005 (goto-char end)
16006 (insert "\n")
16007 (backward-char))
16008 (insert ":" property ":")
16009 (when value (insert " " value))
16010 (org-indent-line)))))
16011 (run-hook-with-args 'org-property-changed-functions property value)))
16013 (defun org-buffer-property-keys
16014 (&optional specials defaults columns ignore-malformed)
16015 "Get all property keys in the current buffer.
16017 When SPECIALS is non-nil, also list the special properties that
16018 reflect things like tags and TODO state.
16020 When DEFAULTS is non-nil, also include properties that has
16021 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16022 DESCRIPTION, LOCATION, and LOGGING and others.
16024 When COLUMNS in non-nil, also include property names given in
16025 COLUMN formats in the current buffer.
16027 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16028 automatically performed, such drawers will be silently ignored."
16029 (let ((case-fold-search t)
16030 (props (append
16031 (and specials org-special-properties)
16032 (and defaults (cons org-effort-property org-default-properties))
16033 nil)))
16034 (org-with-wide-buffer
16035 (goto-char (point-min))
16036 (while (re-search-forward org-property-start-re nil t)
16037 (let ((range (org-get-property-block)))
16038 (catch 'skip
16039 (unless range
16040 (when (and (not ignore-malformed)
16041 (not (org-before-first-heading-p))
16042 (y-or-n-p (format "Malformed drawer at %d, repair?"
16043 (line-beginning-position))))
16044 (org-get-property-block nil t))
16045 (throw 'skip nil))
16046 (goto-char (car range))
16047 (let ((begin (car range))
16048 (end (cdr range)))
16049 ;; Make sure that found property block is not located
16050 ;; before current point, as it would generate an infloop.
16051 ;; It can happen, for example, in the following
16052 ;; situation:
16054 ;; * Headline
16055 ;; :PROPERTIES:
16056 ;; ...
16057 ;; :END:
16058 ;; *************** Inlinetask
16059 ;; #+BEGIN_EXAMPLE
16060 ;; :PROPERTIES:
16061 ;; #+END_EXAMPLE
16063 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16064 (while (< (point) end)
16065 (let ((p (progn (looking-at org-property-re)
16066 (match-string-no-properties 2))))
16067 ;; Only add true property name, not extension symbol.
16068 (push (if (not (string-match-p "\\+\\'" p)) p
16069 (substring p 0 -1))
16070 props))
16071 (forward-line))))
16072 (outline-next-heading)))
16073 (when columns
16074 (goto-char (point-min))
16075 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16076 (let ((element (org-element-at-point)))
16077 (when (memq (org-element-type element) '(keyword node-property))
16078 (let ((value (org-element-property :value element))
16079 (start 0))
16080 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16081 (setq start (match-end 0))
16082 (let ((p (match-string-no-properties 1 value)))
16083 (unless (member-ignore-case p org-special-properties)
16084 (push p props))))))))))
16085 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16087 (defun org-property-values (key)
16088 "List all non-nil values of property KEY in current buffer."
16089 (org-with-wide-buffer
16090 (goto-char (point-min))
16091 (let ((case-fold-search t)
16092 (re (org-re-property key))
16093 values)
16094 (while (re-search-forward re nil t)
16095 (push (org-entry-get (point) key) values))
16096 (delete-dups values))))
16098 (defun org-insert-property-drawer ()
16099 "Insert a property drawer into the current entry."
16100 (org-with-wide-buffer
16101 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16102 (org-back-to-heading t)
16103 (org-with-limited-levels (org-back-to-heading t)))
16104 (forward-line)
16105 (when (looking-at-p org-planning-line-re) (forward-line))
16106 (unless (looking-at-p org-property-drawer-re)
16107 ;; Make sure we start editing a line from current entry, not from
16108 ;; next one. It prevents extending text properties or overlays
16109 ;; belonging to the latter.
16110 (when (bolp) (backward-char))
16111 (let ((begin (1+ (point)))
16112 (inhibit-read-only t))
16113 (insert "\n:PROPERTIES:\n:END:")
16114 (when (eobp) (insert "\n"))
16115 (org-indent-region begin (point))))))
16117 (defun org-insert-drawer (&optional arg drawer)
16118 "Insert a drawer at point.
16120 When optional argument ARG is non-nil, insert a property drawer.
16122 Optional argument DRAWER, when non-nil, is a string representing
16123 drawer's name. Otherwise, the user is prompted for a name.
16125 If a region is active, insert the drawer around that region
16126 instead.
16128 Point is left between drawer's boundaries."
16129 (interactive "P")
16130 (let* ((drawer (if arg "PROPERTIES"
16131 (or drawer (read-from-minibuffer "Drawer: ")))))
16132 (cond
16133 ;; With C-u, fall back on `org-insert-property-drawer'
16134 (arg (org-insert-property-drawer))
16135 ;; Check validity of suggested drawer's name.
16136 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16137 (user-error "Invalid drawer name"))
16138 ;; With an active region, insert a drawer at point.
16139 ((not (org-region-active-p))
16140 (progn
16141 (unless (bolp) (insert "\n"))
16142 (insert (format ":%s:\n\n:END:\n" drawer))
16143 (forward-line -2)))
16144 ;; Otherwise, insert the drawer at point
16146 (let ((rbeg (region-beginning))
16147 (rend (copy-marker (region-end))))
16148 (unwind-protect
16149 (progn
16150 (goto-char rbeg)
16151 (beginning-of-line)
16152 (when (save-excursion
16153 (re-search-forward org-outline-regexp-bol rend t))
16154 (user-error "Drawers cannot contain headlines"))
16155 ;; Position point at the beginning of the first
16156 ;; non-blank line in region. Insert drawer's opening
16157 ;; there, then indent it.
16158 (org-skip-whitespace)
16159 (beginning-of-line)
16160 (insert ":" drawer ":\n")
16161 (forward-line -1)
16162 (indent-for-tab-command)
16163 ;; Move point to the beginning of the first blank line
16164 ;; after the last non-blank line in region. Insert
16165 ;; drawer's closing, then indent it.
16166 (goto-char rend)
16167 (skip-chars-backward " \r\t\n")
16168 (insert "\n:END:")
16169 (deactivate-mark t)
16170 (indent-for-tab-command)
16171 (unless (eolp) (insert "\n")))
16172 ;; Clear marker, whatever the outcome of insertion is.
16173 (set-marker rend nil)))))))
16175 (defvar org-property-set-functions-alist nil
16176 "Property set function alist.
16177 Each entry should have the following format:
16179 (PROPERTY . READ-FUNCTION)
16181 The read function will be called with the same argument as
16182 `org-completing-read'.")
16184 (defun org-set-property-function (property)
16185 "Get the function that should be used to set PROPERTY.
16186 This is computed according to `org-property-set-functions-alist'."
16187 (or (cdr (assoc property org-property-set-functions-alist))
16188 'org-completing-read))
16190 (defun org-read-property-value (property)
16191 "Read PROPERTY value from user."
16192 (let* ((completion-ignore-case t)
16193 (allowed (org-property-get-allowed-values nil property 'table))
16194 (cur (org-entry-get nil property))
16195 (prompt (concat property " value"
16196 (if (and cur (string-match "\\S-" cur))
16197 (concat " [" cur "]") "") ": "))
16198 (set-function (org-set-property-function property))
16199 (val (if allowed
16200 (funcall set-function prompt allowed nil
16201 (not (get-text-property 0 'org-unrestricted
16202 (caar allowed))))
16203 (funcall set-function prompt
16204 (mapcar 'list (org-property-values property))
16205 nil nil "" nil cur))))
16206 (org-trim val)))
16208 (defvar org-last-set-property nil)
16209 (defvar org-last-set-property-value nil)
16210 (defun org-read-property-name ()
16211 "Read a property name."
16212 (let ((completion-ignore-case t)
16213 (default-prop (or (and (org-at-property-p)
16214 (match-string-no-properties 2))
16215 org-last-set-property)))
16216 (org-completing-read
16217 (concat "Property"
16218 (if default-prop (concat " [" default-prop "]") "")
16219 ": ")
16220 (mapcar #'list (org-buffer-property-keys nil t t))
16221 nil nil nil nil default-prop)))
16223 (defun org-set-property-and-value (use-last)
16224 "Allow to set [PROPERTY]: [value] direction from prompt.
16225 When use-default, don't even ask, just use the last
16226 \"[PROPERTY]: [value]\" string from the history."
16227 (interactive "P")
16228 (let* ((completion-ignore-case t)
16229 (pv (or (and use-last org-last-set-property-value)
16230 (org-completing-read
16231 "Enter a \"[Property]: [value]\" pair: "
16232 nil nil nil nil nil
16233 org-last-set-property-value)))
16234 prop val)
16235 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16236 (setq prop (match-string 1 pv)
16237 val (match-string 2 pv))
16238 (org-set-property prop val))))
16240 (defun org-set-property (property value)
16241 "In the current entry, set PROPERTY to VALUE.
16243 When called interactively, this will prompt for a property name, offering
16244 completion on existing and default properties. And then it will prompt
16245 for a value, offering completion either on allowed values (via an inherited
16246 xxx_ALL property) or on existing values in other instances of this property
16247 in the current file.
16249 Throw an error when trying to set a property with an invalid name."
16250 (interactive (list nil nil))
16251 (let ((property (or property (org-read-property-name))))
16252 ;; `org-entry-put' also makes the following check, but this one
16253 ;; avoids polluting `org-last-set-property' and
16254 ;; `org-last-set-property-value' needlessly.
16255 (unless (org--valid-property-p property)
16256 (user-error "Invalid property name: \"%s\"" property))
16257 (let ((value (or value (org-read-property-value property)))
16258 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16259 (setq org-last-set-property property)
16260 (setq org-last-set-property-value (concat property ": " value))
16261 ;; Possibly postprocess the inserted value:
16262 (when fn (setq value (funcall fn value)))
16263 (unless (equal (org-entry-get nil property) value)
16264 (org-entry-put nil property value)))))
16266 (defun org-find-property (property &optional value)
16267 "Find first entry in buffer that sets PROPERTY.
16269 When optional argument VALUE is non-nil, only consider an entry
16270 if it contains PROPERTY set to this value. If PROPERTY should be
16271 explicitly set to nil, use string \"nil\" for VALUE.
16273 Return position where the entry begins, or nil if there is no
16274 such entry. If narrowing is in effect, only search the visible
16275 part of the buffer."
16276 (save-excursion
16277 (goto-char (point-min))
16278 (let ((case-fold-search t)
16279 (re (org-re-property property nil (not value) value)))
16280 (catch 'exit
16281 (while (re-search-forward re nil t)
16282 (when (if value (org-at-property-p)
16283 (org-entry-get (point) property nil t))
16284 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16286 (defun org-delete-property (property)
16287 "In the current entry, delete PROPERTY."
16288 (interactive
16289 (let* ((completion-ignore-case t)
16290 (cat (org-entry-get (point) "CATEGORY"))
16291 (props0 (org-entry-properties nil 'standard))
16292 (props (if cat props0
16293 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16294 (prop (if (< 1 (length props))
16295 (completing-read "Property: " props nil t)
16296 (caar props))))
16297 (list prop)))
16298 (if (not property)
16299 (message "No property to delete in this entry")
16300 (org-entry-delete nil property)
16301 (message "Property \"%s\" deleted" property)))
16303 (defun org-delete-property-globally (property)
16304 "Remove PROPERTY globally, from all entries.
16305 This function ignores narrowing, if any."
16306 (interactive
16307 (let* ((completion-ignore-case t)
16308 (prop (completing-read
16309 "Globally remove property: "
16310 (mapcar #'list (org-buffer-property-keys)))))
16311 (list prop)))
16312 (org-with-wide-buffer
16313 (goto-char (point-min))
16314 (let ((count 0)
16315 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16316 (while (re-search-forward re nil t)
16317 (when (org-entry-delete (point) property) (cl-incf count)))
16318 (message "Property \"%s\" removed from %d entries" property count))))
16320 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16322 (defun org-compute-property-at-point ()
16323 "Compute the property at point.
16324 This looks for an enclosing column format, extracts the operator and
16325 then applies it to the property in the column format's scope."
16326 (interactive)
16327 (unless (org-at-property-p)
16328 (user-error "Not at a property"))
16329 (let ((prop (match-string-no-properties 2)))
16330 (org-columns-get-format-and-top-level)
16331 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16332 (user-error "No operator defined for property %s" prop))
16333 (org-columns-compute prop)))
16335 (defvar org-property-allowed-value-functions nil
16336 "Hook for functions supplying allowed values for a specific property.
16337 The functions must take a single argument, the name of the property, and
16338 return a flat list of allowed values. If \":ETC\" is one of
16339 the values, this means that these values are intended as defaults for
16340 completion, but that other values should be allowed too.
16341 The functions must return nil if they are not responsible for this
16342 property.")
16344 (defun org-property-get-allowed-values (pom property &optional table)
16345 "Get allowed values for the property PROPERTY.
16346 When TABLE is non-nil, return an alist that can directly be used for
16347 completion."
16348 (let (vals)
16349 (cond
16350 ((equal property "TODO")
16351 (setq vals (org-with-point-at pom
16352 (append org-todo-keywords-1 '("")))))
16353 ((equal property "PRIORITY")
16354 (let ((n org-lowest-priority))
16355 (while (>= n org-highest-priority)
16356 (push (char-to-string n) vals)
16357 (setq n (1- n)))))
16358 ((equal property "CATEGORY"))
16359 ((member property org-special-properties))
16360 ((setq vals (run-hook-with-args-until-success
16361 'org-property-allowed-value-functions property)))
16363 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16364 (when (and vals (string-match "\\S-" vals))
16365 (setq vals (car (read-from-string (concat "(" vals ")"))))
16366 (setq vals (mapcar (lambda (x)
16367 (cond ((stringp x) x)
16368 ((numberp x) (number-to-string x))
16369 ((symbolp x) (symbol-name x))
16370 (t "???")))
16371 vals)))))
16372 (when (member ":ETC" vals)
16373 (setq vals (remove ":ETC" vals))
16374 (org-add-props (car vals) '(org-unrestricted t)))
16375 (if table (mapcar 'list vals) vals)))
16377 (defun org-property-previous-allowed-value (&optional _previous)
16378 "Switch to the next allowed value for this property."
16379 (interactive)
16380 (org-property-next-allowed-value t))
16382 (defun org-property-next-allowed-value (&optional previous)
16383 "Switch to the next allowed value for this property."
16384 (interactive)
16385 (unless (org-at-property-p)
16386 (user-error "Not at a property"))
16387 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16388 (key (match-string 2))
16389 (value (match-string 3))
16390 (allowed (or (org-property-get-allowed-values (point) key)
16391 (and (member value '("[ ]" "[-]" "[X]"))
16392 '("[ ]" "[X]"))))
16393 (heading (save-match-data (nth 4 (org-heading-components))))
16394 nval)
16395 (unless allowed
16396 (user-error "Allowed values for this property have not been defined"))
16397 (when previous (setq allowed (reverse allowed)))
16398 (when (member value allowed)
16399 (setq nval (car (cdr (member value allowed)))))
16400 (setq nval (or nval (car allowed)))
16401 (when (equal nval value)
16402 (user-error "Only one allowed value for this property"))
16403 (org-at-property-p)
16404 (replace-match (concat " :" key ": " nval) t t)
16405 (org-indent-line)
16406 (beginning-of-line 1)
16407 (skip-chars-forward " \t")
16408 (when (equal prop org-effort-property)
16409 (org-refresh-property
16410 '((effort . identity)
16411 (effort-minutes . org-duration-to-minutes))
16412 nval)
16413 (when (string= org-clock-current-task heading)
16414 (setq org-clock-effort nval)
16415 (org-clock-update-mode-line)))
16416 (run-hook-with-args 'org-property-changed-functions key nval)))
16418 (defun org-find-olp (path &optional this-buffer)
16419 "Return a marker pointing to the entry at outline path OLP.
16420 If anything goes wrong, throw an error.
16421 You can wrap this call to catch the error like this:
16423 (condition-case msg
16424 (org-mobile-locate-entry (match-string 4))
16425 (error (nth 1 msg)))
16427 The return value will then be either a string with the error message,
16428 or a marker if everything is OK.
16430 If THIS-BUFFER is set, the outline path does not contain a file,
16431 only headings."
16432 (let* ((file (if this-buffer buffer-file-name (pop path)))
16433 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16434 (level 1)
16435 (lmin 1)
16436 (lmax 1)
16437 end found flevel)
16438 (unless buffer (error "File not found :%s" file))
16439 (with-current-buffer buffer
16440 (unless (derived-mode-p 'org-mode)
16441 (error "Buffer %s needs to be in Org mode" buffer))
16442 (org-with-wide-buffer
16443 (goto-char (point-min))
16444 (dolist (heading path)
16445 (let ((re (format org-complex-heading-regexp-format
16446 (regexp-quote heading)))
16447 (cnt 0))
16448 (while (re-search-forward re end t)
16449 (setq level (- (match-end 1) (match-beginning 1)))
16450 (when (and (>= level lmin) (<= level lmax))
16451 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16452 (when (= cnt 0)
16453 (error "Heading not found on level %d: %s" lmax heading))
16454 (when (> cnt 1)
16455 (error "Heading not unique on level %d: %s" lmax heading))
16456 (goto-char found)
16457 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16458 (setq end (save-excursion (org-end-of-subtree t t)))))
16459 (when (org-at-heading-p)
16460 (point-marker))))))
16462 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16463 "Find node HEADING in BUFFER.
16464 Return a marker to the heading if it was found, or nil if not.
16465 If POS-ONLY is set, return just the position instead of a marker.
16467 The heading text must match exact, but it may have a TODO keyword,
16468 a priority cookie and tags in the standard locations."
16469 (with-current-buffer (or buffer (current-buffer))
16470 (org-with-wide-buffer
16471 (goto-char (point-min))
16472 (let (case-fold-search)
16473 (when (re-search-forward
16474 (format org-complex-heading-regexp-format
16475 (regexp-quote heading)) nil t)
16476 (if pos-only
16477 (match-beginning 0)
16478 (move-marker (make-marker) (match-beginning 0))))))))
16480 (defun org-find-exact-heading-in-directory (heading &optional dir)
16481 "Find Org node headline HEADING in all .org files in directory DIR.
16482 When the target headline is found, return a marker to this location."
16483 (let ((files (directory-files (or dir default-directory)
16484 t "\\`[^.#].*\\.org\\'"))
16485 visiting m buffer)
16486 (catch 'found
16487 (dolist (file files)
16488 (message "trying %s" file)
16489 (setq visiting (org-find-base-buffer-visiting file))
16490 (setq buffer (or visiting (find-file-noselect file)))
16491 (setq m (org-find-exact-headline-in-buffer
16492 heading buffer))
16493 (when (and (not m) (not visiting)) (kill-buffer buffer))
16494 (and m (throw 'found m))))))
16496 (defun org-find-entry-with-id (ident)
16497 "Locate the entry that contains the ID property with exact value IDENT.
16498 IDENT can be a string, a symbol or a number, this function will search for
16499 the string representation of it.
16500 Return the position where this entry starts, or nil if there is no such entry."
16501 (interactive "sID: ")
16502 (let ((id (cond
16503 ((stringp ident) ident)
16504 ((symbolp ident) (symbol-name ident))
16505 ((numberp ident) (number-to-string ident))
16506 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16507 (org-with-wide-buffer (org-find-property "ID" id))))
16509 ;;;; Timestamps
16511 (defvar org-last-changed-timestamp nil)
16512 (defvar org-last-inserted-timestamp nil
16513 "The last time stamp inserted with `org-insert-time-stamp'.")
16515 (defun org-time-stamp (arg &optional inactive)
16516 "Prompt for a date/time and insert a time stamp.
16518 If the user specifies a time like HH:MM or if this command is
16519 called with at least one prefix argument, the time stamp contains
16520 the date and the time. Otherwise, only the date is included.
16522 All parts of a date not specified by the user are filled in from
16523 the timestamp at point, if any, or the current date/time
16524 otherwise.
16526 If there is already a timestamp at the cursor, it is replaced.
16528 With two universal prefix arguments, insert an active timestamp
16529 with the current time without prompting the user.
16531 When called from lisp, the timestamp is inactive if INACTIVE is
16532 non-nil."
16533 (interactive "P")
16534 (let* ((ts (cond
16535 ((org-at-date-range-p t)
16536 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16537 ((org-at-timestamp-p 'lax) (match-string 0))))
16538 ;; Default time is either the timestamp at point or today.
16539 ;; When entering a range, only the range start is considered.
16540 (default-time (if (not ts) (current-time)
16541 (apply #'encode-time (org-parse-time-string ts))))
16542 (default-input (and ts (org-get-compact-tod ts)))
16543 (repeater (and ts
16544 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16545 (match-string 0 ts)))
16546 org-time-was-given
16547 org-end-time-was-given
16548 (time
16549 (and (if (equal arg '(16)) (current-time)
16550 ;; Preserve `this-command' and `last-command'.
16551 (let ((this-command this-command)
16552 (last-command last-command))
16553 (org-read-date
16554 arg 'totime nil nil default-time default-input
16555 inactive))))))
16556 (cond
16557 ((and ts
16558 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16559 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16560 (insert "--")
16561 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16563 ;; Make sure we're on a timestamp. When in the middle of a date
16564 ;; range, move arbitrarily to range end.
16565 (unless (org-at-timestamp-p 'lax)
16566 (skip-chars-forward "-")
16567 (org-at-timestamp-p 'lax))
16568 (replace-match "")
16569 (setq org-last-changed-timestamp
16570 (org-insert-time-stamp
16571 time (or org-time-was-given arg)
16572 inactive nil nil (list org-end-time-was-given)))
16573 (when repeater
16574 (backward-char)
16575 (insert " " repeater)
16576 (setq org-last-changed-timestamp
16577 (concat (substring org-last-inserted-timestamp 0 -1)
16578 " " repeater ">")))
16579 (message "Timestamp updated"))
16580 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16581 (t (org-insert-time-stamp
16582 time (or org-time-was-given arg) inactive nil nil
16583 (list org-end-time-was-given))))))
16585 ;; FIXME: can we use this for something else, like computing time differences?
16586 (defun org-get-compact-tod (s)
16587 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16588 (let* ((t1 (match-string 1 s))
16589 (h1 (string-to-number (match-string 2 s)))
16590 (m1 (string-to-number (match-string 3 s)))
16591 (t2 (and (match-end 4) (match-string 5 s)))
16592 (h2 (and t2 (string-to-number (match-string 6 s))))
16593 (m2 (and t2 (string-to-number (match-string 7 s))))
16594 dh dm)
16595 (if (not t2)
16597 (setq dh (- h2 h1) dm (- m2 m1))
16598 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16599 (concat t1 "+" (number-to-string dh)
16600 (and (/= 0 dm) (format ":%02d" dm)))))))
16602 (defun org-time-stamp-inactive (&optional arg)
16603 "Insert an inactive time stamp.
16604 An inactive time stamp is enclosed in square brackets instead of angle
16605 brackets. It is inactive in the sense that it does not trigger agenda entries,
16606 does not link to the calendar and cannot be changed with the S-cursor keys.
16607 So these are more for recording a certain time/date."
16608 (interactive "P")
16609 (org-time-stamp arg 'inactive))
16611 (defvar org-date-ovl (make-overlay 1 1))
16612 (overlay-put org-date-ovl 'face 'org-date-selected)
16613 (delete-overlay org-date-ovl)
16615 (defvar org-ans1) ; dynamically scoped parameter
16616 (defvar org-ans2) ; dynamically scoped parameter
16618 (defvar org-plain-time-of-day-regexp) ; defined below
16620 (defvar org-overriding-default-time nil) ; dynamically scoped
16621 (defvar org-read-date-overlay nil)
16622 (defvar org-dcst nil) ; dynamically scoped
16623 (defvar org-read-date-history nil)
16624 (defvar org-read-date-final-answer nil)
16625 (defvar org-read-date-analyze-futurep nil)
16626 (defvar org-read-date-analyze-forced-year nil)
16627 (defvar org-read-date-inactive)
16629 (defvar org-read-date-minibuffer-local-map
16630 (let* ((map (make-sparse-keymap)))
16631 (set-keymap-parent map minibuffer-local-map)
16632 (org-defkey map (kbd ".")
16633 (lambda () (interactive)
16634 ;; Are we at the beginning of the prompt?
16635 (if (looking-back "^[^:]+: "
16636 (let ((inhibit-field-text-motion t))
16637 (line-beginning-position)))
16638 (org-eval-in-calendar '(calendar-goto-today))
16639 (insert "."))))
16640 (org-defkey map (kbd "C-.")
16641 (lambda () (interactive)
16642 (org-eval-in-calendar '(calendar-goto-today))))
16643 (org-defkey map [(meta shift left)]
16644 (lambda () (interactive)
16645 (org-eval-in-calendar '(calendar-backward-month 1))))
16646 (org-defkey map [(meta shift right)]
16647 (lambda () (interactive)
16648 (org-eval-in-calendar '(calendar-forward-month 1))))
16649 (org-defkey map [(meta shift up)]
16650 (lambda () (interactive)
16651 (org-eval-in-calendar '(calendar-backward-year 1))))
16652 (org-defkey map [(meta shift down)]
16653 (lambda () (interactive)
16654 (org-eval-in-calendar '(calendar-forward-year 1))))
16655 (org-defkey map [?\e (shift left)]
16656 (lambda () (interactive)
16657 (org-eval-in-calendar '(calendar-backward-month 1))))
16658 (org-defkey map [?\e (shift right)]
16659 (lambda () (interactive)
16660 (org-eval-in-calendar '(calendar-forward-month 1))))
16661 (org-defkey map [?\e (shift up)]
16662 (lambda () (interactive)
16663 (org-eval-in-calendar '(calendar-backward-year 1))))
16664 (org-defkey map [?\e (shift down)]
16665 (lambda () (interactive)
16666 (org-eval-in-calendar '(calendar-forward-year 1))))
16667 (org-defkey map [(shift up)]
16668 (lambda () (interactive)
16669 (org-eval-in-calendar '(calendar-backward-week 1))))
16670 (org-defkey map [(shift down)]
16671 (lambda () (interactive)
16672 (org-eval-in-calendar '(calendar-forward-week 1))))
16673 (org-defkey map [(shift left)]
16674 (lambda () (interactive)
16675 (org-eval-in-calendar '(calendar-backward-day 1))))
16676 (org-defkey map [(shift right)]
16677 (lambda () (interactive)
16678 (org-eval-in-calendar '(calendar-forward-day 1))))
16679 (org-defkey map "!"
16680 (lambda () (interactive)
16681 (org-eval-in-calendar '(diary-view-entries))
16682 (message "")))
16683 (org-defkey map ">"
16684 (lambda () (interactive)
16685 (org-eval-in-calendar '(calendar-scroll-left 1))))
16686 (org-defkey map "<"
16687 (lambda () (interactive)
16688 (org-eval-in-calendar '(calendar-scroll-right 1))))
16689 (org-defkey map "\C-v"
16690 (lambda () (interactive)
16691 (org-eval-in-calendar
16692 '(calendar-scroll-left-three-months 1))))
16693 (org-defkey map "\M-v"
16694 (lambda () (interactive)
16695 (org-eval-in-calendar
16696 '(calendar-scroll-right-three-months 1))))
16697 map)
16698 "Keymap for minibuffer commands when using `org-read-date'.")
16700 (defvar org-def)
16701 (defvar org-defdecode)
16702 (defvar org-with-time)
16704 (defvar calendar-setup) ; Dynamically scoped.
16705 (defun org-read-date (&optional with-time to-time from-string prompt
16706 default-time default-input inactive)
16707 "Read a date, possibly a time, and make things smooth for the user.
16708 The prompt will suggest to enter an ISO date, but you can also enter anything
16709 which will at least partially be understood by `parse-time-string'.
16710 Unrecognized parts of the date will default to the current day, month, year,
16711 hour and minute. If this command is called to replace a timestamp at point,
16712 or to enter the second timestamp of a range, the default time is taken
16713 from the existing stamp. Furthermore, the command prefers the future,
16714 so if you are giving a date where the year is not given, and the day-month
16715 combination is already past in the current year, it will assume you
16716 mean next year. For details, see the manual. A few examples:
16718 3-2-5 --> 2003-02-05
16719 feb 15 --> currentyear-02-15
16720 2/15 --> currentyear-02-15
16721 sep 12 9 --> 2009-09-12
16722 12:45 --> today 12:45
16723 22 sept 0:34 --> currentyear-09-22 0:34
16724 12 --> currentyear-currentmonth-12
16725 Fri --> nearest Friday after today
16726 -Tue --> last Tuesday
16727 etc.
16729 Furthermore you can specify a relative date by giving, as the *first* thing
16730 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16731 change in days weeks, months, years.
16732 With a single plus or minus, the date is relative to today. With a double
16733 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16734 +4d --> four days from today
16735 +4 --> same as above
16736 +2w --> two weeks from today
16737 ++5 --> five days from default date
16739 The function understands only English month and weekday abbreviations.
16741 While prompting, a calendar is popped up - you can also select the
16742 date with the mouse (button 1). The calendar shows a period of three
16743 months. To scroll it to other months, use the keys `>' and `<'.
16744 If you don't like the calendar, turn it off with
16745 (setq org-read-date-popup-calendar nil)
16747 With optional argument TO-TIME, the date will immediately be converted
16748 to an internal time.
16749 With an optional argument WITH-TIME, the prompt will suggest to
16750 also insert a time. Note that when WITH-TIME is not set, you can
16751 still enter a time, and this function will inform the calling routine
16752 about this change. The calling routine may then choose to change the
16753 format used to insert the time stamp into the buffer to include the time.
16754 With optional argument FROM-STRING, read from this string instead from
16755 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16756 the time/date that is used for everything that is not specified by the
16757 user."
16758 (require 'parse-time)
16759 (let* ((org-with-time with-time)
16760 (org-time-stamp-rounding-minutes
16761 (if (equal org-with-time '(16))
16762 '(0 0)
16763 org-time-stamp-rounding-minutes))
16764 (org-dcst org-display-custom-times)
16765 (ct (org-current-time))
16766 (org-def (or org-overriding-default-time default-time ct))
16767 (org-defdecode (decode-time org-def))
16768 (cur-frame (selected-frame))
16769 (mouse-autoselect-window nil) ; Don't let the mouse jump
16770 (calendar-setup
16771 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16772 (calendar-move-hook nil)
16773 (calendar-view-diary-initially-flag nil)
16774 (calendar-view-holidays-initially-flag nil)
16775 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16776 ;; Rationalize `org-def' and `org-defdecode', if required.
16777 (when (< (nth 2 org-defdecode) org-extend-today-until)
16778 (setf (nth 2 org-defdecode) -1)
16779 (setf (nth 1 org-defdecode) 59)
16780 (setq org-def (apply #'encode-time org-defdecode))
16781 (setq org-defdecode (decode-time org-def)))
16782 (let* ((timestr (format-time-string
16783 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16784 org-def))
16785 (prompt (concat (if prompt (concat prompt " ") "")
16786 (format "Date+time [%s]: " timestr))))
16787 (cond
16788 (from-string (setq ans from-string))
16789 (org-read-date-popup-calendar
16790 (save-excursion
16791 (save-window-excursion
16792 (calendar)
16793 (when (eq calendar-setup 'calendar-only)
16794 (setq cal-frame
16795 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16796 (select-frame cal-frame))
16797 (org-eval-in-calendar '(setq cursor-type nil) t)
16798 (unwind-protect
16799 (progn
16800 (calendar-forward-day (- (time-to-days org-def)
16801 (calendar-absolute-from-gregorian
16802 (calendar-current-date))))
16803 (org-eval-in-calendar nil t)
16804 (let* ((old-map (current-local-map))
16805 (map (copy-keymap calendar-mode-map))
16806 (minibuffer-local-map
16807 (copy-keymap org-read-date-minibuffer-local-map)))
16808 (org-defkey map (kbd "RET") 'org-calendar-select)
16809 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16810 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16811 (unwind-protect
16812 (progn
16813 (use-local-map map)
16814 (setq org-read-date-inactive inactive)
16815 (add-hook 'post-command-hook 'org-read-date-display)
16816 (setq org-ans0
16817 (read-string prompt
16818 default-input
16819 'org-read-date-history
16820 nil))
16821 ;; org-ans0: from prompt
16822 ;; org-ans1: from mouse click
16823 ;; org-ans2: from calendar motion
16824 (setq ans
16825 (concat org-ans0 " " (or org-ans1 org-ans2))))
16826 (remove-hook 'post-command-hook 'org-read-date-display)
16827 (use-local-map old-map)
16828 (when org-read-date-overlay
16829 (delete-overlay org-read-date-overlay)
16830 (setq org-read-date-overlay nil)))))
16831 (bury-buffer "*Calendar*")
16832 (when cal-frame
16833 (delete-frame cal-frame)
16834 (select-frame-set-input-focus cur-frame))))))
16836 (t ; Naked prompt only
16837 (unwind-protect
16838 (setq ans (read-string prompt default-input
16839 'org-read-date-history timestr))
16840 (when org-read-date-overlay
16841 (delete-overlay org-read-date-overlay)
16842 (setq org-read-date-overlay nil))))))
16844 (setq final (org-read-date-analyze ans org-def org-defdecode))
16846 (when org-read-date-analyze-forced-year
16847 (message "Year was forced into %s"
16848 (if org-read-date-force-compatible-dates
16849 "compatible range (1970-2037)"
16850 "range representable on this machine"))
16851 (ding))
16853 ;; One round trip to get rid of 34th of August and stuff like that....
16854 (setq final (decode-time (apply 'encode-time final)))
16856 (setq org-read-date-final-answer ans)
16858 (if to-time
16859 (apply 'encode-time final)
16860 (if (and (boundp 'org-time-was-given) org-time-was-given)
16861 (format "%04d-%02d-%02d %02d:%02d"
16862 (nth 5 final) (nth 4 final) (nth 3 final)
16863 (nth 2 final) (nth 1 final))
16864 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16866 (defun org-read-date-display ()
16867 "Display the current date prompt interpretation in the minibuffer."
16868 (when org-read-date-display-live
16869 (when org-read-date-overlay
16870 (delete-overlay org-read-date-overlay))
16871 (when (minibufferp (current-buffer))
16872 (save-excursion
16873 (end-of-line 1)
16874 (while (not (equal (buffer-substring
16875 (max (point-min) (- (point) 4)) (point))
16876 " "))
16877 (insert " ")))
16878 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16879 " " (or org-ans1 org-ans2)))
16880 (org-end-time-was-given nil)
16881 (f (org-read-date-analyze ans org-def org-defdecode))
16882 (fmts (if org-dcst
16883 org-time-stamp-custom-formats
16884 org-time-stamp-formats))
16885 (fmt (if (or org-with-time
16886 (and (boundp 'org-time-was-given) org-time-was-given))
16887 (cdr fmts)
16888 (car fmts)))
16889 (txt (format-time-string fmt (apply 'encode-time f)))
16890 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16891 (txt (concat "=> " txt)))
16892 (when (and org-end-time-was-given
16893 (string-match org-plain-time-of-day-regexp txt))
16894 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16895 org-end-time-was-given
16896 (substring txt (match-end 0)))))
16897 (when org-read-date-analyze-futurep
16898 (setq txt (concat txt " (=>F)")))
16899 (setq org-read-date-overlay
16900 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16901 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16903 (defun org-read-date-analyze (ans def defdecode)
16904 "Analyze the combined answer of the date prompt."
16905 ;; FIXME: cleanup and comment
16906 ;; Pass `current-time' result to `decode-time' (instead of calling
16907 ;; without arguments) so that only `current-time' has to be
16908 ;; overridden in tests.
16909 (let ((org-def def)
16910 (org-defdecode defdecode)
16911 (nowdecode (decode-time (current-time)))
16912 delta deltan deltaw deltadef year month day
16913 hour minute second wday pm h2 m2 tl wday1
16914 iso-year iso-weekday iso-week iso-date futurep kill-year)
16915 (setq org-read-date-analyze-futurep nil
16916 org-read-date-analyze-forced-year nil)
16917 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16918 (setq ans "+0"))
16920 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16921 (setq ans (replace-match "" t t ans)
16922 deltan (car delta)
16923 deltaw (nth 1 delta)
16924 deltadef (nth 2 delta)))
16926 ;; Check if there is an iso week date in there. If yes, store the
16927 ;; info and postpone interpreting it until the rest of the parsing
16928 ;; is done.
16929 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16930 (setq iso-year (when (match-end 1)
16931 (org-small-year-to-year
16932 (string-to-number (match-string 1 ans))))
16933 iso-weekday (when (match-end 3)
16934 (string-to-number (match-string 3 ans)))
16935 iso-week (string-to-number (match-string 2 ans)))
16936 (setq ans (replace-match "" t t ans)))
16938 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16939 (when (string-match
16940 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16941 (setq year (if (match-end 2)
16942 (string-to-number (match-string 2 ans))
16943 (progn (setq kill-year t)
16944 (string-to-number (format-time-string "%Y"))))
16945 month (string-to-number (match-string 3 ans))
16946 day (string-to-number (match-string 4 ans)))
16947 (setq year (org-small-year-to-year year))
16948 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16949 t nil ans)))
16951 ;; Help matching dotted european dates
16952 (when (string-match
16953 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16954 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16955 (setq kill-year t)
16956 (string-to-number (format-time-string "%Y")))
16957 day (string-to-number (match-string 1 ans))
16958 month (string-to-number (match-string 2 ans))
16959 ans (replace-match (format "%04d-%02d-%02d" year month day)
16960 t nil ans)))
16962 ;; Help matching american dates, like 5/30 or 5/30/7
16963 (when (string-match
16964 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16965 (setq year (if (match-end 4)
16966 (string-to-number (match-string 4 ans))
16967 (progn (setq kill-year t)
16968 (string-to-number (format-time-string "%Y"))))
16969 month (string-to-number (match-string 1 ans))
16970 day (string-to-number (match-string 2 ans)))
16971 (setq year (org-small-year-to-year year))
16972 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16973 t nil ans)))
16974 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16975 ;; If there is a time with am/pm, and *no* time without it, we convert
16976 ;; so that matching will be successful.
16977 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16978 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16979 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16980 (setq hour (string-to-number (match-string 1 ans))
16981 minute (if (match-end 3)
16982 (string-to-number (match-string 3 ans))
16984 pm (equal ?p
16985 (string-to-char (downcase (match-string 4 ans)))))
16986 (if (and (= hour 12) (not pm))
16987 (setq hour 0)
16988 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16989 (setq ans (replace-match (format "%02d:%02d" hour minute)
16990 t t ans))))
16992 ;; Check if a time range is given as a duration
16993 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16994 (setq hour (string-to-number (match-string 1 ans))
16995 h2 (+ hour (string-to-number (match-string 3 ans)))
16996 minute (string-to-number (match-string 2 ans))
16997 m2 (+ minute (if (match-end 5) (string-to-number
16998 (match-string 5 ans))0)))
16999 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17000 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17001 t t ans)))
17003 ;; Check if there is a time range
17004 (when (boundp 'org-end-time-was-given)
17005 (setq org-time-was-given nil)
17006 (when (and (string-match org-plain-time-of-day-regexp ans)
17007 (match-end 8))
17008 (setq org-end-time-was-given (match-string 8 ans))
17009 (setq ans (concat (substring ans 0 (match-beginning 7))
17010 (substring ans (match-end 7))))))
17012 (setq tl (parse-time-string ans)
17013 day (or (nth 3 tl) (nth 3 org-defdecode))
17014 month
17015 (cond ((nth 4 tl))
17016 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17017 ;; Day was specified. Make sure DAY+MONTH
17018 ;; combination happens in the future.
17019 ((nth 3 tl)
17020 (setq futurep t)
17021 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17022 (nth 4 nowdecode)))
17023 (t (nth 4 org-defdecode)))
17024 year
17025 (cond ((and (not kill-year) (nth 5 tl)))
17026 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17027 ;; Month was guessed in the future and is at least
17028 ;; equal to NOWDECODE's. Fix year accordingly.
17029 (futurep
17030 (if (or (> month (nth 4 nowdecode))
17031 (>= day (nth 3 nowdecode)))
17032 (nth 5 nowdecode)
17033 (1+ (nth 5 nowdecode))))
17034 ;; Month was specified. Make sure MONTH+YEAR
17035 ;; combination happens in the future.
17036 ((nth 4 tl)
17037 (setq futurep t)
17038 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17039 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17040 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17041 (t (nth 5 nowdecode))))
17042 (t (nth 5 org-defdecode)))
17043 hour (or (nth 2 tl) (nth 2 org-defdecode))
17044 minute (or (nth 1 tl) (nth 1 org-defdecode))
17045 second (or (nth 0 tl) 0)
17046 wday (nth 6 tl))
17048 (when (and (eq org-read-date-prefer-future 'time)
17049 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17050 (equal day (nth 3 nowdecode))
17051 (equal month (nth 4 nowdecode))
17052 (equal year (nth 5 nowdecode))
17053 (nth 2 tl)
17054 (or (< (nth 2 tl) (nth 2 nowdecode))
17055 (and (= (nth 2 tl) (nth 2 nowdecode))
17056 (nth 1 tl)
17057 (< (nth 1 tl) (nth 1 nowdecode)))))
17058 (setq day (1+ day)
17059 futurep t))
17061 ;; Special date definitions below
17062 (cond
17063 (iso-week
17064 ;; There was an iso week
17065 (require 'cal-iso)
17066 (setq futurep nil)
17067 (setq year (or iso-year year)
17068 day (or iso-weekday wday 1)
17069 wday nil ; to make sure that the trigger below does not match
17070 iso-date (calendar-gregorian-from-absolute
17071 (calendar-iso-to-absolute
17072 (list iso-week day year))))
17073 ; FIXME: Should we also push ISO weeks into the future?
17074 ; (when (and org-read-date-prefer-future
17075 ; (not iso-year)
17076 ; (< (calendar-absolute-from-gregorian iso-date)
17077 ; (time-to-days (current-time))))
17078 ; (setq year (1+ year)
17079 ; iso-date (calendar-gregorian-from-absolute
17080 ; (calendar-iso-to-absolute
17081 ; (list iso-week day year)))))
17082 (setq month (car iso-date)
17083 year (nth 2 iso-date)
17084 day (nth 1 iso-date)))
17085 (deltan
17086 (setq futurep nil)
17087 (unless deltadef
17088 ;; Pass `current-time' result to `decode-time' (instead of
17089 ;; calling without arguments) so that only `current-time' has
17090 ;; to be overridden in tests.
17091 (let ((now (decode-time (current-time))))
17092 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17093 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17094 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17095 ((equal deltaw "m") (setq month (+ month deltan)))
17096 ((equal deltaw "y") (setq year (+ year deltan)))))
17097 ((and wday (not (nth 3 tl)))
17098 ;; Weekday was given, but no day, so pick that day in the week
17099 ;; on or after the derived date.
17100 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17101 (unless (equal wday wday1)
17102 (setq day (+ day (% (- wday wday1 -7) 7))))))
17103 (when (and (boundp 'org-time-was-given)
17104 (nth 2 tl))
17105 (setq org-time-was-given t))
17106 (when (< year 100) (setq year (+ 2000 year)))
17107 ;; Check of the date is representable
17108 (if org-read-date-force-compatible-dates
17109 (progn
17110 (when (< year 1970)
17111 (setq year 1970 org-read-date-analyze-forced-year t))
17112 (when (> year 2037)
17113 (setq year 2037 org-read-date-analyze-forced-year t)))
17114 (condition-case nil
17115 (ignore (encode-time second minute hour day month year))
17116 (error
17117 (setq year (nth 5 org-defdecode))
17118 (setq org-read-date-analyze-forced-year t))))
17119 (setq org-read-date-analyze-futurep futurep)
17120 (list second minute hour day month year)))
17122 (defvar parse-time-weekdays)
17123 (defun org-read-date-get-relative (s today default)
17124 "Check string S for special relative date string.
17125 TODAY and DEFAULT are internal times, for today and for a default.
17126 Return shift list (N what def-flag)
17127 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17128 N is the number of WHATs to shift.
17129 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17130 the DEFAULT date rather than TODAY."
17131 (require 'parse-time)
17132 (when (and
17133 (string-match
17134 (concat
17135 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17136 "\\([0-9]+\\)?"
17137 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17138 "\\([ \t]\\|$\\)") s)
17139 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17140 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17141 (string-to-char (substring (match-string 1 s) -1))
17142 ?+))
17143 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17144 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17145 (what (if (match-end 3) (match-string 3 s) "d"))
17146 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17147 (date (if rel default today))
17148 (wday (nth 6 (decode-time date)))
17149 delta)
17150 (if wday1
17151 (progn
17152 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17153 (when (= delta 0) (setq delta 7))
17154 (when (= dir ?-)
17155 (setq delta (- delta 7))
17156 (when (= delta 0) (setq delta -7)))
17157 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17158 (list delta "d" rel))
17159 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17161 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17162 "Turn a user-specified date into the internal representation.
17163 The internal representation needed by the calendar is (month day year).
17164 This is a wrapper to handle the brain-dead convention in calendar that
17165 user function argument order change dependent on argument order."
17166 (pcase calendar-date-style
17167 (`american (list arg1 arg2 arg3))
17168 (`european (list arg2 arg1 arg3))
17169 (`iso (list arg2 arg3 arg1))))
17171 (defun org-eval-in-calendar (form &optional keepdate)
17172 "Eval FORM in the calendar window and return to current window.
17173 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17174 (let ((sf (selected-frame))
17175 (sw (selected-window)))
17176 (select-window (get-buffer-window "*Calendar*" t))
17177 (eval form)
17178 (when (and (not keepdate) (calendar-cursor-to-date))
17179 (let* ((date (calendar-cursor-to-date))
17180 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17181 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17182 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17183 (select-window sw)
17184 (select-frame-set-input-focus sf)))
17186 (defun org-calendar-select ()
17187 "Return to `org-read-date' with the date currently selected.
17188 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17189 (interactive)
17190 (when (calendar-cursor-to-date)
17191 (let* ((date (calendar-cursor-to-date))
17192 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17193 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17194 (when (active-minibuffer-window) (exit-minibuffer))))
17196 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17197 "Insert a date stamp for the date given by the internal TIME.
17198 See `format-time-string' for the format of TIME.
17199 WITH-HM means use the stamp format that includes the time of the day.
17200 INACTIVE means use square brackets instead of angular ones, so that the
17201 stamp will not contribute to the agenda.
17202 PRE and POST are optional strings to be inserted before and after the
17203 stamp.
17204 The command returns the inserted time stamp."
17205 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17206 stamp)
17207 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17208 (insert-before-markers (or pre ""))
17209 (when (listp extra)
17210 (setq extra (car extra))
17211 (if (and (stringp extra)
17212 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17213 (setq extra (format "-%02d:%02d"
17214 (string-to-number (match-string 1 extra))
17215 (string-to-number (match-string 2 extra))))
17216 (setq extra nil)))
17217 (when extra
17218 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17219 (insert-before-markers (setq stamp (format-time-string fmt time)))
17220 (insert-before-markers (or post ""))
17221 (setq org-last-inserted-timestamp stamp)))
17223 (defun org-toggle-time-stamp-overlays ()
17224 "Toggle the use of custom time stamp formats."
17225 (interactive)
17226 (setq org-display-custom-times (not org-display-custom-times))
17227 (unless org-display-custom-times
17228 (let ((p (point-min)) (bmp (buffer-modified-p)))
17229 (while (setq p (next-single-property-change p 'display))
17230 (when (and (get-text-property p 'display)
17231 (eq (get-text-property p 'face) 'org-date))
17232 (remove-text-properties
17233 p (setq p (next-single-property-change p 'display))
17234 '(display t))))
17235 (set-buffer-modified-p bmp)))
17236 (org-restart-font-lock)
17237 (setq org-table-may-need-update t)
17238 (if org-display-custom-times
17239 (message "Time stamps are overlaid with custom format")
17240 (message "Time stamp overlays removed")))
17242 (defun org-display-custom-time (beg end)
17243 "Overlay modified time stamp format over timestamp between BEG and END."
17244 (let* ((ts (buffer-substring beg end))
17245 t1 with-hm tf time str (off 0))
17246 (save-match-data
17247 (setq t1 (org-parse-time-string ts t))
17248 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17249 (setq off (- (match-end 0) (match-beginning 0)))))
17250 (setq end (- end off))
17251 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17252 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17253 time (org-fix-decoded-time t1)
17254 str (org-add-props
17255 (format-time-string
17256 (substring tf 1 -1) (apply 'encode-time time))
17257 nil 'mouse-face 'highlight))
17258 (put-text-property beg end 'display str)))
17260 (defun org-fix-decoded-time (time)
17261 "Set 0 instead of nil for the first 6 elements of time.
17262 Don't touch the rest."
17263 (let ((n 0))
17264 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17266 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17267 "Difference between TIMESTAMP-STRING and now in days.
17268 If SECONDS is non-nil, return the difference in seconds."
17269 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17270 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17271 (funcall fdiff (current-time)))))
17273 (defun org-deadline-close-p (timestamp-string &optional ndays)
17274 "Is the time in TIMESTAMP-STRING close to the current date?"
17275 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17276 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17277 (not (org-entry-is-done-p))))
17279 (defun org-get-wdays (ts &optional delay zero-delay)
17280 "Get the deadline lead time appropriate for timestring TS.
17281 When DELAY is non-nil, get the delay time for scheduled items
17282 instead of the deadline lead time. When ZERO-DELAY is non-nil
17283 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17284 don't try to find the delay cookie in the scheduled timestamp."
17285 (let ((tv (if delay org-scheduled-delay-days
17286 org-deadline-warning-days)))
17287 (cond
17288 ((or (and delay (< tv 0))
17289 (and delay zero-delay (<= tv 0))
17290 (and (not delay) (<= tv 0)))
17291 ;; Enforce this value no matter what
17292 (- tv))
17293 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17294 ;; lead time is specified.
17295 (floor (* (string-to-number (match-string 1 ts))
17296 (cdr (assoc (match-string 2 ts)
17297 '(("d" . 1) ("w" . 7)
17298 ("m" . 30.4) ("y" . 365.25)
17299 ("h" . 0.041667)))))))
17300 ;; go for the default.
17301 (t tv))))
17303 (defun org-calendar-select-mouse (ev)
17304 "Return to `org-read-date' with the date currently selected.
17305 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17306 (interactive "e")
17307 (mouse-set-point ev)
17308 (when (calendar-cursor-to-date)
17309 (let* ((date (calendar-cursor-to-date))
17310 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17311 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17312 (when (active-minibuffer-window) (exit-minibuffer))))
17314 (defun org-check-deadlines (ndays)
17315 "Check if there are any deadlines due or past due.
17316 A deadline is considered due if it happens within `org-deadline-warning-days'
17317 days from today's date. If the deadline appears in an entry marked DONE,
17318 it is not shown. A numeric prefix argument NDAYS can be used to test that
17319 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17320 are shown."
17321 (interactive "P")
17322 (let* ((org-warn-days
17323 (cond
17324 ((equal ndays '(4)) 100000)
17325 (ndays (prefix-numeric-value ndays))
17326 (t (abs org-deadline-warning-days))))
17327 (case-fold-search nil)
17328 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17329 (callback
17330 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17331 (message "%d deadlines past-due or due within %d days"
17332 (org-occur regexp nil callback)
17333 org-warn-days)))
17335 (defsubst org-re-timestamp (type)
17336 "Return a regexp for timestamp TYPE.
17337 Allowed values for TYPE are:
17339 all: all timestamps
17340 active: only active timestamps (<...>)
17341 inactive: only inactive timestamps ([...])
17342 scheduled: only scheduled timestamps
17343 deadline: only deadline timestamps
17344 closed: only closed time-stamps
17346 When TYPE is nil, fall back on returning a regexp that matches
17347 both scheduled and deadline timestamps."
17348 (cl-case type
17349 (all org-ts-regexp-both)
17350 (active org-ts-regexp)
17351 (inactive org-ts-regexp-inactive)
17352 (scheduled org-scheduled-time-regexp)
17353 (deadline org-deadline-time-regexp)
17354 (closed org-closed-time-regexp)
17355 (otherwise
17356 (concat "\\<"
17357 (regexp-opt (list org-deadline-string org-scheduled-string))
17358 " *<\\([^>]+\\)>"))))
17360 (defun org-check-before-date (d)
17361 "Check if there are deadlines or scheduled entries before date D."
17362 (interactive (list (org-read-date)))
17363 (let* ((case-fold-search nil)
17364 (regexp (org-re-timestamp org-ts-type))
17365 (ts-type org-ts-type)
17366 (callback
17367 (lambda ()
17368 (let ((match (match-string 1)))
17369 (and (if (memq ts-type '(active inactive all))
17370 (eq (org-element-type (save-excursion
17371 (backward-char)
17372 (org-element-context)))
17373 'timestamp)
17374 (org-at-planning-p))
17375 (time-less-p
17376 (org-time-string-to-time match t)
17377 (org-time-string-to-time d t)))))))
17378 (message "%d entries before %s"
17379 (org-occur regexp nil callback)
17380 d)))
17382 (defun org-check-after-date (d)
17383 "Check if there are deadlines or scheduled entries after date D."
17384 (interactive (list (org-read-date)))
17385 (let* ((case-fold-search nil)
17386 (regexp (org-re-timestamp org-ts-type))
17387 (ts-type org-ts-type)
17388 (callback
17389 (lambda ()
17390 (let ((match (match-string 1)))
17391 (and (if (memq ts-type '(active inactive all))
17392 (eq (org-element-type (save-excursion
17393 (backward-char)
17394 (org-element-context)))
17395 'timestamp)
17396 (org-at-planning-p))
17397 (not (time-less-p
17398 (org-time-string-to-time match t)
17399 (org-time-string-to-time d t))))))))
17400 (message "%d entries after %s"
17401 (org-occur regexp nil callback)
17402 d)))
17404 (defun org-check-dates-range (start-date end-date)
17405 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17406 (interactive (list (org-read-date nil nil nil "Range starts")
17407 (org-read-date nil nil nil "Range end")))
17408 (let ((case-fold-search nil)
17409 (regexp (org-re-timestamp org-ts-type))
17410 (callback
17411 (let ((type org-ts-type))
17412 (lambda ()
17413 (let ((match (match-string 1)))
17414 (and
17415 (if (memq type '(active inactive all))
17416 (eq (org-element-type (save-excursion
17417 (backward-char)
17418 (org-element-context)))
17419 'timestamp)
17420 (org-at-planning-p))
17421 (not (time-less-p
17422 (org-time-string-to-time match t)
17423 (org-time-string-to-time start-date t)))
17424 (time-less-p
17425 (org-time-string-to-time match t)
17426 (org-time-string-to-time end-date t))))))))
17427 (message "%d entries between %s and %s"
17428 (org-occur regexp nil callback) start-date end-date)))
17430 (defun org-evaluate-time-range (&optional to-buffer)
17431 "Evaluate a time range by computing the difference between start and end.
17432 Normally the result is just printed in the echo area, but with prefix arg
17433 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17434 If the time range is actually in a table, the result is inserted into the
17435 next column.
17436 For time difference computation, a year is assumed to be exactly 365
17437 days in order to avoid rounding problems."
17438 (interactive "P")
17440 (org-clock-update-time-maybe)
17441 (save-excursion
17442 (unless (org-at-date-range-p t)
17443 (goto-char (point-at-bol))
17444 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17445 (unless (org-at-date-range-p t)
17446 (user-error "Not at a time-stamp range, and none found in current line")))
17447 (let* ((ts1 (match-string 1))
17448 (ts2 (match-string 2))
17449 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17450 (match-end (match-end 0))
17451 (time1 (org-time-string-to-time ts1))
17452 (time2 (org-time-string-to-time ts2))
17453 (t1 (float-time time1))
17454 (t2 (float-time time2))
17455 (diff (abs (- t2 t1)))
17456 (negative (< (- t2 t1) 0))
17457 ;; (ys (floor (* 365 24 60 60)))
17458 (ds (* 24 60 60))
17459 (hs (* 60 60))
17460 (fy "%dy %dd %02d:%02d")
17461 (fy1 "%dy %dd")
17462 (fd "%dd %02d:%02d")
17463 (fd1 "%dd")
17464 (fh "%02d:%02d")
17465 y d h m align)
17466 (if havetime
17467 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17469 d (floor (/ diff ds)) diff (mod diff ds)
17470 h (floor (/ diff hs)) diff (mod diff hs)
17471 m (floor (/ diff 60)))
17472 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17474 d (floor (+ (/ diff ds) 0.5))
17475 h 0 m 0))
17476 (if (not to-buffer)
17477 (message "%s" (org-make-tdiff-string y d h m))
17478 (if (org-at-table-p)
17479 (progn
17480 (goto-char match-end)
17481 (setq align t)
17482 (and (looking-at " *|") (goto-char (match-end 0))))
17483 (goto-char match-end))
17484 (when (looking-at
17485 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17486 (replace-match ""))
17487 (when negative (insert " -"))
17488 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17489 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17490 (insert " " (format fh h m))))
17491 (when align (org-table-align))
17492 (message "Time difference inserted")))))
17494 (defun org-make-tdiff-string (y d h m)
17495 (let ((fmt "")
17496 (l nil))
17497 (when (> y 0)
17498 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17499 (push y l))
17500 (when (> d 0)
17501 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17502 (push d l))
17503 (when (> h 0)
17504 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17505 (push h l))
17506 (when (> m 0)
17507 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17508 (push m l))
17509 (apply 'format fmt (nreverse l))))
17511 (defun org-time-string-to-time (s &optional zone)
17512 "Convert timestamp string S into internal time.
17513 The optional ZONE is omitted or nil for Emacs local time, t for
17514 Universal Time, ‘wall’ for system wall clock time, or a string as
17515 in the TZ environment variable."
17516 (apply #'encode-time (org-parse-time-string s nil zone)))
17518 (defun org-time-string-to-seconds (s &optional zone)
17519 "Convert a timestamp string S into a number of seconds.
17520 The optional ZONE is omitted or nil for Emacs local time, t for
17521 Universal Time, ‘wall’ for system wall clock time, or a string as
17522 in the TZ environment variable."
17523 (float-time (org-time-string-to-time s zone)))
17525 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17527 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17528 "Convert time stamp S to an absolute day number.
17530 If DAYNR in non-nil, and there is a specifier for a cyclic time
17531 stamp, get the closest date to DAYNR. If PREFER is
17532 `past' (respectively `future') return a date past (respectively
17533 after) or equal to DAYNR.
17535 POS is the location of time stamp S, as a buffer position in
17536 BUFFER.
17538 Diary sexp timestamps are matched against DAYNR, when non-nil.
17539 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17540 signaled."
17541 (cond
17542 ((string-match "\\`%%\\((.*)\\)" s)
17543 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17544 ;; only able to match individual dates. If it fails, raise an
17545 ;; error.
17546 (if (and daynr
17547 (org-diary-sexp-entry
17548 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17549 daynr
17550 (signal 'org-diary-sexp-no-match (list s))))
17551 (daynr (org-closest-date s daynr prefer))
17552 (t (time-to-days
17553 (condition-case errdata
17554 (apply #'encode-time (org-parse-time-string s))
17555 (error (error "Bad timestamp `%s'%s\nError was: %s"
17557 (if (not (and buffer pos)) ""
17558 (format-message " at %d in buffer `%s'" pos buffer))
17559 (cdr errdata))))))))
17561 (defun org-days-to-iso-week (days)
17562 "Return the iso week number."
17563 (require 'cal-iso)
17564 (car (calendar-iso-from-absolute days)))
17566 (defun org-small-year-to-year (year)
17567 "Convert 2-digit years into 4-digit years.
17568 YEAR is expanded into one of the 30 next years, if possible, or
17569 into a past one. Any year larger than 99 is returned unchanged."
17570 (if (>= year 100) year
17571 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17572 (century (/ current 100))
17573 (offset (- year (% current 100))))
17574 (cond ((> offset 30) (+ (* (1- century) 100) year))
17575 ((> offset -70) (+ (* century 100) year))
17576 (t (+ (* (1+ century) 100) year))))))
17578 (defun org-time-from-absolute (d)
17579 "Return the time corresponding to date D.
17580 D may be an absolute day number, or a calendar-type list (month day year)."
17581 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17582 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17584 (defvar org-agenda-current-date)
17585 (defun org-calendar-holiday ()
17586 "List of holidays, for Diary display in Org mode."
17587 (require 'holidays)
17588 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17589 (and hl (mapconcat #'identity hl "; "))))
17591 (defun org-diary-sexp-entry (sexp entry d)
17592 "Process a SEXP diary ENTRY for date D."
17593 (require 'diary-lib)
17594 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17595 ;; dynamically.
17596 (let* ((sexp `(let ((entry ,entry)
17597 (date ',d))
17598 ,(car (read-from-string sexp))))
17599 (result (if calendar-debug-sexp (eval sexp)
17600 (condition-case nil
17601 (eval sexp)
17602 (error
17603 (beep)
17604 (message "Bad sexp at line %d in %s: %s"
17605 (org-current-line)
17606 (buffer-file-name) sexp)
17607 (sleep-for 2))))))
17608 (cond ((stringp result) (split-string result "; "))
17609 ((and (consp result)
17610 (not (consp (cdr result)))
17611 (stringp (cdr result))) (cdr result))
17612 ((and (consp result)
17613 (stringp (car result))) result)
17614 (result entry))))
17616 (defun org-diary-to-ical-string (frombuf)
17617 "Get iCalendar entries from diary entries in buffer FROMBUF.
17618 This uses the icalendar.el library."
17619 (let* ((tmpdir temporary-file-directory)
17620 (tmpfile (make-temp-name
17621 (expand-file-name "orgics" tmpdir)))
17622 buf rtn b e)
17623 (with-current-buffer frombuf
17624 (icalendar-export-region (point-min) (point-max) tmpfile)
17625 (setq buf (find-buffer-visiting tmpfile))
17626 (set-buffer buf)
17627 (goto-char (point-min))
17628 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17629 (setq b (match-beginning 0)))
17630 (goto-char (point-max))
17631 (when (re-search-backward "^END:VEVENT" nil t)
17632 (setq e (match-end 0)))
17633 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17634 (kill-buffer buf)
17635 (delete-file tmpfile)
17636 rtn))
17638 (defun org-closest-date (start current prefer)
17639 "Return closest date to CURRENT starting from START.
17641 CURRENT and START are both time stamps.
17643 When PREFER is `past', return a date that is either CURRENT or
17644 past. When PREFER is `future', return a date that is either
17645 CURRENT or future.
17647 Only time stamps with a repeater are modified. Any other time
17648 stamp stay unchanged. In any case, return value is an absolute
17649 day number."
17650 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17651 ;; No repeater. Do not shift time stamp.
17652 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17653 (let ((value (string-to-number (match-string 1 start)))
17654 (type (match-string 2 start)))
17655 (if (= 0 value)
17656 ;; Repeater with a 0-value is considered as void.
17657 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17658 (let* ((base (org-date-to-gregorian start))
17659 (target (org-date-to-gregorian current))
17660 (sday (calendar-absolute-from-gregorian base))
17661 (cday (calendar-absolute-from-gregorian target))
17662 n1 n2)
17663 ;; If START is already past CURRENT, just return START.
17664 (if (<= cday sday) sday
17665 ;; Compute closest date before (N1) and closest date past
17666 ;; (N2) CURRENT.
17667 (pcase type
17668 ("h"
17669 (let ((missing-hours
17670 (mod (+ (- (* 24 (- cday sday))
17671 (nth 2 (org-parse-time-string start)))
17672 org-extend-today-until)
17673 value)))
17674 (setf n1 (if (= missing-hours 0) cday
17675 (- cday (1+ (/ missing-hours 24)))))
17676 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17677 ((or "d" "w")
17678 (let ((value (if (equal type "w") (* 7 value) value)))
17679 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17680 (setf n2 (+ n1 value))))
17681 ("m"
17682 (let* ((add-months
17683 (lambda (d n)
17684 ;; Add N months to gregorian date D, i.e.,
17685 ;; a list (MONTH DAY YEAR). Return a valid
17686 ;; gregorian date.
17687 (let ((m (+ (nth 0 d) n)))
17688 (list (mod m 12)
17689 (nth 1 d)
17690 (+ (/ m 12) (nth 2 d))))))
17691 (months ; Complete months to TARGET.
17692 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17693 (- (nth 0 target) (nth 0 base))
17694 ;; If START's day is greater than
17695 ;; TARGET's, remove incomplete month.
17696 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17697 value)
17698 value))
17699 (before (funcall add-months base months)))
17700 (setf n1 (calendar-absolute-from-gregorian before))
17701 (setf n2
17702 (calendar-absolute-from-gregorian
17703 (funcall add-months before value)))))
17705 (let* ((d (nth 1 base))
17706 (m (nth 0 base))
17707 (y (nth 2 base))
17708 (years ; Complete years to TARGET.
17709 (* (/ (- (nth 2 target)
17711 ;; If START's month and day are
17712 ;; greater than TARGET's, remove
17713 ;; incomplete year.
17714 (if (or (> (nth 0 target) m)
17715 (and (= (nth 0 target) m)
17716 (> (nth 1 target) d)))
17719 value)
17720 value))
17721 (before (list m d (+ y years))))
17722 (setf n1 (calendar-absolute-from-gregorian before))
17723 (setf n2 (calendar-absolute-from-gregorian
17724 (list m d (+ (nth 2 before) value)))))))
17725 ;; Handle PREFER parameter, if any.
17726 (cond
17727 ((eq prefer 'past) (if (= cday n2) n2 n1))
17728 ((eq prefer 'future) (if (= cday n1) n1 n2))
17729 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17731 (defun org-date-to-gregorian (d)
17732 "Turn any specification of date D into a Gregorian date for the calendar."
17733 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17734 ((and (listp d) (= (length d) 3)) d)
17735 ((stringp d)
17736 (let ((d (org-parse-time-string d)))
17737 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17738 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17740 (defun org-parse-time-string (s &optional nodefault zone)
17741 "Parse the standard Org time string.
17743 This should be a lot faster than the normal `parse-time-string'.
17745 If time is not given, defaults to 0:00. However, with optional
17746 NODEFAULT, hour and minute fields will be nil if not given.
17748 The optional ZONE is omitted or nil for Emacs local time, t for
17749 Universal Time, ‘wall’ for system wall clock time, or a string as
17750 in the TZ environment variable."
17751 (cond ((string-match org-ts-regexp0 s)
17752 (list 0
17753 (when (or (match-beginning 8) (not nodefault))
17754 (string-to-number (or (match-string 8 s) "0")))
17755 (when (or (match-beginning 7) (not nodefault))
17756 (string-to-number (or (match-string 7 s) "0")))
17757 (string-to-number (match-string 4 s))
17758 (string-to-number (match-string 3 s))
17759 (string-to-number (match-string 2 s))
17760 nil nil zone))
17761 ((string-match "^<[^>]+>$" s)
17762 ;; FIXME: `decode-time' needs to be called with ZONE as its
17763 ;; second argument. However, this requires at least Emacs
17764 ;; 25.1. We can do it when we switch to this version as our
17765 ;; minimal requirement.
17766 (decode-time (seconds-to-time (org-matcher-time s))))
17767 (t (error "Not a standard Org time string: %s" s))))
17769 (defun org-timestamp-up (&optional arg)
17770 "Increase the date item at the cursor by one.
17771 If the cursor is on the year, change the year. If it is on the month,
17772 the day or the time, change that.
17773 With prefix ARG, change by that many units."
17774 (interactive "p")
17775 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17777 (defun org-timestamp-down (&optional arg)
17778 "Decrease the date item at the cursor by one.
17779 If the cursor is on the year, change the year. If it is on the month,
17780 the day or the time, change that.
17781 With prefix ARG, change by that many units."
17782 (interactive "p")
17783 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17785 (defun org-timestamp-up-day (&optional arg)
17786 "Increase the date in the time stamp by one day.
17787 With prefix ARG, change that many days."
17788 (interactive "p")
17789 (if (and (not (org-at-timestamp-p 'lax))
17790 (org-at-heading-p))
17791 (org-todo 'up)
17792 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17794 (defun org-timestamp-down-day (&optional arg)
17795 "Decrease the date in the time stamp by one day.
17796 With prefix ARG, change that many days."
17797 (interactive "p")
17798 (if (and (not (org-at-timestamp-p 'lax))
17799 (org-at-heading-p))
17800 (org-todo 'down)
17801 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17803 (defun org-at-timestamp-p (&optional extended)
17804 "Non-nil if point is inside a timestamp.
17806 By default, the function only consider syntactically valid active
17807 timestamps. However, the caller may have a broader definition
17808 for timestamps. As a consequence, optional argument EXTENDED can
17809 be set to the following values
17811 `inactive'
17813 Include also syntactically valid inactive timestamps.
17815 `agenda'
17817 Include timestamps allowed in Agenda, i.e., those in
17818 properties drawers, planning lines and clock lines.
17820 `lax'
17822 Ignore context. The function matches any part of the
17823 document looking like a timestamp. This includes comments,
17824 example blocks...
17826 For backward-compatibility with Org 9.0, every other non-nil
17827 value is equivalent to `inactive'.
17829 When at a timestamp, return the position of the point as a symbol
17830 among `bracket', `after', `year', `month', `hour', `minute',
17831 `day' or a number of character from the last know part of the
17832 time stamp.
17834 When matching, the match groups are the following:
17835 group 1: year
17836 group 2: month
17837 group 3: day number
17838 group 4: day name
17839 group 5: hours, if any
17840 group 6: minutes, if any"
17841 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17842 (pos (point))
17843 (match?
17844 (let ((boundaries (org-in-regexp regexp)))
17845 (save-match-data
17846 (cond ((null boundaries) nil)
17847 ((eq extended 'lax) t)
17849 (or (and (eq extended 'agenda)
17850 (or (org-at-planning-p)
17851 (org-at-property-p)
17852 (and (bound-and-true-p
17853 org-agenda-include-inactive-timestamps)
17854 (org-at-clock-log-p))))
17855 (eq 'timestamp
17856 (save-excursion
17857 (when (= pos (cdr boundaries)) (forward-char -1))
17858 (org-element-type (org-element-context)))))))))))
17859 (cond
17860 ((not match?) nil)
17861 ((= pos (match-beginning 0)) 'bracket)
17862 ;; Distinguish location right before the closing bracket from
17863 ;; right after it.
17864 ((= pos (1- (match-end 0))) 'bracket)
17865 ((= pos (match-end 0)) 'after)
17866 ((org-pos-in-match-range pos 2) 'year)
17867 ((org-pos-in-match-range pos 3) 'month)
17868 ((org-pos-in-match-range pos 7) 'hour)
17869 ((org-pos-in-match-range pos 8) 'minute)
17870 ((or (org-pos-in-match-range pos 4)
17871 (org-pos-in-match-range pos 5)) 'day)
17872 ((and (> pos (or (match-end 8) (match-end 5)))
17873 (< pos (match-end 0)))
17874 (- pos (or (match-end 8) (match-end 5))))
17875 (t 'day))))
17877 (defun org-toggle-timestamp-type ()
17878 "Toggle the type (<active> or [inactive]) of a time stamp."
17879 (interactive)
17880 (when (org-at-timestamp-p 'lax)
17881 (let ((beg (match-beginning 0)) (end (match-end 0))
17882 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17883 (save-excursion
17884 (goto-char beg)
17885 (while (re-search-forward "[][<>]" end t)
17886 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17887 t t)))
17888 (message "Timestamp is now %sactive"
17889 (if (equal (char-after beg) ?<) "" "in")))))
17891 (defun org-at-clock-log-p ()
17892 "Non-nil if point is on a clock log line."
17893 (and (org-match-line org-clock-line-re)
17894 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17896 (defvar org-clock-history) ; defined in org-clock.el
17897 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17898 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17899 "Change the date in the time stamp at point.
17900 The date will be changed by N times WHAT. WHAT can be `day', `month',
17901 `year', `minute', `second'. If WHAT is not given, the cursor position
17902 in the timestamp determines what will be changed.
17903 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17904 (let ((origin (point))
17905 (timestamp? (org-at-timestamp-p 'lax))
17906 origin-cat
17907 with-hm inactive
17908 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17909 extra rem
17910 ts time time0 fixnext clrgx)
17911 (unless timestamp? (user-error "Not at a timestamp"))
17912 (if (and (not what) (eq timestamp? 'bracket))
17913 (org-toggle-timestamp-type)
17914 ;; Point isn't on brackets. Remember the part of the time-stamp
17915 ;; the point was in. Indeed, size of time-stamps may change,
17916 ;; but point must be kept in the same category nonetheless.
17917 (setq origin-cat timestamp?)
17918 (when (and (not what) (not (eq timestamp? 'day))
17919 org-display-custom-times
17920 (get-text-property (point) 'display)
17921 (not (get-text-property (1- (point)) 'display)))
17922 (setq timestamp? 'day))
17923 (setq timestamp? (or what timestamp?)
17924 inactive (= (char-after (match-beginning 0)) ?\[)
17925 ts (match-string 0))
17926 (replace-match "")
17927 (when (string-match
17928 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17930 (setq extra (match-string 1 ts))
17931 (when suppress-tmp-delay
17932 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17933 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17934 (setq with-hm t))
17935 (setq time0 (org-parse-time-string ts))
17936 (when (and updown
17937 (eq timestamp? 'minute)
17938 (not current-prefix-arg))
17939 ;; This looks like s-up and s-down. Change by one rounding step.
17940 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17941 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17942 (setcar (cdr time0) (+ (nth 1 time0)
17943 (if (> n 0) (- rem) (- dm rem))))))
17944 (setq time
17945 (apply #'encode-time
17946 (or (car time0) 0)
17947 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17948 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17949 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17950 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17951 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17952 (nthcdr 6 time0)))
17953 (when (and (memq timestamp? '(hour minute))
17954 extra
17955 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17956 (setq extra (org-modify-ts-extra
17957 extra
17958 (if (eq timestamp? 'hour) 2 5)
17959 n dm)))
17960 (when (integerp timestamp?)
17961 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17962 (when (eq what 'calendar)
17963 (let ((cal-date (org-get-date-from-calendar)))
17964 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17965 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17966 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17967 (setcar time0 (or (car time0) 0))
17968 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17969 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17970 (setq time (apply 'encode-time time0))))
17971 ;; Insert the new time-stamp, and ensure point stays in the same
17972 ;; category as before (i.e. not after the last position in that
17973 ;; category).
17974 (let ((pos (point)))
17975 ;; Stay before inserted string. `save-excursion' is of no use.
17976 (setq org-last-changed-timestamp
17977 (org-insert-time-stamp time with-hm inactive nil nil extra))
17978 (goto-char pos))
17979 (save-match-data
17980 (looking-at org-ts-regexp3)
17981 (goto-char
17982 (pcase origin-cat
17983 ;; `day' category ends before `hour' if any, or at the end
17984 ;; of the day name.
17985 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17986 (`hour (min (match-end 7) origin))
17987 (`minute (min (1- (match-end 8)) origin))
17988 ((pred integerp) (min (1- (match-end 0)) origin))
17989 ;; Point was right after the time-stamp. However, the
17990 ;; time-stamp length might have changed, so refer to
17991 ;; (match-end 0) instead.
17992 (`after (match-end 0))
17993 ;; `year' and `month' have both fixed size: point couldn't
17994 ;; have moved into another part.
17995 (_ origin))))
17996 ;; Update clock if on a CLOCK line.
17997 (org-clock-update-time-maybe)
17998 ;; Maybe adjust the closest clock in `org-clock-history'
17999 (when org-clock-adjust-closest
18000 (if (not (and (org-at-clock-log-p)
18001 (< 1 (length (delq nil (mapcar 'marker-position
18002 org-clock-history))))))
18003 (message "No clock to adjust")
18004 (cond ((save-excursion ; fix previous clock?
18005 (re-search-backward org-ts-regexp0 nil t)
18006 (looking-back (concat org-clock-string " \\[")
18007 (line-beginning-position)))
18008 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18009 ((save-excursion ; fix next clock?
18010 (re-search-backward org-ts-regexp0 nil t)
18011 (looking-at (concat org-ts-regexp0 "\\] =>")))
18012 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18013 (save-window-excursion
18014 ;; Find closest clock to point, adjust the previous/next one in history
18015 (let* ((p (save-excursion (org-back-to-heading t)))
18016 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18017 (clfixnth
18018 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18019 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18020 (if (not clfixpos)
18021 (message "No clock to adjust")
18022 (save-excursion
18023 (org-goto-marker-or-bmk clfixpos)
18024 (org-show-subtree)
18025 (when (re-search-forward clrgx nil t)
18026 (goto-char (match-beginning 1))
18027 (let (org-clock-adjust-closest)
18028 (org-timestamp-change n timestamp? updown))
18029 (message "Clock adjusted in %s for heading: %s"
18030 (file-name-nondirectory (buffer-file-name))
18031 (org-get-heading t t)))))))))
18032 ;; Try to recenter the calendar window, if any.
18033 (when (and org-calendar-follow-timestamp-change
18034 (get-buffer-window "*Calendar*" t)
18035 (memq timestamp? '(day month year)))
18036 (org-recenter-calendar (time-to-days time))))))
18038 (defun org-modify-ts-extra (s pos n dm)
18039 "Change the different parts of the lead-time and repeat fields in timestamp."
18040 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18041 ng h m new rem)
18042 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18043 (cond
18044 ((or (org-pos-in-match-range pos 2)
18045 (org-pos-in-match-range pos 3))
18046 (setq m (string-to-number (match-string 3 s))
18047 h (string-to-number (match-string 2 s)))
18048 (if (org-pos-in-match-range pos 2)
18049 (setq h (+ h n))
18050 (setq n (* dm (with-no-warnings (signum n))))
18051 (unless (= 0 (setq rem (% m dm)))
18052 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18053 (setq m (+ m n)))
18054 (when (< m 0) (setq m (+ m 60) h (1- h)))
18055 (when (> m 59) (setq m (- m 60) h (1+ h)))
18056 (setq h (mod h 24))
18057 (setq ng 1 new (format "-%02d:%02d" h m)))
18058 ((org-pos-in-match-range pos 6)
18059 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18060 ((org-pos-in-match-range pos 5)
18061 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18063 ((org-pos-in-match-range pos 9)
18064 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18065 ((org-pos-in-match-range pos 8)
18066 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18068 (when ng
18069 (setq s (concat
18070 (substring s 0 (match-beginning ng))
18072 (substring s (match-end ng))))))
18075 (defun org-recenter-calendar (d)
18076 "If the calendar is visible, recenter it to date D."
18077 (let ((cwin (get-buffer-window "*Calendar*" t)))
18078 (when cwin
18079 (let ((calendar-move-hook nil))
18080 (with-selected-window cwin
18081 (calendar-goto-date
18082 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18084 (defun org-goto-calendar (&optional arg)
18085 "Go to the Emacs calendar at the current date.
18086 If there is a time stamp in the current line, go to that date.
18087 A prefix ARG can be used to force the current date."
18088 (interactive "P")
18089 (let ((calendar-move-hook nil)
18090 (calendar-view-holidays-initially-flag nil)
18091 (calendar-view-diary-initially-flag nil)
18092 diff)
18093 (when (or (org-at-timestamp-p 'lax)
18094 (org-match-line (concat ".*" org-ts-regexp)))
18095 (let ((d1 (time-to-days (current-time)))
18096 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18097 (setq diff (- d2 d1))))
18098 (calendar)
18099 (calendar-goto-today)
18100 (when (and diff (not arg)) (calendar-forward-day diff))))
18102 (defun org-get-date-from-calendar ()
18103 "Return a list (month day year) of date at point in calendar."
18104 (with-current-buffer "*Calendar*"
18105 (save-match-data
18106 (calendar-cursor-to-date))))
18108 (defun org-date-from-calendar ()
18109 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18110 If there is already a time stamp at the cursor position, update it."
18111 (interactive)
18112 (if (org-at-timestamp-p 'lax)
18113 (org-timestamp-change 0 'calendar)
18114 (let ((cal-date (org-get-date-from-calendar)))
18115 (org-insert-time-stamp
18116 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18118 (defcustom org-effort-durations
18119 `(("min" . 1)
18120 ("h" . 60)
18121 ("d" . ,(* 60 8))
18122 ("w" . ,(* 60 8 5))
18123 ("m" . ,(* 60 8 5 4))
18124 ("y" . ,(* 60 8 5 40)))
18125 "Conversion factor to minutes for an effort modifier.
18127 Each entry has the form (MODIFIER . MINUTES).
18129 In an effort string, a number followed by MODIFIER is multiplied
18130 by the specified number of MINUTES to obtain an effort in
18131 minutes.
18133 For example, if the value of this variable is ((\"hours\" . 60)), then an
18134 effort string \"2hours\" is equivalent to 120 minutes."
18135 :group 'org-agenda
18136 :version "26.1"
18137 :package-version '(Org . "8.3")
18138 :type '(alist :key-type (string :tag "Modifier")
18139 :value-type (number :tag "Minutes")))
18141 (defcustom org-image-actual-width t
18142 "Should we use the actual width of images when inlining them?
18144 When set to t, always use the image width.
18146 When set to a number, use imagemagick (when available) to set
18147 the image's width to this value.
18149 When set to a number in a list, try to get the width from any
18150 #+ATTR.* keyword if it matches a width specification like
18152 #+ATTR_HTML: :width 300px
18154 and fall back on that number if none is found.
18156 When set to nil, try to get the width from an #+ATTR.* keyword
18157 and fall back on the original width if none is found.
18159 This requires Emacs >= 24.1, build with imagemagick support."
18160 :group 'org-appearance
18161 :version "24.4"
18162 :package-version '(Org . "8.0")
18163 :type '(choice
18164 (const :tag "Use the image width" t)
18165 (integer :tag "Use a number of pixels")
18166 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18167 (const :tag "Use #+ATTR* or don't resize" nil)))
18169 (defcustom org-agenda-inhibit-startup nil
18170 "Inhibit startup when preparing agenda buffers.
18171 When this variable is t, the initialization of the Org agenda
18172 buffers is inhibited: e.g. the visibility state is not set, the
18173 tables are not re-aligned, etc."
18174 :type 'boolean
18175 :version "24.3"
18176 :group 'org-agenda)
18178 (defcustom org-agenda-ignore-properties nil
18179 "Avoid updating text properties when building the agenda.
18180 Properties are used to prepare buffers for effort estimates,
18181 appointments, statistics and subtree-local categories.
18182 If you don't use these in the agenda, you can add them to this
18183 list and agenda building will be a bit faster.
18184 The value is a list, with zero or more of the symbols `effort', `appt',
18185 `stats' or `category'."
18186 :type '(set :greedy t
18187 (const effort)
18188 (const appt)
18189 (const stats)
18190 (const category))
18191 :version "26.1"
18192 :package-version '(Org . "8.3")
18193 :group 'org-agenda)
18195 ;;;; Files
18197 (defun org-save-all-org-buffers ()
18198 "Save all Org buffers without user confirmation."
18199 (interactive)
18200 (message "Saving all Org buffers...")
18201 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18202 (when (featurep 'org-id) (org-id-locations-save))
18203 (message "Saving all Org buffers... done"))
18205 (defun org-revert-all-org-buffers ()
18206 "Revert all Org buffers.
18207 Prompt for confirmation when there are unsaved changes.
18208 Be sure you know what you are doing before letting this function
18209 overwrite your changes.
18211 This function is useful in a setup where one tracks org files
18212 with a version control system, to revert on one machine after pulling
18213 changes from another. I believe the procedure must be like this:
18215 1. M-x org-save-all-org-buffers
18216 2. Pull changes from the other machine, resolve conflicts
18217 3. M-x org-revert-all-org-buffers"
18218 (interactive)
18219 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18220 (user-error "Abort"))
18221 (save-excursion
18222 (save-window-excursion
18223 (dolist (b (buffer-list))
18224 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18225 (with-current-buffer b buffer-file-name))
18226 (pop-to-buffer-same-window b)
18227 (revert-buffer t 'no-confirm)))
18228 (when (and (featurep 'org-id) org-id-track-globally)
18229 (org-id-locations-load)))))
18231 ;;;; Agenda files
18233 ;;;###autoload
18234 (defun org-switchb (&optional arg)
18235 "Switch between Org buffers.
18237 With `\\[universal-argument]' prefix, restrict available buffers to files.
18239 With `\\[universal-argument] \\[universal-argument]' \
18240 prefix, restrict available buffers to agenda files."
18241 (interactive "P")
18242 (let ((blist (org-buffer-list
18243 (cond ((equal arg '(4)) 'files)
18244 ((equal arg '(16)) 'agenda)))))
18245 (pop-to-buffer-same-window
18246 (completing-read "Org buffer: "
18247 (mapcar #'list (mapcar #'buffer-name blist))
18248 nil t))))
18250 (defun org-buffer-list (&optional predicate exclude-tmp)
18251 "Return a list of Org buffers.
18252 PREDICATE can be `export', `files' or `agenda'.
18254 export restrict the list to Export buffers.
18255 files restrict the list to buffers visiting Org files.
18256 agenda restrict the list to buffers visiting agenda files.
18258 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18259 (let* ((bfn nil)
18260 (agenda-files (and (eq predicate 'agenda)
18261 (mapcar 'file-truename (org-agenda-files t))))
18262 (filter
18263 (cond
18264 ((eq predicate 'files)
18265 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18266 ((eq predicate 'export)
18267 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18268 ((eq predicate 'agenda)
18269 (lambda (b)
18270 (with-current-buffer b
18271 (and (derived-mode-p 'org-mode)
18272 (setq bfn (buffer-file-name b))
18273 (member (file-truename bfn) agenda-files)))))
18274 (t (lambda (b) (with-current-buffer b
18275 (or (derived-mode-p 'org-mode)
18276 (string-match "\\*Org .*Export"
18277 (buffer-name b)))))))))
18278 (delq nil
18279 (mapcar
18280 (lambda(b)
18281 (if (and (funcall filter b)
18282 (or (not exclude-tmp)
18283 (not (string-match "tmp" (buffer-name b)))))
18285 nil))
18286 (buffer-list)))))
18288 (defun org-agenda-files (&optional unrestricted archives)
18289 "Get the list of agenda files.
18290 Optional UNRESTRICTED means return the full list even if a restriction
18291 is currently in place.
18292 When ARCHIVES is t, include all archive files that are really being
18293 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18294 `org-agenda-archives-mode' is t."
18295 (let ((files
18296 (cond
18297 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18298 ((stringp org-agenda-files) (org-read-agenda-file-list))
18299 ((listp org-agenda-files) org-agenda-files)
18300 (t (error "Invalid value of `org-agenda-files'")))))
18301 (setq files (apply 'append
18302 (mapcar (lambda (f)
18303 (if (file-directory-p f)
18304 (directory-files
18305 f t org-agenda-file-regexp)
18306 (list f)))
18307 files)))
18308 (when org-agenda-skip-unavailable-files
18309 (setq files (delq nil
18310 (mapcar (function
18311 (lambda (file)
18312 (and (file-readable-p file) file)))
18313 files))))
18314 (when (or (eq archives t)
18315 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18316 (setq files (org-add-archive-files files)))
18317 files))
18319 (defun org-agenda-file-p (&optional file)
18320 "Return non-nil, if FILE is an agenda file.
18321 If FILE is omitted, use the file associated with the current
18322 buffer."
18323 (let ((fname (or file (buffer-file-name))))
18324 (and fname
18325 (member (file-truename fname)
18326 (mapcar #'file-truename (org-agenda-files t))))))
18328 (defun org-edit-agenda-file-list ()
18329 "Edit the list of agenda files.
18330 Depending on setup, this either uses customize to edit the variable
18331 `org-agenda-files', or it visits the file that is holding the list. In the
18332 latter case, the buffer is set up in a way that saving it automatically kills
18333 the buffer and restores the previous window configuration."
18334 (interactive)
18335 (if (stringp org-agenda-files)
18336 (let ((cw (current-window-configuration)))
18337 (find-file org-agenda-files)
18338 (setq-local org-window-configuration cw)
18339 (add-hook 'after-save-hook
18340 (lambda ()
18341 (set-window-configuration
18342 (prog1 org-window-configuration
18343 (kill-buffer (current-buffer))))
18344 (org-install-agenda-files-menu)
18345 (message "New agenda file list installed"))
18346 nil 'local)
18347 (message "%s" (substitute-command-keys
18348 "Edit list and finish with \\[save-buffer]")))
18349 (customize-variable 'org-agenda-files)))
18351 (defun org-store-new-agenda-file-list (list)
18352 "Set new value for the agenda file list and save it correctly."
18353 (if (stringp org-agenda-files)
18354 (let ((fe (org-read-agenda-file-list t)) b u)
18355 (while (setq b (find-buffer-visiting org-agenda-files))
18356 (kill-buffer b))
18357 (with-temp-file org-agenda-files
18358 (insert
18359 (mapconcat
18360 (lambda (f) ;; Keep un-expanded entries.
18361 (if (setq u (assoc f fe))
18362 (cdr u)
18364 list "\n")
18365 "\n")))
18366 (let ((org-mode-hook nil) (org-inhibit-startup t)
18367 (org-insert-mode-line-in-empty-file nil))
18368 (setq org-agenda-files list)
18369 (customize-save-variable 'org-agenda-files org-agenda-files))))
18371 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18372 "Read the list of agenda files from a file.
18373 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18374 filenames, used by `org-store-new-agenda-file-list' to write back
18375 un-expanded file names."
18376 (when (file-directory-p org-agenda-files)
18377 (error "`org-agenda-files' cannot be a single directory"))
18378 (when (stringp org-agenda-files)
18379 (with-temp-buffer
18380 (insert-file-contents org-agenda-files)
18381 (mapcar
18382 (lambda (f)
18383 (let ((e (expand-file-name (substitute-in-file-name f)
18384 org-directory)))
18385 (if pair-with-expansion
18386 (cons e f)
18387 e)))
18388 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18390 ;;;###autoload
18391 (defun org-cycle-agenda-files ()
18392 "Cycle through the files in `org-agenda-files'.
18393 If the current buffer visits an agenda file, find the next one in the list.
18394 If the current buffer does not, find the first agenda file."
18395 (interactive)
18396 (let* ((fs (or (org-agenda-files t)
18397 (user-error "No agenda files")))
18398 (files (copy-sequence fs))
18399 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18400 file)
18401 (when tcf
18402 (while (and (setq file (pop files))
18403 (not (equal (file-truename file) tcf)))))
18404 (find-file (car (or files fs)))
18405 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18407 (defun org-agenda-file-to-front (&optional to-end)
18408 "Move/add the current file to the top of the agenda file list.
18409 If the file is not present in the list, it is added to the front. If it is
18410 present, it is moved there. With optional argument TO-END, add/move to the
18411 end of the list."
18412 (interactive "P")
18413 (let ((org-agenda-skip-unavailable-files nil)
18414 (file-alist (mapcar (lambda (x)
18415 (cons (file-truename x) x))
18416 (org-agenda-files t)))
18417 (ctf (file-truename
18418 (or buffer-file-name
18419 (user-error "Please save the current buffer to a file"))))
18420 x had)
18421 (setq x (assoc ctf file-alist) had x)
18423 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18424 (if to-end
18425 (setq file-alist (append (delq x file-alist) (list x)))
18426 (setq file-alist (cons x (delq x file-alist))))
18427 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18428 (org-install-agenda-files-menu)
18429 (message "File %s to %s of agenda file list"
18430 (if had "moved" "added") (if to-end "end" "front"))))
18432 (defun org-remove-file (&optional file)
18433 "Remove current file from the list of files in variable `org-agenda-files'.
18434 These are the files which are being checked for agenda entries.
18435 Optional argument FILE means use this file instead of the current."
18436 (interactive)
18437 (let* ((org-agenda-skip-unavailable-files nil)
18438 (file (or file buffer-file-name
18439 (user-error "Current buffer does not visit a file")))
18440 (true-file (file-truename file))
18441 (afile (abbreviate-file-name file))
18442 (files (delq nil (mapcar
18443 (lambda (x)
18444 (unless (equal true-file
18445 (file-truename x))
18447 (org-agenda-files t)))))
18448 (if (not (= (length files) (length (org-agenda-files t))))
18449 (progn
18450 (org-store-new-agenda-file-list files)
18451 (org-install-agenda-files-menu)
18452 (message "Removed from Org Agenda list: %s" afile))
18453 (message "File was not in list: %s (not removed)" afile))))
18455 (defun org-file-menu-entry (file)
18456 (vector file (list 'find-file file) t))
18458 (defun org-check-agenda-file (file)
18459 "Make sure FILE exists. If not, ask user what to do."
18460 (unless (file-exists-p file)
18461 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18462 (abbreviate-file-name file))
18463 (let ((r (downcase (read-char-exclusive))))
18464 (cond
18465 ((equal r ?r)
18466 (org-remove-file file)
18467 (throw 'nextfile t))
18468 (t (user-error "Abort"))))))
18470 (defun org-get-agenda-file-buffer (file)
18471 "Get an agenda buffer visiting FILE.
18472 If the buffer needs to be created, add it to the list of buffers
18473 which might be released later."
18474 (let ((buf (org-find-base-buffer-visiting file)))
18475 (if buf
18476 buf ; just return it
18477 ;; Make a new buffer and remember it
18478 (setq buf (find-file-noselect file))
18479 (when buf (push buf org-agenda-new-buffers))
18480 buf)))
18482 (defun org-release-buffers (blist)
18483 "Release all buffers in list, asking the user for confirmation when needed.
18484 When a buffer is unmodified, it is just killed. When modified, it is saved
18485 \(if the user agrees) and then killed."
18486 (let (file)
18487 (dolist (buf blist)
18488 (setq file (buffer-file-name buf))
18489 (when (and (buffer-modified-p buf)
18490 file
18491 (y-or-n-p (format "Save file %s? " file)))
18492 (with-current-buffer buf (save-buffer)))
18493 (kill-buffer buf))))
18495 (defun org-agenda-prepare-buffers (files)
18496 "Create buffers for all agenda files, protect archived trees and comments."
18497 (interactive)
18498 (let ((pa '(:org-archived t))
18499 (pc '(:org-comment t))
18500 (pall '(:org-archived t :org-comment t))
18501 (inhibit-read-only t)
18502 (org-inhibit-startup org-agenda-inhibit-startup)
18503 (rea (concat ":" org-archive-tag ":"))
18504 re pos)
18505 (setq org-tag-alist-for-agenda nil
18506 org-tag-groups-alist-for-agenda nil)
18507 (save-excursion
18508 (save-restriction
18509 (dolist (file files)
18510 (catch 'nextfile
18511 (if (bufferp file)
18512 (set-buffer file)
18513 (org-check-agenda-file file)
18514 (set-buffer (org-get-agenda-file-buffer file)))
18515 (widen)
18516 (org-set-regexps-and-options 'tags-only)
18517 (setq pos (point))
18518 (or (memq 'category org-agenda-ignore-properties)
18519 (org-refresh-category-properties))
18520 (or (memq 'stats org-agenda-ignore-properties)
18521 (org-refresh-stats-properties))
18522 (or (memq 'effort org-agenda-ignore-properties)
18523 (org-refresh-effort-properties))
18524 (or (memq 'appt org-agenda-ignore-properties)
18525 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18526 (setq org-todo-keywords-for-agenda
18527 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18528 (setq org-done-keywords-for-agenda
18529 (append org-done-keywords-for-agenda org-done-keywords))
18530 (setq org-todo-keyword-alist-for-agenda
18531 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18532 (setq org-tag-alist-for-agenda
18533 (org-uniquify
18534 (append org-tag-alist-for-agenda
18535 org-current-tag-alist)))
18536 ;; Merge current file's tag groups into global
18537 ;; `org-tag-groups-alist-for-agenda'.
18538 (when org-group-tags
18539 (dolist (alist org-tag-groups-alist)
18540 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18541 (if old
18542 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18543 (push alist org-tag-groups-alist-for-agenda)))))
18544 (org-with-silent-modifications
18545 (save-excursion
18546 (remove-text-properties (point-min) (point-max) pall)
18547 (when org-agenda-skip-archived-trees
18548 (goto-char (point-min))
18549 (while (re-search-forward rea nil t)
18550 (when (org-at-heading-p t)
18551 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18552 (goto-char (point-min))
18553 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18554 (while (re-search-forward re nil t)
18555 (when (save-match-data (org-in-commented-heading-p t))
18556 (add-text-properties
18557 (match-beginning 0) (org-end-of-subtree t) pc)))))
18558 (goto-char pos)))))
18559 (setq org-todo-keywords-for-agenda
18560 (org-uniquify org-todo-keywords-for-agenda))
18561 (setq org-todo-keyword-alist-for-agenda
18562 (org-uniquify org-todo-keyword-alist-for-agenda))))
18565 ;;;; CDLaTeX minor mode
18567 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18568 "Keymap for the minor `org-cdlatex-mode'.")
18570 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18571 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18572 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18573 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18574 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18576 (defvar org-cdlatex-texmathp-advice-is-done nil
18577 "Flag remembering if we have applied the advice to texmathp already.")
18579 (define-minor-mode org-cdlatex-mode
18580 "Toggle the minor `org-cdlatex-mode'.
18581 This mode supports entering LaTeX environment and math in LaTeX fragments
18582 in Org mode.
18583 \\{org-cdlatex-mode-map}"
18584 nil " OCDL" nil
18585 (when org-cdlatex-mode
18586 (require 'cdlatex)
18587 (run-hooks 'cdlatex-mode-hook)
18588 (cdlatex-compute-tables))
18589 (unless org-cdlatex-texmathp-advice-is-done
18590 (setq org-cdlatex-texmathp-advice-is-done t)
18591 (defadvice texmathp (around org-math-always-on activate)
18592 "Always return t in Org buffers.
18593 This is because we want to insert math symbols without dollars even outside
18594 the LaTeX math segments. If Org mode thinks that point is actually inside
18595 an embedded LaTeX fragment, let `texmathp' do its job.
18596 `\\[org-cdlatex-mode-map]'"
18597 (interactive)
18598 (let (p)
18599 (cond
18600 ((not (derived-mode-p 'org-mode)) ad-do-it)
18601 ((eq this-command 'cdlatex-math-symbol)
18602 (setq ad-return-value t
18603 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18605 (let ((p (org-inside-LaTeX-fragment-p)))
18606 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18607 (setq ad-return-value t
18608 texmathp-why '("Org mode embedded math" . 0))
18609 (when p ad-do-it)))))))))
18611 (defun turn-on-org-cdlatex ()
18612 "Unconditionally turn on `org-cdlatex-mode'."
18613 (org-cdlatex-mode 1))
18615 (defun org-try-cdlatex-tab ()
18616 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18617 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18618 - inside a LaTeX fragment, or
18619 - after the first word in a line, where an abbreviation expansion could
18620 insert a LaTeX environment."
18621 (when org-cdlatex-mode
18622 (cond
18623 ;; Before any word on the line: No expansion possible.
18624 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18625 ;; Just after first word on the line: Expand it. Make sure it
18626 ;; cannot happen on headlines, though.
18627 ((save-excursion
18628 (skip-chars-backward "a-zA-Z0-9*")
18629 (skip-chars-backward " \t")
18630 (and (bolp) (not (org-at-heading-p))))
18631 (cdlatex-tab) t)
18632 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18634 (defun org-cdlatex-underscore-caret (&optional _arg)
18635 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18636 Revert to the normal definition outside of these fragments."
18637 (interactive "P")
18638 (if (org-inside-LaTeX-fragment-p)
18639 (call-interactively 'cdlatex-sub-superscript)
18640 (let (org-cdlatex-mode)
18641 (call-interactively (key-binding (vector last-input-event))))))
18643 (defun org-cdlatex-math-modify (&optional _arg)
18644 "Execute `cdlatex-math-modify' in LaTeX fragments.
18645 Revert to the normal definition outside of these fragments."
18646 (interactive "P")
18647 (if (org-inside-LaTeX-fragment-p)
18648 (call-interactively 'cdlatex-math-modify)
18649 (let (org-cdlatex-mode)
18650 (call-interactively (key-binding (vector last-input-event))))))
18652 (defun org-cdlatex-environment-indent (&optional environment item)
18653 "Execute `cdlatex-environment' and indent the inserted environment.
18655 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18657 The inserted environment is indented to current indentation
18658 unless point is at the beginning of the line, in which the
18659 environment remains unintended."
18660 (interactive)
18661 ;; cdlatex-environment always return nil. Therefore, capture output
18662 ;; first and determine if an environment was selected.
18663 (let* ((beg (point-marker))
18664 (end (copy-marker (point) t))
18665 (inserted (progn
18666 (ignore-errors (cdlatex-environment environment item))
18667 (< beg end)))
18668 ;; Figure out how many lines to move forward after the
18669 ;; environment has been inserted.
18670 (lines (when inserted
18671 (save-excursion
18672 (- (cl-loop while (< beg (point))
18673 with x = 0
18674 do (forward-line -1)
18675 (cl-incf x)
18676 finally return x)
18677 (if (progn (goto-char beg)
18678 (and (progn (skip-chars-forward " \t") (eolp))
18679 (progn (skip-chars-backward " \t") (bolp))))
18680 1 0)))))
18681 (env (org-trim (delete-and-extract-region beg end))))
18682 (when inserted
18683 ;; Get indentation of next line unless at column 0.
18684 (let ((ind (if (bolp) 0
18685 (save-excursion
18686 (org-return-indent)
18687 (prog1 (org-get-indentation)
18688 (when (progn (skip-chars-forward " \t") (eolp))
18689 (delete-region beg (point)))))))
18690 (bol (progn (skip-chars-backward " \t") (bolp))))
18691 ;; Insert a newline before environment unless at column zero
18692 ;; to "escape" the current line. Insert a newline if
18693 ;; something is one the same line as \end{ENVIRONMENT}.
18694 (insert
18695 (concat (unless bol "\n") env
18696 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18697 (unless (zerop ind)
18698 (save-excursion
18699 (goto-char beg)
18700 (while (< (point) end)
18701 (unless (eolp) (indent-line-to ind))
18702 (forward-line))))
18703 (goto-char beg)
18704 (forward-line lines)
18705 (indent-line-to ind)))
18706 (set-marker beg nil)
18707 (set-marker end nil)))
18710 ;;;; LaTeX fragments
18712 (defun org-inside-LaTeX-fragment-p ()
18713 "Test if point is inside a LaTeX fragment.
18714 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18715 sequence appearing also before point.
18716 Even though the matchers for math are configurable, this function assumes
18717 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18718 delimiters are skipped when they have been removed by customization.
18719 The return value is nil, or a cons cell with the delimiter and the
18720 position of this delimiter.
18722 This function does a reasonably good job, but can locally be fooled by
18723 for example currency specifications. For example it will assume being in
18724 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18725 fragments that are properly closed, but during editing, we have to live
18726 with the uncertainty caused by missing closing delimiters. This function
18727 looks only before point, not after."
18728 (catch 'exit
18729 (let ((pos (point))
18730 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18731 (lim (save-excursion (org-backward-paragraph) (point)))
18732 dd-on str (start 0) m re)
18733 (goto-char pos)
18734 (when dodollar
18735 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18736 re (nth 1 (assoc "$" org-latex-regexps)))
18737 (while (string-match re str start)
18738 (cond
18739 ((= (match-end 0) (length str))
18740 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18741 ((= (match-end 0) (- (length str) 5))
18742 (throw 'exit nil))
18743 (t (setq start (match-end 0))))))
18744 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18745 (goto-char pos)
18746 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18747 (and (match-beginning 2) (throw 'exit nil))
18748 ;; count $$
18749 (while (re-search-backward "\\$\\$" lim t)
18750 (setq dd-on (not dd-on)))
18751 (goto-char pos)
18752 (when dd-on (cons "$$" m))))))
18754 (defun org-inside-latex-macro-p ()
18755 "Is point inside a LaTeX macro or its arguments?"
18756 (save-match-data
18757 (org-in-regexp
18758 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18760 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18761 "Build an overlay between BEG and END using IMAGE file.
18762 Argument IMAGETYPE is the extension of the displayed image,
18763 as a string. It defaults to \"png\"."
18764 (let ((ov (make-overlay beg end))
18765 (imagetype (or (intern imagetype) 'png)))
18766 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18767 (overlay-put ov 'evaporate t)
18768 (overlay-put ov
18769 'modification-hooks
18770 (list (lambda (o _flag _beg _end &optional _l)
18771 (delete-overlay o))))
18772 (overlay-put ov
18773 'display
18774 (list 'image :type imagetype :file image :ascent 'center))))
18776 (defun org--list-latex-overlays (&optional beg end)
18777 "List all Org LaTeX overlays in current buffer.
18778 Limit to overlays between BEG and END when those are provided."
18779 (cl-remove-if-not
18780 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18781 (overlays-in (or beg (point-min)) (or end (point-max)))))
18783 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18784 "Remove all overlays with LaTeX fragment images in current buffer.
18785 When optional arguments BEG and END are non-nil, remove all
18786 overlays between them instead. Return a non-nil value when some
18787 overlays were removed, nil otherwise."
18788 (let ((overlays (org--list-latex-overlays beg end)))
18789 (mapc #'delete-overlay overlays)
18790 overlays))
18792 (defun org-toggle-latex-fragment (&optional arg)
18793 "Preview the LaTeX fragment at point, or all locally or globally.
18795 If the cursor is on a LaTeX fragment, create the image and overlay
18796 it over the source code, if there is none. Remove it otherwise.
18797 If there is no fragment at point, display all fragments in the
18798 current section.
18800 With prefix ARG, preview or clear image for all fragments in the
18801 current subtree or in the whole buffer when used before the first
18802 headline. With a prefix ARG `\\[universal-argument] \
18803 \\[universal-argument]' preview or clear images
18804 for all fragments in the buffer."
18805 (interactive "P")
18806 (when (display-graphic-p)
18807 (catch 'exit
18808 (save-excursion
18809 (let (beg end msg)
18810 (cond
18811 ((or (equal arg '(16))
18812 (and (equal arg '(4))
18813 (org-with-limited-levels (org-before-first-heading-p))))
18814 (if (org-remove-latex-fragment-image-overlays)
18815 (progn (message "LaTeX fragments images removed from buffer")
18816 (throw 'exit nil))
18817 (setq msg "Creating images for buffer...")))
18818 ((equal arg '(4))
18819 (org-with-limited-levels (org-back-to-heading t))
18820 (setq beg (point))
18821 (setq end (progn (org-end-of-subtree t) (point)))
18822 (if (org-remove-latex-fragment-image-overlays beg end)
18823 (progn
18824 (message "LaTeX fragment images removed from subtree")
18825 (throw 'exit nil))
18826 (setq msg "Creating images for subtree...")))
18827 ((let ((datum (org-element-context)))
18828 (when (memq (org-element-type datum)
18829 '(latex-environment latex-fragment))
18830 (setq beg (org-element-property :begin datum))
18831 (setq end (org-element-property :end datum))
18832 (if (org-remove-latex-fragment-image-overlays beg end)
18833 (progn (message "LaTeX fragment image removed")
18834 (throw 'exit nil))
18835 (setq msg "Creating image...")))))
18837 (org-with-limited-levels
18838 (setq beg (if (org-at-heading-p) (line-beginning-position)
18839 (outline-previous-heading)
18840 (point)))
18841 (setq end (progn (outline-next-heading) (point)))
18842 (if (org-remove-latex-fragment-image-overlays beg end)
18843 (progn
18844 (message "LaTeX fragment images removed from section")
18845 (throw 'exit nil))
18846 (setq msg "Creating images for section...")))))
18847 (let ((file (buffer-file-name (buffer-base-buffer))))
18848 (org-format-latex
18849 (concat org-preview-latex-image-directory "org-ltximg")
18850 beg end
18851 ;; Emacs cannot overlay images from remote hosts. Create
18852 ;; it in `temporary-file-directory' instead.
18853 (if (or (not file) (file-remote-p file))
18854 temporary-file-directory
18855 default-directory)
18856 'overlays msg 'forbuffer org-preview-latex-default-process))
18857 (message (concat msg "done")))))))
18859 (defun org-format-latex
18860 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18861 "Replace LaTeX fragments with links to an image.
18863 The function takes care of creating the replacement image.
18865 Only consider fragments between BEG and END when those are
18866 provided.
18868 When optional argument OVERLAYS is non-nil, display the image on
18869 top of the fragment instead of replacing it.
18871 PROCESSING-TYPE is the conversion method to use, as a symbol.
18873 Some of the options can be changed using the variable
18874 `org-format-latex-options', which see."
18875 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18876 (unless (eq processing-type 'verbatim)
18877 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18878 (cnt 0)
18879 checkdir-flag)
18880 (goto-char (or beg (point-min)))
18881 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18882 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18883 (overlay-recenter (or end (point-max))))
18884 (while (re-search-forward math-regexp end t)
18885 (unless (and overlays
18886 (eq (get-char-property (point) 'org-overlay-type)
18887 'org-latex-overlay))
18888 (let* ((context (org-element-context))
18889 (type (org-element-type context)))
18890 (when (memq type '(latex-environment latex-fragment))
18891 (let ((block-type (eq type 'latex-environment))
18892 (value (org-element-property :value context))
18893 (beg (org-element-property :begin context))
18894 (end (save-excursion
18895 (goto-char (org-element-property :end context))
18896 (skip-chars-backward " \r\t\n")
18897 (point))))
18898 (cond
18899 ((eq processing-type 'mathjax)
18900 ;; Prepare for MathJax processing.
18901 (if (not (string-match "\\`\\$\\$?" value))
18902 (goto-char end)
18903 (delete-region beg end)
18904 (if (string= (match-string 0 value) "$$")
18905 (insert "\\[" (substring value 2 -2) "\\]")
18906 (insert "\\(" (substring value 1 -1) "\\)"))))
18907 ((assq processing-type org-preview-latex-process-alist)
18908 ;; Process to an image.
18909 (cl-incf cnt)
18910 (goto-char beg)
18911 (let* ((processing-info
18912 (cdr (assq processing-type org-preview-latex-process-alist)))
18913 (face (face-at-point))
18914 ;; Get the colors from the face at point.
18916 (let ((color (plist-get org-format-latex-options
18917 :foreground)))
18918 (if (and forbuffer (eq color 'auto))
18919 (face-attribute face :foreground nil 'default)
18920 color)))
18922 (let ((color (plist-get org-format-latex-options
18923 :background)))
18924 (if (and forbuffer (eq color 'auto))
18925 (face-attribute face :background nil 'default)
18926 color)))
18927 (hash (sha1 (prin1-to-string
18928 (list org-format-latex-header
18929 org-latex-default-packages-alist
18930 org-latex-packages-alist
18931 org-format-latex-options
18932 forbuffer value fg bg))))
18933 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18934 (absprefix (expand-file-name prefix dir))
18935 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18936 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18937 (sep (and block-type "\n\n"))
18938 (link (concat sep "[[file:" linkfile "]]" sep))
18939 (options
18940 (org-combine-plists
18941 org-format-latex-options
18942 `(:foreground ,fg :background ,bg))))
18943 (when msg (message msg cnt))
18944 (unless checkdir-flag ; Ensure the directory exists.
18945 (setq checkdir-flag t)
18946 (let ((todir (file-name-directory absprefix)))
18947 (unless (file-directory-p todir)
18948 (make-directory todir t))))
18949 (unless (file-exists-p movefile)
18950 (org-create-formula-image
18951 value movefile options forbuffer processing-type))
18952 (if overlays
18953 (progn
18954 (dolist (o (overlays-in beg end))
18955 (when (eq (overlay-get o 'org-overlay-type)
18956 'org-latex-overlay)
18957 (delete-overlay o)))
18958 (org--format-latex-make-overlay beg end movefile imagetype)
18959 (goto-char end))
18960 (delete-region beg end)
18961 (insert
18962 (org-add-props link
18963 (list 'org-latex-src
18964 (replace-regexp-in-string "\"" "" value)
18965 'org-latex-src-embed-type
18966 (if block-type 'paragraph 'character)))))))
18967 ((eq processing-type 'mathml)
18968 ;; Process to MathML.
18969 (unless (org-format-latex-mathml-available-p)
18970 (user-error "LaTeX to MathML converter not configured"))
18971 (cl-incf cnt)
18972 (when msg (message msg cnt))
18973 (goto-char beg)
18974 (delete-region beg end)
18975 (insert (org-format-latex-as-mathml
18976 value block-type prefix dir)))
18978 (error "Unknown conversion process %s for LaTeX fragments"
18979 processing-type)))))))))))
18981 (defun org-create-math-formula (latex-frag &optional mathml-file)
18982 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18983 Use `org-latex-to-mathml-convert-command'. If the conversion is
18984 sucessful, return the portion between \"<math...> </math>\"
18985 elements otherwise return nil. When MATHML-FILE is specified,
18986 write the results in to that file. When invoked as an
18987 interactive command, prompt for LATEX-FRAG, with initial value
18988 set to the current active region and echo the results for user
18989 inspection."
18990 (interactive (list (let ((frag (when (org-region-active-p)
18991 (buffer-substring-no-properties
18992 (region-beginning) (region-end)))))
18993 (read-string "LaTeX Fragment: " frag nil frag))))
18994 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18995 (let* ((tmp-in-file
18996 (let ((file (file-relative-name
18997 (make-temp-name (expand-file-name "ltxmathml-in")))))
18998 (write-region latex-frag nil file)
18999 file))
19000 (tmp-out-file (file-relative-name
19001 (make-temp-name (expand-file-name "ltxmathml-out"))))
19002 (cmd (format-spec
19003 org-latex-to-mathml-convert-command
19004 `((?j . ,(and org-latex-to-mathml-jar-file
19005 (shell-quote-argument
19006 (expand-file-name
19007 org-latex-to-mathml-jar-file))))
19008 (?I . ,(shell-quote-argument tmp-in-file))
19009 (?i . ,latex-frag)
19010 (?o . ,(shell-quote-argument tmp-out-file)))))
19011 mathml shell-command-output)
19012 (when (called-interactively-p 'any)
19013 (unless (org-format-latex-mathml-available-p)
19014 (user-error "LaTeX to MathML converter not configured")))
19015 (message "Running %s" cmd)
19016 (setq shell-command-output (shell-command-to-string cmd))
19017 (setq mathml
19018 (when (file-readable-p tmp-out-file)
19019 (with-current-buffer (find-file-noselect tmp-out-file t)
19020 (goto-char (point-min))
19021 (when (re-search-forward
19022 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19023 (regexp-quote
19024 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19025 nil t)
19026 (prog1 (match-string 0) (kill-buffer))))))
19027 (cond
19028 (mathml
19029 (setq mathml
19030 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19031 (when mathml-file
19032 (write-region mathml nil mathml-file))
19033 (when (called-interactively-p 'any)
19034 (message mathml)))
19035 ((message "LaTeX to MathML conversion failed")
19036 (message shell-command-output)))
19037 (delete-file tmp-in-file)
19038 (when (file-exists-p tmp-out-file)
19039 (delete-file tmp-out-file))
19040 mathml))
19042 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19043 prefix &optional dir)
19044 "Use `org-create-math-formula' but check local cache first."
19045 (let* ((absprefix (expand-file-name prefix dir))
19046 (print-length nil) (print-level nil)
19047 (formula-id (concat
19048 "formula-"
19049 (sha1
19050 (prin1-to-string
19051 (list latex-frag
19052 org-latex-to-mathml-convert-command)))))
19053 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19054 (formula-cache-dir (file-name-directory formula-cache)))
19056 (unless (file-directory-p formula-cache-dir)
19057 (make-directory formula-cache-dir t))
19059 (unless (file-exists-p formula-cache)
19060 (org-create-math-formula latex-frag formula-cache))
19062 (if (file-exists-p formula-cache)
19063 ;; Successful conversion. Return the link to MathML file.
19064 (org-add-props
19065 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19066 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19067 'org-latex-src-embed-type (if latex-frag-type
19068 'paragraph 'character)))
19069 ;; Failed conversion. Return the LaTeX fragment verbatim
19070 latex-frag)))
19072 (defun org--get-display-dpi ()
19073 "Get the DPI of the display.
19074 The function assumes that the display has the same pixel width in
19075 the horizontal and vertical directions."
19076 (if (display-graphic-p)
19077 (round (/ (display-pixel-height)
19078 (/ (display-mm-height) 25.4)))
19079 (error "Attempt to calculate the dpi of a non-graphic display")))
19081 (defun org-create-formula-image
19082 (string tofile options buffer &optional processing-type)
19083 "Create an image from LaTeX source using external processes.
19085 The LaTeX STRING is saved to a temporary LaTeX file, then
19086 converted to an image file by process PROCESSING-TYPE defined in
19087 `org-preview-latex-process-alist'. A nil value defaults to
19088 `org-preview-latex-default-process'.
19090 The generated image file is eventually moved to TOFILE.
19092 The OPTIONS argument controls the size, foreground color and
19093 background color of the generated image.
19095 When BUFFER non-nil, this function is used for LaTeX previewing.
19096 Otherwise, it is used to deal with LaTeX snippets showed in
19097 a HTML file."
19098 (let* ((processing-type (or processing-type
19099 org-preview-latex-default-process))
19100 (processing-info
19101 (cdr (assq processing-type org-preview-latex-process-alist)))
19102 (programs (plist-get processing-info :programs))
19103 (error-message (or (plist-get processing-info :message) ""))
19104 (use-xcolor (plist-get processing-info :use-xcolor))
19105 (image-input-type (plist-get processing-info :image-input-type))
19106 (image-output-type (plist-get processing-info :image-output-type))
19107 (post-clean (or (plist-get processing-info :post-clean)
19108 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19109 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19110 (latex-header
19111 (or (plist-get processing-info :latex-header)
19112 (org-latex-make-preamble
19113 (org-export-get-environment (org-export-get-backend 'latex))
19114 org-format-latex-header
19115 'snippet)))
19116 (latex-compiler (plist-get processing-info :latex-compiler))
19117 (image-converter (plist-get processing-info :image-converter))
19118 (tmpdir temporary-file-directory)
19119 (texfilebase (make-temp-name
19120 (expand-file-name "orgtex" tmpdir)))
19121 (texfile (concat texfilebase ".tex"))
19122 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19123 '(1.0 . 1.0)))
19124 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19125 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19126 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19127 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19128 "Black"))
19129 (bg (or (plist-get options (if buffer :background :html-background))
19130 "Transparent"))
19131 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19132 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19133 (dolist (program programs)
19134 (org-check-external-command program error-message))
19135 (if use-xcolor
19136 (progn (if (eq fg 'default)
19137 (setq fg (org-latex-color :foreground))
19138 (setq fg (org-latex-color-format fg)))
19139 (if (eq bg 'default)
19140 (setq bg (org-latex-color :background))
19141 (setq bg (org-latex-color-format
19142 (if (string= bg "Transparent") "white" bg))))
19143 (with-temp-file texfile
19144 (insert latex-header)
19145 (insert "\n\\begin{document}\n"
19146 "\\definecolor{fg}{rgb}{" fg "}\n"
19147 "\\definecolor{bg}{rgb}{" bg "}\n"
19148 "\n\\pagecolor{bg}\n"
19149 "\n{\\color{fg}\n"
19150 string
19151 "\n}\n"
19152 "\n\\end{document}\n")))
19153 (if (eq fg 'default)
19154 (setq fg (org-dvipng-color :foreground))
19155 (unless (string= fg "Transparent")
19156 (setq fg (org-dvipng-color-format fg))))
19157 (if (eq bg 'default)
19158 (setq bg (org-dvipng-color :background))
19159 (unless (string= bg "Transparent")
19160 (setq bg (org-dvipng-color-format bg))))
19161 (with-temp-file texfile
19162 (insert latex-header)
19163 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19165 (let* ((err-msg (format "Please adjust `%s' part of \
19166 `org-preview-latex-process-alist'."
19167 processing-type))
19168 (image-input-file
19169 (org-compile-file
19170 texfile latex-compiler image-input-type err-msg log-buf))
19171 (image-output-file
19172 (org-compile-file
19173 image-input-file image-converter image-output-type err-msg log-buf
19174 `((?F . ,(shell-quote-argument fg))
19175 (?B . ,(shell-quote-argument bg))
19176 (?D . ,(shell-quote-argument (format "%s" dpi)))
19177 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19178 (copy-file image-output-file tofile 'replace)
19179 (dolist (e post-clean)
19180 (when (file-exists-p (concat texfilebase e))
19181 (delete-file (concat texfilebase e))))
19182 image-output-file)))
19184 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19185 "Fill a LaTeX header template TPL.
19186 In the template, the following place holders will be recognized:
19188 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19189 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19190 [PACKAGES] \\usepackage statements for PKG
19191 [NO-PACKAGES] do not include PKG
19192 [EXTRA] the string EXTRA
19193 [NO-EXTRA] do not include EXTRA
19195 For backward compatibility, if both the positive and the negative place
19196 holder is missing, the positive one (without the \"NO-\") will be
19197 assumed to be present at the end of the template.
19198 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19199 EXTRA is a string.
19200 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19201 (let (rpl (end ""))
19202 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19203 (setq rpl (if (or (match-end 1) (not def-pkg))
19204 "" (org-latex-packages-to-string def-pkg snippets-p t))
19205 tpl (replace-match rpl t t tpl))
19206 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19208 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19209 (setq rpl (if (or (match-end 1) (not pkg))
19210 "" (org-latex-packages-to-string pkg snippets-p t))
19211 tpl (replace-match rpl t t tpl))
19212 (when pkg (setq end
19213 (concat end "\n"
19214 (org-latex-packages-to-string pkg snippets-p)))))
19216 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19217 (setq rpl (if (or (match-end 1) (not extra))
19218 "" (concat extra "\n"))
19219 tpl (replace-match rpl t t tpl))
19220 (when (and extra (string-match "\\S-" extra))
19221 (setq end (concat end "\n" extra))))
19223 (if (string-match "\\S-" end)
19224 (concat tpl "\n" end)
19225 tpl)))
19227 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19228 "Turn an alist of packages into a string with the \\usepackage macros."
19229 (setq pkg (mapconcat (lambda(p)
19230 (cond
19231 ((stringp p) p)
19232 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19233 (format "%% Package %s omitted" (cadr p)))
19234 ((equal "" (car p))
19235 (format "\\usepackage{%s}" (cadr p)))
19237 (format "\\usepackage[%s]{%s}"
19238 (car p) (cadr p)))))
19240 "\n"))
19241 (if newline (concat pkg "\n") pkg))
19243 (defun org-dvipng-color (attr)
19244 "Return a RGB color specification for dvipng."
19245 (org-dvipng-color-format (face-attribute 'default attr nil)))
19247 (defun org-dvipng-color-format (color-name)
19248 "Convert COLOR-NAME to a RGB color value for dvipng."
19249 (apply #'format "rgb %s %s %s"
19250 (mapcar 'org-normalize-color
19251 (color-values color-name))))
19253 (defun org-latex-color (attr)
19254 "Return a RGB color for the LaTeX color package."
19255 (org-latex-color-format (face-attribute 'default attr nil)))
19257 (defun org-latex-color-format (color-name)
19258 "Convert COLOR-NAME to a RGB color value."
19259 (apply #'format "%s,%s,%s"
19260 (mapcar 'org-normalize-color
19261 (color-values color-name))))
19263 (defun org-normalize-color (value)
19264 "Return string to be used as color value for an RGB component."
19265 (format "%g" (/ value 65535.0)))
19269 ;; Image display
19271 (defvar-local org-inline-image-overlays nil)
19273 (defun org-toggle-inline-images (&optional include-linked)
19274 "Toggle the display of inline images.
19275 INCLUDE-LINKED is passed to `org-display-inline-images'."
19276 (interactive "P")
19277 (if org-inline-image-overlays
19278 (progn
19279 (org-remove-inline-images)
19280 (when (called-interactively-p 'interactive)
19281 (message "Inline image display turned off")))
19282 (org-display-inline-images include-linked)
19283 (when (called-interactively-p 'interactive)
19284 (message (if org-inline-image-overlays
19285 (format "%d images displayed inline"
19286 (length org-inline-image-overlays))
19287 "No images to display inline")))))
19289 (defun org-redisplay-inline-images ()
19290 "Refresh the display of inline images."
19291 (interactive)
19292 (if (not org-inline-image-overlays)
19293 (org-toggle-inline-images)
19294 (org-toggle-inline-images)
19295 (org-toggle-inline-images)))
19297 (defun org-display-inline-images (&optional include-linked refresh beg end)
19298 "Display inline images.
19300 An inline image is a link which follows either of these
19301 conventions:
19303 1. Its path is a file with an extension matching return value
19304 from `image-file-name-regexp' and it has no contents.
19306 2. Its description consists in a single link of the previous
19307 type.
19309 When optional argument INCLUDE-LINKED is non-nil, also links with
19310 a text description part will be inlined. This can be nice for
19311 a quick look at those images, but it does not reflect what
19312 exported files will look like.
19314 When optional argument REFRESH is non-nil, refresh existing
19315 images between BEG and END. This will create new image displays
19316 only if necessary. BEG and END default to the buffer
19317 boundaries."
19318 (interactive "P")
19319 (when (display-graphic-p)
19320 (unless refresh
19321 (org-remove-inline-images)
19322 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19323 (org-with-wide-buffer
19324 (goto-char (or beg (point-min)))
19325 (let* ((case-fold-search t)
19326 (file-extension-re (image-file-name-regexp))
19327 (link-abbrevs (mapcar #'car
19328 (append org-link-abbrev-alist-local
19329 org-link-abbrev-alist)))
19330 ;; Check absolute, relative file names and explicit
19331 ;; "file:" links. Also check link abbreviations since
19332 ;; some might expand to "file" links.
19333 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19334 (and link-abbrevs
19335 (format "\\|\\(?:%s:\\)"
19336 (regexp-opt link-abbrevs))))))
19337 (while (re-search-forward file-types-re end t)
19338 (let ((link (save-match-data (org-element-context))))
19339 ;; Check if we're at an inline image, i.e., an image file
19340 ;; link without a description (unless INCLUDE-LINKED is
19341 ;; non-nil).
19342 (when (and (equal "file" (org-element-property :type link))
19343 (or include-linked
19344 (null (org-element-contents link)))
19345 (string-match-p file-extension-re
19346 (org-element-property :path link)))
19347 (let ((file (expand-file-name
19348 (org-link-unescape
19349 (org-element-property :path link)))))
19350 (when (file-exists-p file)
19351 (let ((width
19352 ;; Apply `org-image-actual-width' specifications.
19353 (cond
19354 ((not (image-type-available-p 'imagemagick)) nil)
19355 ((eq org-image-actual-width t) nil)
19356 ((listp org-image-actual-width)
19358 ;; First try to find a width among
19359 ;; attributes associated to the paragraph
19360 ;; containing link.
19361 (let ((paragraph
19362 (let ((e link))
19363 (while (and (setq e (org-element-property
19364 :parent e))
19365 (not (eq (org-element-type e)
19366 'paragraph))))
19367 e)))
19368 (when paragraph
19369 (save-excursion
19370 (goto-char (org-element-property :begin paragraph))
19371 (when
19372 (re-search-forward
19373 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19374 (org-element-property
19375 :post-affiliated paragraph)
19377 (string-to-number (match-string 1))))))
19378 ;; Otherwise, fall-back to provided number.
19379 (car org-image-actual-width)))
19380 ((numberp org-image-actual-width)
19381 org-image-actual-width)))
19382 (old (get-char-property-and-overlay
19383 (org-element-property :begin link)
19384 'org-image-overlay)))
19385 (if (and (car-safe old) refresh)
19386 (image-refresh (overlay-get (cdr old) 'display))
19387 (let ((image (create-image file
19388 (and width 'imagemagick)
19390 :width width)))
19391 (when image
19392 (let ((ov (make-overlay
19393 (org-element-property :begin link)
19394 (progn
19395 (goto-char
19396 (org-element-property :end link))
19397 (skip-chars-backward " \t")
19398 (point)))))
19399 (overlay-put ov 'display image)
19400 (overlay-put ov 'face 'default)
19401 (overlay-put ov 'org-image-overlay t)
19402 (overlay-put
19403 ov 'modification-hooks
19404 (list 'org-display-inline-remove-overlay))
19405 (push ov org-inline-image-overlays)))))))))))))))
19407 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19408 "Remove inline-display overlay if a corresponding region is modified."
19409 (let ((inhibit-modification-hooks t))
19410 (when (and ov after)
19411 (delete ov org-inline-image-overlays)
19412 (delete-overlay ov))))
19414 (defun org-remove-inline-images ()
19415 "Remove inline display of images."
19416 (interactive)
19417 (mapc #'delete-overlay org-inline-image-overlays)
19418 (setq org-inline-image-overlays nil))
19420 ;;;; Key bindings
19422 (defun org-remap (map &rest commands)
19423 "In MAP, remap the functions given in COMMANDS.
19424 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19425 (let (new old)
19426 (while commands
19427 (setq old (pop commands) new (pop commands))
19428 (org-defkey map (vector 'remap old) new))))
19430 ;; Outline functions from `outline-mode-prefix-map'
19431 ;; that can be remapped in Org:
19432 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19433 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19434 (define-key org-mode-map [remap outline-forward-same-level]
19435 'org-forward-heading-same-level)
19436 (define-key org-mode-map [remap outline-backward-same-level]
19437 'org-backward-heading-same-level)
19438 (define-key org-mode-map [remap outline-show-branches]
19439 'org-kill-note-or-show-branches)
19440 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19441 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19442 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19443 (define-key org-mode-map [remap outline-next-visible-heading]
19444 'org-next-visible-heading)
19445 (define-key org-mode-map [remap outline-previous-visible-heading]
19446 'org-previous-visible-heading)
19447 (define-key org-mode-map [remap show-children] 'org-show-children)
19449 ;; Outline functions from `outline-mode-prefix-map' that can not
19450 ;; be remapped in Org:
19452 ;; - the column "key binding" shows whether the Outline function is still
19453 ;; available in Org mode on the same key that it has been bound to in
19454 ;; Outline mode:
19455 ;; - "overridden": key used for a different functionality in Org mode
19456 ;; - else: key still bound to the same Outline function in Org mode
19458 ;; | Outline function | key binding | Org replacement |
19459 ;; |------------------------------------+-------------+--------------------------|
19460 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19461 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19462 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19463 ;; | `show-entry' | overridden | no replacement |
19464 ;; | `show-branches' | `C-c C-k' | still same function |
19465 ;; | `show-subtree' | overridden | visibility cycling |
19466 ;; | `show-all' | overridden | no replacement |
19467 ;; | `hide-subtree' | overridden | visibility cycling |
19468 ;; | `hide-body' | overridden | no replacement |
19469 ;; | `hide-entry' | overridden | visibility cycling |
19470 ;; | `hide-leaves' | overridden | no replacement |
19471 ;; | `hide-sublevels' | overridden | no replacement |
19472 ;; | `hide-other' | overridden | no replacement |
19474 ;; Make `C-c C-x' a prefix key
19475 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19477 ;; TAB key with modifiers
19478 (org-defkey org-mode-map "\C-i" 'org-cycle)
19479 (org-defkey org-mode-map [(tab)] 'org-cycle)
19480 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19481 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19483 ;; The following line is necessary under Suse GNU/Linux
19484 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19485 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19486 (define-key org-mode-map [backtab] 'org-shifttab)
19488 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19489 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19490 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19492 ;; Cursor keys with modifiers
19493 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19494 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19495 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19496 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19498 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19499 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19500 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19501 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19502 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19503 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19505 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19506 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19507 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19508 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19510 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19511 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19512 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19513 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19515 ;; Babel keys
19516 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19517 (dolist (pair org-babel-key-bindings)
19518 (define-key org-babel-map (car pair) (cdr pair)))
19520 ;;; Extra keys for tty access.
19521 ;; We only set them when really needed because otherwise the
19522 ;; menus don't show the simple keys
19524 (when (or org-use-extra-keys (not window-system))
19525 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19526 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19527 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19528 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19529 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19530 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19531 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19532 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19533 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19534 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19535 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19536 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19537 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19538 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19539 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19540 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19541 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19542 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19543 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19544 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19545 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19546 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19547 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19548 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19549 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19550 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19551 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19552 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19554 ;; All the other keys
19555 (org-remap org-mode-map
19556 'self-insert-command 'org-self-insert-command
19557 'delete-char 'org-delete-char
19558 'delete-backward-char 'org-delete-backward-char)
19559 (org-defkey org-mode-map "|" 'org-force-self-insert)
19561 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19562 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19563 (if (boundp 'narrow-map)
19564 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19565 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19566 (if (boundp 'narrow-map)
19567 (org-defkey narrow-map "b" 'org-narrow-to-block)
19568 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19569 (if (boundp 'narrow-map)
19570 (org-defkey narrow-map "e" 'org-narrow-to-element)
19571 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19572 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19573 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19574 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19575 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19576 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19577 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19578 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19579 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19580 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19581 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19582 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19583 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19584 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19585 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19586 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19587 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19588 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19589 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19590 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19591 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19592 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19593 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19594 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19595 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19596 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19597 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19598 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19599 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19600 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19601 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19602 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19603 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19604 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19605 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19606 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19607 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19608 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19609 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19610 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19611 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19612 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19613 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19614 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19615 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19616 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19617 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19618 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19619 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19620 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19621 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19622 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19623 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19624 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19625 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19626 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19627 (org-defkey org-mode-map "\C-c^" 'org-sort)
19628 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19629 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19630 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19631 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19632 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19633 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19634 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19635 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19636 (org-defkey org-mode-map "\C-m" 'org-return)
19637 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19638 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19639 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19640 (org-defkey org-mode-map (kbd "C-c TAB") #'org-table-toggle-column-width)
19641 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19642 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19643 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19644 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19645 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19646 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19647 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19648 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19649 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19650 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19651 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19652 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19653 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19654 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19655 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19656 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19657 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19658 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19659 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19660 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19661 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19662 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19664 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19665 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19666 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19668 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19669 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19670 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19671 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19672 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19673 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19674 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19675 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19676 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19677 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19678 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19679 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19680 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19681 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19682 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19683 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19684 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19685 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19686 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19687 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19688 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19689 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19691 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19692 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19693 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19694 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19695 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19697 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19699 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19701 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19702 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19704 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19707 (defconst org-speed-commands-default
19709 ("Outline Navigation")
19710 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19711 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19712 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19713 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19714 ("F" . org-next-block)
19715 ("B" . org-previous-block)
19716 ("u" . (org-speed-move-safe 'outline-up-heading))
19717 ("j" . org-goto)
19718 ("g" . (org-refile t))
19719 ("Outline Visibility")
19720 ("c" . org-cycle)
19721 ("C" . org-shifttab)
19722 (" " . org-display-outline-path)
19723 ("s" . org-narrow-to-subtree)
19724 ("=" . org-columns)
19725 ("Outline Structure Editing")
19726 ("U" . org-metaup)
19727 ("D" . org-metadown)
19728 ("r" . org-metaright)
19729 ("l" . org-metaleft)
19730 ("R" . org-shiftmetaright)
19731 ("L" . org-shiftmetaleft)
19732 ("i" . (progn (forward-char 1) (call-interactively
19733 'org-insert-heading-respect-content)))
19734 ("^" . org-sort)
19735 ("w" . org-refile)
19736 ("a" . org-archive-subtree-default-with-confirmation)
19737 ("@" . org-mark-subtree)
19738 ("#" . org-toggle-comment)
19739 ("Clock Commands")
19740 ("I" . org-clock-in)
19741 ("O" . org-clock-out)
19742 ("Meta Data Editing")
19743 ("t" . org-todo)
19744 ("," . (org-priority))
19745 ("0" . (org-priority ?\ ))
19746 ("1" . (org-priority ?A))
19747 ("2" . (org-priority ?B))
19748 ("3" . (org-priority ?C))
19749 (":" . org-set-tags-command)
19750 ("e" . org-set-effort)
19751 ("E" . org-inc-effort)
19752 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19753 (org-entry-put (point) "APPT_WARNTIME" m)))
19754 ("Agenda Views etc")
19755 ("v" . org-agenda)
19756 ("/" . org-sparse-tree)
19757 ("Misc")
19758 ("o" . org-open-at-point)
19759 ("?" . org-speed-command-help)
19760 ("<" . (org-agenda-set-restriction-lock 'subtree))
19761 (">" . (org-agenda-remove-restriction-lock))
19763 "The default speed commands.")
19765 (defun org-print-speed-command (e)
19766 (if (> (length (car e)) 1)
19767 (progn
19768 (princ "\n")
19769 (princ (car e))
19770 (princ "\n")
19771 (princ (make-string (length (car e)) ?-))
19772 (princ "\n"))
19773 (princ (car e))
19774 (princ " ")
19775 (if (symbolp (cdr e))
19776 (princ (symbol-name (cdr e)))
19777 (prin1 (cdr e)))
19778 (princ "\n")))
19780 (defun org-speed-command-help ()
19781 "Show the available speed commands."
19782 (interactive)
19783 (if (not org-use-speed-commands)
19784 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19785 (with-output-to-temp-buffer "*Help*"
19786 (princ "User-defined Speed commands\n===========================\n")
19787 (mapc #'org-print-speed-command org-speed-commands-user)
19788 (princ "\n")
19789 (princ "Built-in Speed commands\n=======================\n")
19790 (mapc #'org-print-speed-command org-speed-commands-default))
19791 (with-current-buffer "*Help*"
19792 (setq truncate-lines t))))
19794 (defun org-speed-move-safe (cmd)
19795 "Execute CMD, but make sure that the cursor always ends up in a headline.
19796 If not, return to the original position and throw an error."
19797 (interactive)
19798 (let ((pos (point)))
19799 (call-interactively cmd)
19800 (unless (and (bolp) (org-at-heading-p))
19801 (goto-char pos)
19802 (error "Boundary reached while executing %s" cmd))))
19804 (defvar org-self-insert-command-undo-counter 0)
19806 (defvar org-table-auto-blank-field) ; defined in org-table.el
19807 (defvar org-speed-command nil)
19809 (defun org-speed-command-activate (keys)
19810 "Hook for activating single-letter speed commands.
19811 `org-speed-commands-default' specifies a minimal command set.
19812 Use `org-speed-commands-user' for further customization."
19813 (when (or (and (bolp) (looking-at org-outline-regexp))
19814 (and (functionp org-use-speed-commands)
19815 (funcall org-use-speed-commands)))
19816 (cdr (assoc keys (append org-speed-commands-user
19817 org-speed-commands-default)))))
19819 (defun org-babel-speed-command-activate (keys)
19820 "Hook for activating single-letter code block commands."
19821 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19822 (cdr (assoc keys org-babel-key-bindings))))
19824 (defcustom org-speed-command-hook
19825 '(org-speed-command-activate org-babel-speed-command-activate)
19826 "Hook for activating speed commands at strategic locations.
19827 Hook functions are called in sequence until a valid handler is
19828 found.
19830 Each hook takes a single argument, a user-pressed command key
19831 which is also a `self-insert-command' from the global map.
19833 Within the hook, examine the cursor position and the command key
19834 and return nil or a valid handler as appropriate. Handler could
19835 be one of an interactive command, a function, or a form.
19837 Set `org-use-speed-commands' to non-nil value to enable this
19838 hook. The default setting is `org-speed-command-activate'."
19839 :group 'org-structure
19840 :version "24.1"
19841 :type 'hook)
19843 (defun org-self-insert-command (N)
19844 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19845 If the cursor is in a table looking at whitespace, the whitespace is
19846 overwritten, and the table is not marked as requiring realignment."
19847 (interactive "p")
19848 (org-check-before-invisible-edit 'insert)
19849 (cond
19850 ((and org-use-speed-commands
19851 (let ((kv (this-command-keys-vector)))
19852 (setq org-speed-command
19853 (run-hook-with-args-until-success
19854 'org-speed-command-hook
19855 (make-string 1 (aref kv (1- (length kv))))))))
19856 (cond
19857 ((commandp org-speed-command)
19858 (setq this-command org-speed-command)
19859 (call-interactively org-speed-command))
19860 ((functionp org-speed-command)
19861 (funcall org-speed-command))
19862 ((and org-speed-command (listp org-speed-command))
19863 (eval org-speed-command))
19864 (t (let (org-use-speed-commands)
19865 (call-interactively 'org-self-insert-command)))))
19866 ((and
19867 (org-at-table-p)
19868 (eq N 1)
19869 (not (org-region-active-p))
19870 (progn
19871 ;; Check if we blank the field, and if that triggers align.
19872 (and (featurep 'org-table) org-table-auto-blank-field
19873 (memq last-command
19874 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19875 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19876 ;; Got extra space, this field does not determine
19877 ;; column width.
19878 (let (org-table-may-need-update) (org-table-blank-field))
19879 ;; No extra space, this field may determine column
19880 ;; width.
19881 (org-table-blank-field)))
19883 (looking-at "[^|\n]* \\( \\)|"))
19884 ;; There is room for insertion without re-aligning the table.
19885 (delete-region (match-beginning 1) (match-end 1))
19886 (self-insert-command N))
19888 (setq org-table-may-need-update t)
19889 (self-insert-command N)
19890 (org-fix-tags-on-the-fly)
19891 (when org-self-insert-cluster-for-undo
19892 (if (not (eq last-command 'org-self-insert-command))
19893 (setq org-self-insert-command-undo-counter 1)
19894 (if (>= org-self-insert-command-undo-counter 20)
19895 (setq org-self-insert-command-undo-counter 1)
19896 (and (> org-self-insert-command-undo-counter 0)
19897 buffer-undo-list (listp buffer-undo-list)
19898 (not (cadr buffer-undo-list)) ; remove nil entry
19899 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19900 (setq org-self-insert-command-undo-counter
19901 (1+ org-self-insert-command-undo-counter))))))))
19903 (defun org-check-before-invisible-edit (kind)
19904 "Check is editing if kind KIND would be dangerous with invisible text around.
19905 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19906 ;; First, try to get out of here as quickly as possible, to reduce overhead
19907 (when (and org-catch-invisible-edits
19908 (or (not (boundp 'visible-mode)) (not visible-mode))
19909 (or (get-char-property (point) 'invisible)
19910 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19911 ;; OK, we need to take a closer look. Do not consider
19912 ;; invisibility obtained through text properties (e.g., link
19913 ;; fontification), as it cannot be toggled.
19914 (let* ((invisible-at-point
19915 (pcase (get-char-property-and-overlay (point) 'invisible)
19916 (`(,_ . ,(and (pred overlayp) o)) o)))
19917 ;; Assume that point cannot land in the middle of an
19918 ;; overlay, or between two overlays.
19919 (invisible-before-point
19920 (and (not invisible-at-point)
19921 (not (bobp))
19922 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19923 (`(,_ . ,(and (pred overlayp) o)) o))))
19924 (border-and-ok-direction
19926 ;; Check if we are acting predictably before invisible
19927 ;; text.
19928 (and invisible-at-point
19929 (memq kind '(insert delete-backward)))
19930 ;; Check if we are acting predictably after invisible text
19931 ;; This works not well, and I have turned it off. It seems
19932 ;; better to always show and stop after invisible text.
19933 ;; (and (not invisible-at-point) invisible-before-point
19934 ;; (memq kind '(insert delete)))
19936 (when (or invisible-at-point invisible-before-point)
19937 (when (eq org-catch-invisible-edits 'error)
19938 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19939 (if (and org-custom-properties-overlays
19940 (y-or-n-p "Display invisible properties in this buffer? "))
19941 (org-toggle-custom-properties-visibility)
19942 ;; Make the area visible
19943 (save-excursion
19944 (when invisible-before-point
19945 (goto-char
19946 (previous-single-char-property-change (point) 'invisible)))
19947 ;; Remove whatever overlay is currently making yet-to-be
19948 ;; edited text invisible. Also remove nested invisibility
19949 ;; related overlays.
19950 (delete-overlay (or invisible-at-point invisible-before-point))
19951 (let ((origin (if invisible-at-point (point) (1- (point)))))
19952 (while (pcase (get-char-property-and-overlay origin 'invisible)
19953 (`(,_ . ,(and (pred overlayp) o))
19954 (delete-overlay o)
19955 t)))))
19956 (cond
19957 ((eq org-catch-invisible-edits 'show)
19958 ;; That's it, we do the edit after showing
19959 (message
19960 "Unfolding invisible region around point before editing")
19961 (sit-for 1))
19962 ((and (eq org-catch-invisible-edits 'smart)
19963 border-and-ok-direction)
19964 (message "Unfolding invisible region around point before editing"))
19966 ;; Don't do the edit, make the user repeat it in full visibility
19967 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19969 (defun org-fix-tags-on-the-fly ()
19970 "Align tags in headline at point.
19971 Unlike to `org-set-tags', it ignores region and sorting."
19972 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19973 (org-at-heading-p))
19974 (let ((org-ignore-region t)
19975 (org-tags-sort-function nil))
19976 (org-set-tags nil t))))
19978 (defun org-delete-backward-char (N)
19979 "Like `delete-backward-char', insert whitespace at field end in tables.
19980 When deleting backwards, in tables this function will insert whitespace in
19981 front of the next \"|\" separator, to keep the table aligned. The table will
19982 still be marked for re-alignment if the field did fill the entire column,
19983 because, in this case the deletion might narrow the column."
19984 (interactive "p")
19985 (save-match-data
19986 (org-check-before-invisible-edit 'delete-backward)
19987 (if (and (org-at-table-p)
19988 (eq N 1)
19989 (not (org-region-active-p))
19990 (string-match "|" (buffer-substring (point-at-bol) (point)))
19991 (looking-at ".*?|"))
19992 (let ((pos (point))
19993 (noalign (looking-at "[^|\n\r]* |"))
19994 (c org-table-may-need-update))
19995 (backward-delete-char N)
19996 (unless overwrite-mode
19997 (skip-chars-forward "^|")
19998 (insert " ")
19999 (goto-char (1- pos)))
20000 ;; noalign: if there were two spaces at the end, this field
20001 ;; does not determine the width of the column.
20002 (when noalign (setq org-table-may-need-update c)))
20003 (backward-delete-char N)
20004 (org-fix-tags-on-the-fly))))
20006 (defun org-delete-char (N)
20007 "Like `delete-char', but insert whitespace at field end in tables.
20008 When deleting characters, in tables this function will insert whitespace in
20009 front of the next \"|\" separator, to keep the table aligned. The table will
20010 still be marked for re-alignment if the field did fill the entire column,
20011 because, in this case the deletion might narrow the column."
20012 (interactive "p")
20013 (save-match-data
20014 (org-check-before-invisible-edit 'delete)
20015 (if (and (org-at-table-p)
20016 (not (bolp))
20017 (not (= (char-after) ?|))
20018 (eq N 1))
20019 (if (looking-at ".*?|")
20020 (let ((pos (point))
20021 (noalign (looking-at "[^|\n\r]* |"))
20022 (c org-table-may-need-update))
20023 (replace-match
20024 (concat (substring (match-string 0) 1 -1) " |") nil t)
20025 (goto-char pos)
20026 ;; noalign: if there were two spaces at the end, this field
20027 ;; does not determine the width of the column.
20028 (when noalign (setq org-table-may-need-update c)))
20029 (delete-char N))
20030 (delete-char N)
20031 (org-fix-tags-on-the-fly))))
20033 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20034 (put 'org-self-insert-command 'delete-selection
20035 (lambda ()
20036 (not (run-hook-with-args-until-success
20037 'self-insert-uses-region-functions))))
20038 (put 'orgtbl-self-insert-command 'delete-selection
20039 (lambda ()
20040 (not (run-hook-with-args-until-success
20041 'self-insert-uses-region-functions))))
20042 (put 'org-delete-char 'delete-selection 'supersede)
20043 (put 'org-delete-backward-char 'delete-selection 'supersede)
20044 (put 'org-yank 'delete-selection 'yank)
20046 ;; Make `flyspell-mode' delay after some commands
20047 (put 'org-self-insert-command 'flyspell-delayed t)
20048 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20049 (put 'org-delete-char 'flyspell-delayed t)
20050 (put 'org-delete-backward-char 'flyspell-delayed t)
20052 ;; Make pabbrev-mode expand after Org mode commands
20053 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20054 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20056 (defun org-transpose-words ()
20057 "Transpose words for Org.
20058 This uses the `org-mode-transpose-word-syntax-table' syntax
20059 table, which interprets characters in `org-emphasis-alist' as
20060 word constituents."
20061 (interactive)
20062 (with-syntax-table org-mode-transpose-word-syntax-table
20063 (call-interactively 'transpose-words)))
20064 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20066 (defvar org-ctrl-c-ctrl-c-hook nil
20067 "Hook for functions attaching themselves to `C-c C-c'.
20069 This can be used to add additional functionality to the C-c C-c
20070 key which executes context-dependent commands. This hook is run
20071 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20072 run after the last test.
20074 Each function will be called with no arguments. The function
20075 must check if the context is appropriate for it to act. If yes,
20076 it should do its thing and then return a non-nil value. If the
20077 context is wrong, just do nothing and return nil.")
20079 (defvar org-ctrl-c-ctrl-c-final-hook nil
20080 "Hook for functions attaching themselves to `C-c C-c'.
20082 This can be used to add additional functionality to the C-c C-c
20083 key which executes context-dependent commands. This hook is run
20084 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20085 before the first test.
20087 Each function will be called with no arguments. The function
20088 must check if the context is appropriate for it to act. If yes,
20089 it should do its thing and then return a non-nil value. If the
20090 context is wrong, just do nothing and return nil.")
20092 (defvar org-tab-first-hook nil
20093 "Hook for functions to attach themselves to TAB.
20094 See `org-ctrl-c-ctrl-c-hook' for more information.
20095 This hook runs as the first action when TAB is pressed, even before
20096 `org-cycle' messes around with the `outline-regexp' to cater for
20097 inline tasks and plain list item folding.
20098 If any function in this hook returns t, any other actions that
20099 would have been caused by TAB (such as table field motion or visibility
20100 cycling) will not occur.")
20102 (defvar org-tab-after-check-for-table-hook nil
20103 "Hook for functions to attach themselves to TAB.
20104 See `org-ctrl-c-ctrl-c-hook' for more information.
20105 This hook runs after it has been established that the cursor is not in a
20106 table, but before checking if the cursor is in a headline or if global cycling
20107 should be done.
20108 If any function in this hook returns t, not other actions like visibility
20109 cycling will be done.")
20111 (defvar org-tab-after-check-for-cycling-hook nil
20112 "Hook for functions to attach themselves to TAB.
20113 See `org-ctrl-c-ctrl-c-hook' for more information.
20114 This hook runs after it has been established that not table field motion and
20115 not visibility should be done because of current context. This is probably
20116 the place where a package like yasnippets can hook in.")
20118 (defvar org-tab-before-tab-emulation-hook nil
20119 "Hook for functions to attach themselves to TAB.
20120 See `org-ctrl-c-ctrl-c-hook' for more information.
20121 This hook runs after every other options for TAB have been exhausted, but
20122 before indentation and \t insertion takes place.")
20124 (defvar org-metaleft-hook nil
20125 "Hook for functions attaching themselves to `M-left'.
20126 See `org-ctrl-c-ctrl-c-hook' for more information.")
20127 (defvar org-metaright-hook nil
20128 "Hook for functions attaching themselves to `M-right'.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.")
20130 (defvar org-metaup-hook nil
20131 "Hook for functions attaching themselves to `M-up'.
20132 See `org-ctrl-c-ctrl-c-hook' for more information.")
20133 (defvar org-metadown-hook nil
20134 "Hook for functions attaching themselves to `M-down'.
20135 See `org-ctrl-c-ctrl-c-hook' for more information.")
20136 (defvar org-shiftmetaleft-hook nil
20137 "Hook for functions attaching themselves to `M-S-left'.
20138 See `org-ctrl-c-ctrl-c-hook' for more information.")
20139 (defvar org-shiftmetaright-hook nil
20140 "Hook for functions attaching themselves to `M-S-right'.
20141 See `org-ctrl-c-ctrl-c-hook' for more information.")
20142 (defvar org-shiftmetaup-hook nil
20143 "Hook for functions attaching themselves to `M-S-up'.
20144 See `org-ctrl-c-ctrl-c-hook' for more information.")
20145 (defvar org-shiftmetadown-hook nil
20146 "Hook for functions attaching themselves to `M-S-down'.
20147 See `org-ctrl-c-ctrl-c-hook' for more information.")
20148 (defvar org-metareturn-hook nil
20149 "Hook for functions attaching themselves to `M-RET'.
20150 See `org-ctrl-c-ctrl-c-hook' for more information.")
20151 (defvar org-shiftup-hook nil
20152 "Hook for functions attaching themselves to `S-up'.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.")
20154 (defvar org-shiftup-final-hook nil
20155 "Hook for functions attaching themselves to `S-up'.
20156 This one runs after all other options except shift-select have been excluded.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20158 (defvar org-shiftdown-hook nil
20159 "Hook for functions attaching themselves to `S-down'.
20160 See `org-ctrl-c-ctrl-c-hook' for more information.")
20161 (defvar org-shiftdown-final-hook nil
20162 "Hook for functions attaching themselves to `S-down'.
20163 This one runs after all other options except shift-select have been excluded.
20164 See `org-ctrl-c-ctrl-c-hook' for more information.")
20165 (defvar org-shiftleft-hook nil
20166 "Hook for functions attaching themselves to `S-left'.
20167 See `org-ctrl-c-ctrl-c-hook' for more information.")
20168 (defvar org-shiftleft-final-hook nil
20169 "Hook for functions attaching themselves to `S-left'.
20170 This one runs after all other options except shift-select have been excluded.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.")
20172 (defvar org-shiftright-hook nil
20173 "Hook for functions attaching themselves to `S-right'.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.")
20175 (defvar org-shiftright-final-hook nil
20176 "Hook for functions attaching themselves to `S-right'.
20177 This one runs after all other options except shift-select have been excluded.
20178 See `org-ctrl-c-ctrl-c-hook' for more information.")
20180 (defun org-modifier-cursor-error ()
20181 "Throw an error, a modified cursor command was applied in wrong context."
20182 (user-error "This command is active in special context like tables, headlines or items"))
20184 (defun org-shiftselect-error ()
20185 "Throw an error because Shift-Cursor command was applied in wrong context."
20186 (if (and (boundp 'shift-select-mode) shift-select-mode)
20187 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20188 (user-error "This command works only in special context like headlines or timestamps")))
20190 (defun org-call-for-shift-select (cmd)
20191 (let ((this-command-keys-shift-translated t))
20192 (call-interactively cmd)))
20194 (defun org-shifttab (&optional arg)
20195 "Global visibility cycling or move to previous table field.
20196 Call `org-table-previous-field' within a table.
20197 When ARG is nil, cycle globally through visibility states.
20198 When ARG is a numeric prefix, show contents of this level."
20199 (interactive "P")
20200 (cond
20201 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20202 ((integerp arg)
20203 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20204 (message "Content view to level: %d" arg)
20205 (org-content (prefix-numeric-value arg2))
20206 (org-cycle-show-empty-lines t)
20207 (setq org-cycle-global-status 'overview)))
20208 (t (call-interactively 'org-global-cycle))))
20210 (defun org-shiftmetaleft ()
20211 "Promote subtree or delete table column.
20212 Calls `org-promote-subtree', `org-outdent-item-tree', or
20213 `org-table-delete-column', depending on context. See the
20214 individual commands for more information."
20215 (interactive)
20216 (cond
20217 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20218 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20219 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20220 ((if (not (org-region-active-p)) (org-at-item-p)
20221 (save-excursion (goto-char (region-beginning))
20222 (org-at-item-p)))
20223 (call-interactively 'org-outdent-item-tree))
20224 (t (org-modifier-cursor-error))))
20226 (defun org-shiftmetaright ()
20227 "Demote subtree or insert table column.
20228 Calls `org-demote-subtree', `org-indent-item-tree', or
20229 `org-table-insert-column', depending on context. See the
20230 individual commands for more information."
20231 (interactive)
20232 (cond
20233 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20234 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20235 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20236 ((if (not (org-region-active-p)) (org-at-item-p)
20237 (save-excursion (goto-char (region-beginning))
20238 (org-at-item-p)))
20239 (call-interactively 'org-indent-item-tree))
20240 (t (org-modifier-cursor-error))))
20242 (defun org-shiftmetaup (&optional _arg)
20243 "Drag the line at point up.
20244 In a table, kill the current row.
20245 On a clock timestamp, update the value of the timestamp like `S-<up>'
20246 but also adjust the previous clocked item in the clock history.
20247 Everywhere else, drag the line at point up."
20248 (interactive "P")
20249 (cond
20250 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20251 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20252 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20253 (call-interactively 'org-timestamp-up)))
20254 (t (call-interactively 'org-drag-line-backward))))
20256 (defun org-shiftmetadown (&optional _arg)
20257 "Drag the line at point down.
20258 In a table, insert an empty row at the current line.
20259 On a clock timestamp, update the value of the timestamp like `S-<down>'
20260 but also adjust the previous clocked item in the clock history.
20261 Everywhere else, drag the line at point down."
20262 (interactive "P")
20263 (cond
20264 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20265 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20266 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20267 (call-interactively 'org-timestamp-down)))
20268 (t (call-interactively 'org-drag-line-forward))))
20270 (defsubst org-hidden-tree-error ()
20271 (user-error
20272 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20274 (defun org-metaleft (&optional _arg)
20275 "Promote heading, list item at point or move table column left.
20277 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20278 depending on context. With no specific context, calls the Emacs
20279 default `backward-word'. See the individual commands for more
20280 information.
20282 This function runs the hook `org-metaleft-hook' as a first step,
20283 and returns at first non-nil value."
20284 (interactive "P")
20285 (cond
20286 ((run-hook-with-args-until-success 'org-metaleft-hook))
20287 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20288 ((org-with-limited-levels
20289 (or (org-at-heading-p)
20290 (and (org-region-active-p)
20291 (save-excursion
20292 (goto-char (region-beginning))
20293 (org-at-heading-p)))))
20294 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20295 (call-interactively 'org-do-promote))
20296 ;; At an inline task.
20297 ((org-at-heading-p)
20298 (call-interactively 'org-inlinetask-promote))
20299 ((or (org-at-item-p)
20300 (and (org-region-active-p)
20301 (save-excursion
20302 (goto-char (region-beginning))
20303 (org-at-item-p))))
20304 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20305 (call-interactively 'org-outdent-item))
20306 (t (call-interactively 'backward-word))))
20308 (defun org-metaright (&optional _arg)
20309 "Demote heading, list item at point or move table column right.
20311 In front of a drawer or a block keyword, indent it correctly.
20313 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20314 `org-indent-drawer' or `org-indent-block' depending on context.
20315 With no specific context, calls the Emacs default `forward-word'.
20316 See the individual commands for more information.
20318 This function runs the hook `org-metaright-hook' as a first step,
20319 and returns at first non-nil value."
20320 (interactive "P")
20321 (cond
20322 ((run-hook-with-args-until-success 'org-metaright-hook))
20323 ((org-at-table-p) (call-interactively 'org-table-move-column))
20324 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20325 ((org-at-block-p) (call-interactively 'org-indent-block))
20326 ((org-with-limited-levels
20327 (or (org-at-heading-p)
20328 (and (org-region-active-p)
20329 (save-excursion
20330 (goto-char (region-beginning))
20331 (org-at-heading-p)))))
20332 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20333 (call-interactively 'org-do-demote))
20334 ;; At an inline task.
20335 ((org-at-heading-p)
20336 (call-interactively 'org-inlinetask-demote))
20337 ((or (org-at-item-p)
20338 (and (org-region-active-p)
20339 (save-excursion
20340 (goto-char (region-beginning))
20341 (org-at-item-p))))
20342 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20343 (call-interactively 'org-indent-item))
20344 (t (call-interactively 'forward-word))))
20346 (defun org-check-for-hidden (what)
20347 "Check if there are hidden headlines/items in the current visual line.
20348 WHAT can be either `headlines' or `items'. If the current line is
20349 an outline or item heading and it has a folded subtree below it,
20350 this function returns t, nil otherwise."
20351 (let ((re (cond
20352 ((eq what 'headlines) org-outline-regexp-bol)
20353 ((eq what 'items) (org-item-beginning-re))
20354 (t (error "This should not happen"))))
20355 beg end)
20356 (save-excursion
20357 (catch 'exit
20358 (unless (org-region-active-p)
20359 (setq beg (point-at-bol))
20360 (beginning-of-line 2)
20361 (while (and (not (eobp)) ;; this is like `next-line'
20362 (get-char-property (1- (point)) 'invisible))
20363 (beginning-of-line 2))
20364 (setq end (point))
20365 (goto-char beg)
20366 (goto-char (point-at-eol))
20367 (setq end (max end (point)))
20368 (while (re-search-forward re end t)
20369 (when (get-char-property (match-beginning 0) 'invisible)
20370 (throw 'exit t))))
20371 nil))))
20373 (defun org-metaup (&optional _arg)
20374 "Move subtree up or move table row up.
20375 Calls `org-move-subtree-up' or `org-table-move-row' or
20376 `org-move-item-up', depending on context. See the individual commands
20377 for more information."
20378 (interactive "P")
20379 (cond
20380 ((run-hook-with-args-until-success 'org-metaup-hook))
20381 ((org-region-active-p)
20382 (let* ((a (min (region-beginning) (region-end)))
20383 (b (1- (max (region-beginning) (region-end))))
20384 (c (save-excursion (goto-char a)
20385 (move-beginning-of-line 0)))
20386 (d (save-excursion (goto-char a)
20387 (move-end-of-line 0) (point))))
20388 (transpose-regions a b c d)
20389 (goto-char c)))
20390 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20391 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20392 ((org-at-item-p) (call-interactively 'org-move-item-up))
20393 (t (org-drag-element-backward))))
20395 (defun org-metadown (&optional _arg)
20396 "Move subtree down or move table row down.
20397 Calls `org-move-subtree-down' or `org-table-move-row' or
20398 `org-move-item-down', depending on context. See the individual
20399 commands for more information."
20400 (interactive "P")
20401 (cond
20402 ((run-hook-with-args-until-success 'org-metadown-hook))
20403 ((org-region-active-p)
20404 (let* ((a (min (region-beginning) (region-end)))
20405 (b (max (region-beginning) (region-end)))
20406 (c (save-excursion (goto-char b)
20407 (move-beginning-of-line 1)))
20408 (d (save-excursion (goto-char b)
20409 (move-end-of-line 1) (1+ (point)))))
20410 (transpose-regions a b c d)
20411 (goto-char d)))
20412 ((org-at-table-p) (call-interactively 'org-table-move-row))
20413 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20414 ((org-at-item-p) (call-interactively 'org-move-item-down))
20415 (t (org-drag-element-forward))))
20417 (defun org-shiftup (&optional arg)
20418 "Increase item in timestamp or increase priority of current headline.
20419 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20420 depending on context. See the individual commands for more information."
20421 (interactive "P")
20422 (cond
20423 ((run-hook-with-args-until-success 'org-shiftup-hook))
20424 ((and org-support-shift-select (org-region-active-p))
20425 (org-call-for-shift-select 'previous-line))
20426 ((org-at-timestamp-p 'lax)
20427 (call-interactively (if org-edit-timestamp-down-means-later
20428 'org-timestamp-down 'org-timestamp-up)))
20429 ((and (not (eq org-support-shift-select 'always))
20430 org-enable-priority-commands
20431 (org-at-heading-p))
20432 (call-interactively 'org-priority-up))
20433 ((and (not org-support-shift-select) (org-at-item-p))
20434 (call-interactively 'org-previous-item))
20435 ((org-clocktable-try-shift 'up arg))
20436 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20437 (org-support-shift-select
20438 (org-call-for-shift-select 'previous-line))
20439 (t (org-shiftselect-error))))
20441 (defun org-shiftdown (&optional arg)
20442 "Decrease item in timestamp or decrease priority of current headline.
20443 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20444 depending on context. See the individual commands for more information."
20445 (interactive "P")
20446 (cond
20447 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20448 ((and org-support-shift-select (org-region-active-p))
20449 (org-call-for-shift-select 'next-line))
20450 ((org-at-timestamp-p 'lax)
20451 (call-interactively (if org-edit-timestamp-down-means-later
20452 'org-timestamp-up 'org-timestamp-down)))
20453 ((and (not (eq org-support-shift-select 'always))
20454 org-enable-priority-commands
20455 (org-at-heading-p))
20456 (call-interactively 'org-priority-down))
20457 ((and (not org-support-shift-select) (org-at-item-p))
20458 (call-interactively 'org-next-item))
20459 ((org-clocktable-try-shift 'down arg))
20460 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20461 (org-support-shift-select
20462 (org-call-for-shift-select 'next-line))
20463 (t (org-shiftselect-error))))
20465 (defun org-shiftright (&optional arg)
20466 "Cycle the thing at point or in the current line, depending on context.
20467 Depending on context, this does one of the following:
20469 - switch a timestamp at point one day into the future
20470 - on a headline, switch to the next TODO keyword.
20471 - on an item, switch entire list to the next bullet type
20472 - on a property line, switch to the next allowed value
20473 - on a clocktable definition line, move time block into the future"
20474 (interactive "P")
20475 (cond
20476 ((run-hook-with-args-until-success 'org-shiftright-hook))
20477 ((and org-support-shift-select (org-region-active-p))
20478 (org-call-for-shift-select 'forward-char))
20479 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20480 ((and (not (eq org-support-shift-select 'always))
20481 (org-at-heading-p))
20482 (let ((org-inhibit-logging
20483 (not org-treat-S-cursor-todo-selection-as-state-change))
20484 (org-inhibit-blocking
20485 (not org-treat-S-cursor-todo-selection-as-state-change)))
20486 (org-call-with-arg 'org-todo 'right)))
20487 ((or (and org-support-shift-select
20488 (not (eq org-support-shift-select 'always))
20489 (org-at-item-bullet-p))
20490 (and (not org-support-shift-select) (org-at-item-p)))
20491 (org-call-with-arg 'org-cycle-list-bullet nil))
20492 ((and (not (eq org-support-shift-select 'always))
20493 (org-at-property-p))
20494 (call-interactively 'org-property-next-allowed-value))
20495 ((org-clocktable-try-shift 'right arg))
20496 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20497 (org-support-shift-select
20498 (org-call-for-shift-select 'forward-char))
20499 (t (org-shiftselect-error))))
20501 (defun org-shiftleft (&optional arg)
20502 "Cycle the thing at point or in the current line, depending on context.
20503 Depending on context, this does one of the following:
20505 - switch a timestamp at point one day into the past
20506 - on a headline, switch to the previous TODO keyword.
20507 - on an item, switch entire list to the previous bullet type
20508 - on a property line, switch to the previous allowed value
20509 - on a clocktable definition line, move time block into the past"
20510 (interactive "P")
20511 (cond
20512 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20513 ((and org-support-shift-select (org-region-active-p))
20514 (org-call-for-shift-select 'backward-char))
20515 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20516 ((and (not (eq org-support-shift-select 'always))
20517 (org-at-heading-p))
20518 (let ((org-inhibit-logging
20519 (not org-treat-S-cursor-todo-selection-as-state-change))
20520 (org-inhibit-blocking
20521 (not org-treat-S-cursor-todo-selection-as-state-change)))
20522 (org-call-with-arg 'org-todo 'left)))
20523 ((or (and org-support-shift-select
20524 (not (eq org-support-shift-select 'always))
20525 (org-at-item-bullet-p))
20526 (and (not org-support-shift-select) (org-at-item-p)))
20527 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20528 ((and (not (eq org-support-shift-select 'always))
20529 (org-at-property-p))
20530 (call-interactively 'org-property-previous-allowed-value))
20531 ((org-clocktable-try-shift 'left arg))
20532 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20533 (org-support-shift-select
20534 (org-call-for-shift-select 'backward-char))
20535 (t (org-shiftselect-error))))
20537 (defun org-shiftcontrolright ()
20538 "Switch to next TODO set."
20539 (interactive)
20540 (cond
20541 ((and org-support-shift-select (org-region-active-p))
20542 (org-call-for-shift-select 'forward-word))
20543 ((and (not (eq org-support-shift-select 'always))
20544 (org-at-heading-p))
20545 (org-call-with-arg 'org-todo 'nextset))
20546 (org-support-shift-select
20547 (org-call-for-shift-select 'forward-word))
20548 (t (org-shiftselect-error))))
20550 (defun org-shiftcontrolleft ()
20551 "Switch to previous TODO set."
20552 (interactive)
20553 (cond
20554 ((and org-support-shift-select (org-region-active-p))
20555 (org-call-for-shift-select 'backward-word))
20556 ((and (not (eq org-support-shift-select 'always))
20557 (org-at-heading-p))
20558 (org-call-with-arg 'org-todo 'previousset))
20559 (org-support-shift-select
20560 (org-call-for-shift-select 'backward-word))
20561 (t (org-shiftselect-error))))
20563 (defun org-shiftcontrolup (&optional n)
20564 "Change timestamps synchronously up in CLOCK log lines.
20565 Optional argument N tells to change by that many units."
20566 (interactive "P")
20567 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20568 (let (org-support-shift-select)
20569 (org-clock-timestamps-up n))
20570 (user-error "Not at a clock log")))
20572 (defun org-shiftcontroldown (&optional n)
20573 "Change timestamps synchronously down in CLOCK log lines.
20574 Optional argument N tells to change by that many units."
20575 (interactive "P")
20576 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20577 (let (org-support-shift-select)
20578 (org-clock-timestamps-down n))
20579 (user-error "Not at a clock log")))
20581 (defun org-increase-number-at-point (&optional inc)
20582 "Increment the number at point.
20583 With an optional prefix numeric argument INC, increment using
20584 this numeric value."
20585 (interactive "p")
20586 (if (not (number-at-point))
20587 (user-error "Not on a number")
20588 (unless inc (setq inc 1))
20589 (let ((pos (point))
20590 (beg (skip-chars-backward "-+^/*0-9eE."))
20591 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20592 (setq nap (buffer-substring-no-properties
20593 (+ pos beg) (+ pos beg end)))
20594 (delete-region (+ pos beg) (+ pos beg end))
20595 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20596 (when (org-at-table-p)
20597 (org-table-align)
20598 (org-table-end-of-field 1))))
20600 (defun org-decrease-number-at-point (&optional inc)
20601 "Decrement the number at point.
20602 With an optional prefix numeric argument INC, decrement using
20603 this numeric value."
20604 (interactive "p")
20605 (org-increase-number-at-point (- (or inc 1))))
20607 (defun org-ctrl-c-ret ()
20608 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20609 (interactive)
20610 (cond
20611 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20612 (t (call-interactively 'org-insert-heading))))
20614 (defun org-find-visible ()
20615 (let ((s (point)))
20616 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20617 (get-char-property s 'invisible)))
20619 (defun org-find-invisible ()
20620 (let ((s (point)))
20621 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20622 (not (get-char-property s 'invisible))))
20625 (defun org-copy-visible (beg end)
20626 "Copy the visible parts of the region."
20627 (interactive "r")
20628 (let ((result ""))
20629 (while (/= beg end)
20630 (when (get-char-property beg 'invisible)
20631 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20632 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20633 (setq result (concat result (buffer-substring beg next)))
20634 (setq beg next)))
20635 (kill-new result)))
20637 (defun org-copy-special ()
20638 "Copy region in table or copy current subtree.
20639 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20640 context. See the individual commands for more information."
20641 (interactive)
20642 (call-interactively
20643 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20645 (defun org-cut-special ()
20646 "Cut region in table or cut current subtree.
20647 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20648 context. See the individual commands for more information."
20649 (interactive)
20650 (call-interactively
20651 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20653 (defun org-paste-special (arg)
20654 "Paste rectangular region into table, or past subtree relative to level.
20655 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20656 See the individual commands for more information."
20657 (interactive "P")
20658 (if (org-at-table-p)
20659 (org-table-paste-rectangle)
20660 (org-paste-subtree arg)))
20662 (defun org-edit-special (&optional arg)
20663 "Call a special editor for the element at point.
20664 When at a table, call the formula editor with `org-table-edit-formulas'.
20665 When in a source code block, call `org-edit-src-code'.
20666 When in a fixed-width region, call `org-edit-fixed-width-region'.
20667 When in an export block, call `org-edit-export-block'.
20668 When in a LaTeX environment, call `org-edit-latex-environment'.
20669 When at an #+INCLUDE keyword, visit the included file.
20670 When at a footnote reference, call `org-edit-footnote-reference'
20671 On a link, call `ffap' to visit the link at point.
20672 Otherwise, return a user error."
20673 (interactive "P")
20674 (let ((element (org-element-at-point)))
20675 (barf-if-buffer-read-only)
20676 (pcase (org-element-type element)
20677 (`src-block
20678 (if (not arg) (org-edit-src-code)
20679 (let* ((info (org-babel-get-src-block-info))
20680 (lang (nth 0 info))
20681 (params (nth 2 info))
20682 (session (cdr (assq :session params))))
20683 (if (not session) (org-edit-src-code)
20684 ;; At a src-block with a session and function called with
20685 ;; an ARG: switch to the buffer related to the inferior
20686 ;; process.
20687 (switch-to-buffer
20688 (funcall (intern (concat "org-babel-prep-session:" lang))
20689 session params))))))
20690 (`keyword
20691 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20692 (org-open-link-from-string
20693 (format "[[%s]]"
20694 (expand-file-name
20695 (let ((value (org-element-property :value element)))
20696 (cond ((org-file-url-p value)
20697 (user-error "The file is specified as a URL, cannot be edited"))
20698 ((not (org-string-nw-p value))
20699 (user-error "No file to edit"))
20700 ((string-match "\\`\"\\(.*?\\)\"" value)
20701 (match-string 1 value))
20702 ((string-match "\\`[^ \t\"]\\S-*" value)
20703 (match-string 0 value))
20704 (t (user-error "No valid file specified")))))))
20705 (user-error "No special environment to edit here")))
20706 (`table
20707 (if (eq (org-element-property :type element) 'table.el)
20708 (org-edit-table.el)
20709 (call-interactively 'org-table-edit-formulas)))
20710 ;; Only Org tables contain `table-row' type elements.
20711 (`table-row (call-interactively 'org-table-edit-formulas))
20712 (`example-block (org-edit-src-code))
20713 (`export-block (org-edit-export-block))
20714 (`fixed-width (org-edit-fixed-width-region))
20715 (`latex-environment (org-edit-latex-environment))
20717 ;; No notable element at point. Though, we may be at a link or
20718 ;; a footnote reference, which are objects. Thus, scan deeper.
20719 (let ((context (org-element-context element)))
20720 (pcase (org-element-type context)
20721 (`footnote-reference (org-edit-footnote-reference))
20722 (`inline-src-block (org-edit-inline-src-code))
20723 (`link (call-interactively #'ffap))
20724 (_ (user-error "No special environment to edit here"))))))))
20726 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20727 (defun org-ctrl-c-ctrl-c (&optional arg)
20728 "Set tags in headline, or update according to changed information at point.
20730 This command does many different things, depending on context:
20732 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20733 this is what we do.
20735 - If the cursor is on a statistics cookie, update it.
20737 - If the cursor is in a headline, prompt for tags and insert them
20738 into the current line, aligned to `org-tags-column'. When called
20739 with prefix arg, realign all tags in the current buffer.
20741 - If the cursor is in one of the special #+KEYWORD lines, this
20742 triggers scanning the buffer for these lines and updating the
20743 information.
20745 - If the cursor is inside a table, realign the table. This command
20746 works even if the automatic table editor has been turned off.
20748 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20749 the entire table.
20751 - If the cursor is at a footnote reference or definition, jump to
20752 the corresponding definition or references, respectively.
20754 - If the cursor is a the beginning of a dynamic block, update it.
20756 - If the current buffer is a capture buffer, close note and file it.
20758 - If the cursor is on a <<<target>>>, update radio targets and
20759 corresponding links in this buffer.
20761 - If the cursor is on a numbered item in a plain list, renumber the
20762 ordered list.
20764 - If the cursor is on a checkbox, toggle it.
20766 - If the cursor is on a code block, evaluate it. The variable
20767 `org-confirm-babel-evaluate' can be used to control prompting
20768 before code block evaluation, by default every code block
20769 evaluation requires confirmation. Code block evaluation can be
20770 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20771 (interactive "P")
20772 (cond
20773 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20774 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20775 (org-remove-occur-highlights)
20776 (message "Temporary highlights/overlays removed from current buffer"))
20777 ((and (local-variable-p 'org-finish-function)
20778 (fboundp org-finish-function))
20779 (funcall org-finish-function))
20780 ((org-babel-hash-at-point))
20781 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20783 (let* ((context
20784 (org-element-lineage
20785 (org-element-context)
20786 ;; Limit to supported contexts.
20787 '(babel-call clock dynamic-block footnote-definition
20788 footnote-reference inline-babel-call inline-src-block
20789 inlinetask item keyword node-property paragraph
20790 plain-list property-drawer radio-target src-block
20791 statistics-cookie table table-cell table-row
20792 timestamp)
20794 (type (org-element-type context)))
20795 ;; For convenience: at the first line of a paragraph on the same
20796 ;; line as an item, apply function on that item instead.
20797 (when (eq type 'paragraph)
20798 (let ((parent (org-element-property :parent context)))
20799 (when (and (eq (org-element-type parent) 'item)
20800 (= (line-beginning-position)
20801 (org-element-property :begin parent)))
20802 (setq context parent)
20803 (setq type 'item))))
20804 ;; Act according to type of element or object at point.
20806 ;; Do nothing on a blank line, except if it is contained in
20807 ;; a src block. Hence, we first check if point is in such
20808 ;; a block and then if it is at a blank line.
20809 (pcase type
20810 ((or `inline-src-block `src-block)
20811 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20812 (org-babel-eval-wipe-error-buffer)
20813 (org-babel-execute-src-block
20814 current-prefix-arg (org-babel-get-src-block-info nil context))))
20815 ((guard (org-match-line "[ \t]*$"))
20816 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20817 (user-error
20818 (substitute-command-keys
20819 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20820 ((or `babel-call `inline-babel-call)
20821 (let ((info (org-babel-lob-get-info context)))
20822 (when info (org-babel-execute-src-block nil info))))
20823 (`clock (org-clock-update-time-maybe))
20824 (`dynamic-block
20825 (save-excursion
20826 (goto-char (org-element-property :post-affiliated context))
20827 (org-update-dblock)))
20828 (`footnote-definition
20829 (goto-char (org-element-property :post-affiliated context))
20830 (call-interactively 'org-footnote-action))
20831 (`footnote-reference (call-interactively #'org-footnote-action))
20832 ((or `headline `inlinetask)
20833 (save-excursion (goto-char (org-element-property :begin context))
20834 (call-interactively #'org-set-tags)))
20835 (`item
20836 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20837 ;; unconditionally, whereas `C-u' will toggle its presence.
20838 ;; Without a universal argument, if the item has a checkbox,
20839 ;; toggle it. Otherwise repair the list.
20840 (let* ((box (org-element-property :checkbox context))
20841 (struct (org-element-property :structure context))
20842 (old-struct (copy-tree struct))
20843 (parents (org-list-parents-alist struct))
20844 (prevs (org-list-prevs-alist struct))
20845 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20846 (org-list-set-checkbox
20847 (org-element-property :begin context) struct
20848 (cond ((equal arg '(16)) "[-]")
20849 ((and (not box) (equal arg '(4))) "[ ]")
20850 ((or (not box) (equal arg '(4))) nil)
20851 ((eq box 'on) "[ ]")
20852 (t "[X]")))
20853 ;; Mimic `org-list-write-struct' but with grabbing a return
20854 ;; value from `org-list-struct-fix-box'.
20855 (org-list-struct-fix-ind struct parents 2)
20856 (org-list-struct-fix-item-end struct)
20857 (org-list-struct-fix-bul struct prevs)
20858 (org-list-struct-fix-ind struct parents)
20859 (let ((block-item
20860 (org-list-struct-fix-box struct parents prevs orderedp)))
20861 (if (and box (equal struct old-struct))
20862 (if (equal arg '(16))
20863 (message "Checkboxes already reset")
20864 (user-error "Cannot toggle this checkbox: %s"
20865 (if (eq box 'on)
20866 "all subitems checked"
20867 "unchecked subitems")))
20868 (org-list-struct-apply-struct struct old-struct)
20869 (org-update-checkbox-count-maybe))
20870 (when block-item
20871 (message "Checkboxes were removed due to empty box at line %d"
20872 (org-current-line block-item))))))
20873 (`keyword
20874 (let ((org-inhibit-startup-visibility-stuff t)
20875 (org-startup-align-all-tables nil))
20876 (when (boundp 'org-table-coordinate-overlays)
20877 (mapc #'delete-overlay org-table-coordinate-overlays)
20878 (setq org-table-coordinate-overlays nil))
20879 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20880 (message "Local setup has been refreshed"))
20881 (`plain-list
20882 ;; At a plain list, with a double C-u argument, set
20883 ;; checkboxes of each item to "[-]", whereas a single one
20884 ;; will toggle their presence according to the state of the
20885 ;; first item in the list. Without an argument, repair the
20886 ;; list.
20887 (let* ((begin (org-element-property :contents-begin context))
20888 (beginm (move-marker (make-marker) begin))
20889 (struct (org-element-property :structure context))
20890 (old-struct (copy-tree struct))
20891 (first-box (save-excursion
20892 (goto-char begin)
20893 (looking-at org-list-full-item-re)
20894 (match-string-no-properties 3)))
20895 (new-box (cond ((equal arg '(16)) "[-]")
20896 ((equal arg '(4)) (unless first-box "[ ]"))
20897 ((equal first-box "[X]") "[ ]")
20898 (t "[X]"))))
20899 (cond
20900 (arg
20901 (dolist (pos
20902 (org-list-get-all-items
20903 begin struct (org-list-prevs-alist struct)))
20904 (org-list-set-checkbox pos struct new-box)))
20905 ((and first-box (eq (point) begin))
20906 ;; For convenience, when point is at bol on the first
20907 ;; item of the list and no argument is provided, simply
20908 ;; toggle checkbox of that item, if any.
20909 (org-list-set-checkbox begin struct new-box)))
20910 (org-list-write-struct
20911 struct (org-list-parents-alist struct) old-struct)
20912 (org-update-checkbox-count-maybe)
20913 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20914 ((or `property-drawer `node-property)
20915 (call-interactively #'org-property-action))
20916 (`radio-target
20917 (call-interactively #'org-update-radio-target-regexp))
20918 (`statistics-cookie
20919 (call-interactively #'org-update-statistics-cookies))
20920 ((or `table `table-cell `table-row)
20921 ;; At a table, recalculate every field and align it. Also
20922 ;; send the table if necessary. If the table has
20923 ;; a `table.el' type, just give up. At a table row or cell,
20924 ;; maybe recalculate line but always align table.
20925 (if (eq (org-element-property :type context) 'table.el)
20926 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20927 Use `\\[org-edit-special]' to edit table.el tables"))
20928 (if (or (eq type 'table)
20929 ;; Check if point is at a TBLFM line.
20930 (and (eq type 'table-row)
20931 (= (point) (org-element-property :end context))))
20932 (save-excursion
20933 (if (org-at-TBLFM-p)
20934 (progn (require 'org-table)
20935 (org-table-calc-current-TBLFM))
20936 (goto-char (org-element-property :contents-begin context))
20937 (org-call-with-arg 'org-table-recalculate (or arg t))
20938 (orgtbl-send-table 'maybe)))
20939 (org-table-maybe-eval-formula)
20940 (cond (arg (call-interactively #'org-table-recalculate))
20941 ((org-table-maybe-recalculate-line))
20942 (t (org-table-align))))))
20943 (`timestamp (org-timestamp-change 0 'day))
20944 ((and `nil (guard (org-at-heading-p)))
20945 ;; When point is on an unsupported object type, we can miss
20946 ;; the fact that it also is at a heading. Handle it here.
20947 (call-interactively #'org-set-tags))
20948 ((guard
20949 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20951 (user-error
20952 (substitute-command-keys
20953 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20955 (defun org-mode-restart ()
20956 (interactive)
20957 (let ((indent-status (bound-and-true-p org-indent-mode)))
20958 (funcall major-mode)
20959 (hack-local-variables)
20960 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20961 (org-indent-mode -1))
20962 (org-reset-file-cache))
20963 (message "%s restarted" major-mode))
20965 (defun org-kill-note-or-show-branches ()
20966 "Abort storing current note, or call `outline-show-branches'."
20967 (interactive)
20968 (if (not org-finish-function)
20969 (progn
20970 (outline-hide-subtree)
20971 (call-interactively 'outline-show-branches))
20972 (let ((org-note-abort t))
20973 (funcall org-finish-function))))
20975 (defun org-delete-indentation (&optional arg)
20976 "Join current line to previous and fix whitespace at join.
20978 If previous line is a headline add to headline title. Otherwise
20979 the function calls `delete-indentation'.
20981 With a non-nil optional argument, join it to the following one."
20982 (interactive "*P")
20983 (if (save-excursion
20984 (beginning-of-line (if arg 1 0))
20985 (let ((case-fold-search nil))
20986 (looking-at org-complex-heading-regexp)))
20987 ;; At headline.
20988 (let ((tags-column (when (match-beginning 5)
20989 (save-excursion (goto-char (match-beginning 5))
20990 (current-column))))
20991 (string (concat " " (progn (when arg (forward-line 1))
20992 (org-trim (delete-and-extract-region
20993 (line-beginning-position)
20994 (line-end-position)))))))
20995 (unless (bobp) (delete-region (point) (1- (point))))
20996 (goto-char (or (match-end 4)
20997 (match-beginning 5)
20998 (match-end 0)))
20999 (skip-chars-backward " \t")
21000 (save-excursion (insert string))
21001 ;; Adjust alignment of tags.
21002 (cond
21003 ((not tags-column)) ;no tags
21004 (org-auto-align-tags (org-set-tags nil t))
21005 (t (org--align-tags-here tags-column)))) ;preserve tags column
21006 (delete-indentation arg)))
21008 (defun org-open-line (n)
21009 "Insert a new row in tables, call `open-line' elsewhere.
21010 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21011 As a special case, when a document starts with a table, allow to
21012 call `open-line' on the very first character."
21013 (interactive "*p")
21014 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21015 (org-table-insert-row)
21016 (open-line n)))
21018 (defun org-return (&optional indent)
21019 "Goto next table row or insert a newline.
21021 Calls `org-table-next-row' or `newline', depending on context.
21023 When optional INDENT argument is non-nil, call
21024 `newline-and-indent' instead of `newline'.
21026 When `org-return-follows-link' is non-nil and point is on
21027 a timestamp or a link, call `org-open-at-point'. However, it
21028 will not happen if point is in a table or on a \"dead\"
21029 object (e.g., within a comment). In these case, you need to use
21030 `org-open-at-point' directly."
21031 (interactive)
21032 (let ((context (if org-return-follows-link (org-element-context)
21033 (org-element-at-point))))
21034 (cond
21035 ;; In a table, call `org-table-next-row'.
21036 ((or (and (eq (org-element-type context) 'table)
21037 (>= (point) (org-element-property :contents-begin context))
21038 (< (point) (org-element-property :contents-end context)))
21039 (org-element-lineage context '(table-row table-cell) t))
21040 (org-table-justify-field-maybe)
21041 (call-interactively #'org-table-next-row))
21042 ;; On a link or a timestamp, call `org-open-at-point' if
21043 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21044 ;; locations, e.g., in a comment, as `org-open-at-point'.
21045 ((and org-return-follows-link
21046 (or (org-in-regexp org-ts-regexp-both nil t)
21047 (org-in-regexp org-tsr-regexp-both nil t)
21048 (org-in-regexp org-any-link-re nil t)))
21049 (call-interactively #'org-open-at-point))
21050 ;; Insert newline in heading, but preserve tags.
21051 ((and (not (bolp))
21052 (save-excursion (beginning-of-line)
21053 (let ((case-fold-search nil))
21054 (looking-at org-complex-heading-regexp))))
21055 ;; At headline. Split line. However, if point is on keyword,
21056 ;; priority cookie or tags, do not break any of them: add
21057 ;; a newline after the headline instead.
21058 (let ((tags-column (and (match-beginning 5)
21059 (save-excursion (goto-char (match-beginning 5))
21060 (current-column))))
21061 (string
21062 (when (and (match-end 4) (org-point-in-group (point) 4))
21063 (delete-and-extract-region (point) (match-end 4)))))
21064 ;; Adjust tag alignment.
21065 (cond
21066 ((not (and tags-column string)))
21067 (org-auto-align-tags (org-set-tags nil t))
21068 (t (org--align-tags-here tags-column))) ;preserve tags column
21069 (end-of-line)
21070 (org-show-entry)
21071 (if indent (newline-and-indent) (newline))
21072 (when string (save-excursion (insert (org-trim string))))))
21073 ;; In a list, make sure indenting keeps trailing text within.
21074 ((and indent
21075 (not (eolp))
21076 (org-element-lineage context '(item)))
21077 (let ((trailing-data
21078 (delete-and-extract-region (point) (line-end-position))))
21079 (newline-and-indent)
21080 (save-excursion (insert trailing-data))))
21081 (t (if indent (newline-and-indent) (newline))))))
21083 (defun org-return-indent ()
21084 "Goto next table row or insert a newline and indent.
21085 Calls `org-table-next-row' or `newline-and-indent', depending on
21086 context. See the individual commands for more information."
21087 (interactive)
21088 (org-return t))
21090 (defun org-ctrl-c-star ()
21091 "Compute table, or change heading status of lines.
21092 Calls `org-table-recalculate' or `org-toggle-heading',
21093 depending on context."
21094 (interactive)
21095 (cond
21096 ((org-at-table-p)
21097 (call-interactively 'org-table-recalculate))
21099 ;; Convert all lines in region to list items
21100 (call-interactively 'org-toggle-heading))))
21102 (defun org-ctrl-c-minus ()
21103 "Insert separator line in table or modify bullet status of line.
21104 Also turns a plain line or a region of lines into list items.
21105 Calls `org-table-insert-hline', `org-toggle-item', or
21106 `org-cycle-list-bullet', depending on context."
21107 (interactive)
21108 (cond
21109 ((org-at-table-p)
21110 (call-interactively 'org-table-insert-hline))
21111 ((org-region-active-p)
21112 (call-interactively 'org-toggle-item))
21113 ((org-in-item-p)
21114 (call-interactively 'org-cycle-list-bullet))
21116 (call-interactively 'org-toggle-item))))
21118 (defun org-toggle-heading (&optional nstars)
21119 "Convert headings to normal text, or items or text to headings.
21120 If there is no active region, only convert the current line.
21122 With a `\\[universal-argument]' prefix, convert the whole list at
21123 point into heading.
21125 In a region:
21127 - If the first non blank line is a headline, remove the stars
21128 from all headlines in the region.
21130 - If it is a normal line, turn each and every normal line (i.e.,
21131 not an heading or an item) in the region into headings. If you
21132 want to convert only the first line of this region, use one
21133 universal prefix argument.
21135 - If it is a plain list item, turn all plain list items into headings.
21137 When converting a line into a heading, the number of stars is chosen
21138 such that the lines become children of the current entry. However,
21139 when a numeric prefix argument is given, its value determines the
21140 number of stars to add."
21141 (interactive "P")
21142 (let ((skip-blanks
21143 (function
21144 ;; Return beginning of first non-blank line, starting from
21145 ;; line at POS.
21146 (lambda (pos)
21147 (save-excursion
21148 (goto-char pos)
21149 (while (org-at-comment-p) (forward-line))
21150 (skip-chars-forward " \r\t\n")
21151 (point-at-bol)))))
21152 beg end toggled)
21153 ;; Determine boundaries of changes. If a universal prefix has
21154 ;; been given, put the list in a region. If region ends at a bol,
21155 ;; do not consider the last line to be in the region.
21157 (when (and current-prefix-arg (org-at-item-p))
21158 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21159 (org-mark-element))
21161 (if (org-region-active-p)
21162 (setq beg (funcall skip-blanks (region-beginning))
21163 end (copy-marker (save-excursion
21164 (goto-char (region-end))
21165 (if (bolp) (point) (point-at-eol)))))
21166 (setq beg (funcall skip-blanks (point-at-bol))
21167 end (copy-marker (point-at-eol))))
21168 ;; Ensure inline tasks don't count as headings.
21169 (org-with-limited-levels
21170 (save-excursion
21171 (goto-char beg)
21172 (cond
21173 ;; Case 1. Started at an heading: de-star headings.
21174 ((org-at-heading-p)
21175 (while (< (point) end)
21176 (when (org-at-heading-p t)
21177 (looking-at org-outline-regexp) (replace-match "")
21178 (setq toggled t))
21179 (forward-line)))
21180 ;; Case 2. Started at an item: change items into headlines.
21181 ;; One star will be added by `org-list-to-subtree'.
21182 ((org-at-item-p)
21183 (while (< (point) end)
21184 (when (org-at-item-p)
21185 ;; Pay attention to cases when region ends before list.
21186 (let* ((struct (org-list-struct))
21187 (list-end
21188 (min (org-list-get-bottom-point struct) (1+ end))))
21189 (save-restriction
21190 (narrow-to-region (point) list-end)
21191 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21192 (setq toggled t))
21193 (forward-line)))
21194 ;; Case 3. Started at normal text: make every line an heading,
21195 ;; skipping headlines and items.
21196 (t (let* ((stars
21197 (make-string
21198 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21199 (add-stars
21200 (cond (nstars "") ; stars from prefix only
21201 ((equal stars "") "*") ; before first heading
21202 (org-odd-levels-only "**") ; inside heading, odd
21203 (t "*"))) ; inside heading, oddeven
21204 (rpl (concat stars add-stars " "))
21205 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21206 (while (< (point) (if (equal nstars '(4)) lend end))
21207 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21208 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21209 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21210 (forward-line)))))))
21211 (unless toggled (message "Cannot toggle heading from here"))))
21213 (defun org-meta-return (&optional arg)
21214 "Insert a new heading or wrap a region in a table.
21215 Calls `org-insert-heading', `org-insert-item' or
21216 `org-table-wrap-region', depending on context. When called with
21217 an argument, unconditionally call `org-insert-heading'."
21218 (interactive "P")
21219 (org-check-before-invisible-edit 'insert)
21220 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21221 (call-interactively (cond (arg #'org-insert-heading)
21222 ((org-at-table-p) #'org-table-wrap-region)
21223 ((org-in-item-p) #'org-insert-item)
21224 (t #'org-insert-heading)))))
21226 ;;; Menu entries
21228 (defsubst org-in-subtree-not-table-p ()
21229 "Are we in a subtree and not in a table?"
21230 (and (not (org-before-first-heading-p))
21231 (not (org-at-table-p))))
21233 ;; Define the Org mode menus
21234 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21235 '("Tbl"
21236 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21237 ["Next Field" org-cycle (org-at-table-p)]
21238 ["Previous Field" org-shifttab (org-at-table-p)]
21239 ["Next Row" org-return (org-at-table-p)]
21240 "--"
21241 ["Blank Field" org-table-blank-field (org-at-table-p)]
21242 ["Edit Field" org-table-edit-field (org-at-table-p)]
21243 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21244 "--"
21245 ("Column"
21246 ["Move Column Left" org-metaleft (org-at-table-p)]
21247 ["Move Column Right" org-metaright (org-at-table-p)]
21248 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21249 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21250 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
21251 ("Row"
21252 ["Move Row Up" org-metaup (org-at-table-p)]
21253 ["Move Row Down" org-metadown (org-at-table-p)]
21254 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21255 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21256 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21257 "--"
21258 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21259 ("Rectangle"
21260 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21261 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21262 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21263 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21264 "--"
21265 ("Calculate"
21266 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21267 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21268 ["Edit Formulas" org-edit-special (org-at-table-p)]
21269 "--"
21270 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21271 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21272 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21273 "--"
21274 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21275 "--"
21276 ["Sum Column/Rectangle" org-table-sum
21277 (or (org-at-table-p) (org-region-active-p))]
21278 ["Which Column?" org-table-current-column (org-at-table-p)])
21279 ["Debug Formulas"
21280 org-table-toggle-formula-debugger
21281 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21282 ["Show Col/Row Numbers"
21283 org-table-toggle-coordinate-overlays
21284 :style toggle
21285 :selected (bound-and-true-p org-table-overlay-coordinates)]
21286 "--"
21287 ["Create" org-table-create (not (org-at-table-p))]
21288 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21289 ["Import from File" org-table-import (not (org-at-table-p))]
21290 ["Export to File" org-table-export (org-at-table-p)]
21291 "--"
21292 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21293 "--"
21294 ("Plot"
21295 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21296 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21298 (easy-menu-define org-org-menu org-mode-map "Org menu"
21299 '("Org"
21300 ("Show/Hide"
21301 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21302 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21303 ["Sparse Tree..." org-sparse-tree t]
21304 ["Reveal Context" org-reveal t]
21305 ["Show All" outline-show-all t]
21306 "--"
21307 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21308 "--"
21309 ["New Heading" org-insert-heading t]
21310 ("Navigate Headings"
21311 ["Up" outline-up-heading t]
21312 ["Next" outline-next-visible-heading t]
21313 ["Previous" outline-previous-visible-heading t]
21314 ["Next Same Level" outline-forward-same-level t]
21315 ["Previous Same Level" outline-backward-same-level t]
21316 "--"
21317 ["Jump" org-goto t])
21318 ("Edit Structure"
21319 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21320 "--"
21321 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21322 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21323 "--"
21324 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21325 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21326 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21327 "--"
21328 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21329 "--"
21330 ["Copy visible text" org-copy-visible t]
21331 "--"
21332 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21333 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21334 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21335 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21336 "--"
21337 ["Sort Region/Children" org-sort t]
21338 "--"
21339 ["Convert to odd levels" org-convert-to-odd-levels t]
21340 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21341 ("Editing"
21342 ["Emphasis..." org-emphasize t]
21343 ["Edit Source Example" org-edit-special t]
21344 "--"
21345 ["Footnote new/jump" org-footnote-action t]
21346 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21347 ("Archive"
21348 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21349 "--"
21350 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21351 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21352 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21354 "--"
21355 ("Hyperlinks"
21356 ["Store Link (Global)" org-store-link t]
21357 ["Find existing link to here" org-occur-link-in-agenda-files t]
21358 ["Insert Link" org-insert-link t]
21359 ["Follow Link" org-open-at-point t]
21360 "--"
21361 ["Next link" org-next-link t]
21362 ["Previous link" org-previous-link t]
21363 "--"
21364 ["Descriptive Links"
21365 org-toggle-link-display
21366 :style radio
21367 :selected org-descriptive-links
21369 ["Literal Links"
21370 org-toggle-link-display
21371 :style radio
21372 :selected (not org-descriptive-links)])
21373 "--"
21374 ("TODO Lists"
21375 ["TODO/DONE/-" org-todo t]
21376 ("Select keyword"
21377 ["Next keyword" org-shiftright (org-at-heading-p)]
21378 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21379 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21380 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21381 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21382 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21383 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21384 "--"
21385 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21386 :selected org-enforce-todo-dependencies :style toggle :active t]
21387 "Settings for tree at point"
21388 ["Do Children sequentially" org-toggle-ordered-property :style radio
21389 :selected (org-entry-get nil "ORDERED")
21390 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21391 ["Do Children parallel" org-toggle-ordered-property :style radio
21392 :selected (not (org-entry-get nil "ORDERED"))
21393 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21394 "--"
21395 ["Set Priority" org-priority t]
21396 ["Priority Up" org-shiftup t]
21397 ["Priority Down" org-shiftdown t]
21398 "--"
21399 ["Get news from all feeds" org-feed-update-all t]
21400 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21401 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21402 ("TAGS and Properties"
21403 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21404 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21405 "--"
21406 ["Set property" org-set-property (not (org-before-first-heading-p))]
21407 ["Column view of properties" org-columns t]
21408 ["Insert Column View DBlock" org-columns-insert-dblock t])
21409 ("Dates and Scheduling"
21410 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21411 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21412 ("Change Date"
21413 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21414 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21415 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21416 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21417 ["Compute Time Range" org-evaluate-time-range t]
21418 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21419 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21420 "--"
21421 ["Custom time format" org-toggle-time-stamp-overlays
21422 :style radio :selected org-display-custom-times]
21423 "--"
21424 ["Goto Calendar" org-goto-calendar t]
21425 ["Date from Calendar" org-date-from-calendar t]
21426 "--"
21427 ["Start/Restart Timer" org-timer-start t]
21428 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21429 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21430 ["Insert Timer String" org-timer t]
21431 ["Insert Timer Item" org-timer-item t])
21432 ("Logging work"
21433 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21434 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21435 ["Clock out" org-clock-out t]
21436 ["Clock cancel" org-clock-cancel t]
21437 "--"
21438 ["Mark as default task" org-clock-mark-default-task t]
21439 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21440 ["Goto running clock" org-clock-goto t]
21441 "--"
21442 ["Display times" org-clock-display t]
21443 ["Create clock table" org-clock-report t]
21444 "--"
21445 ["Record DONE time"
21446 (progn (setq org-log-done (not org-log-done))
21447 (message "Switching to %s will %s record a timestamp"
21448 (car org-done-keywords)
21449 (if org-log-done "automatically" "not")))
21450 :style toggle :selected org-log-done])
21451 "--"
21452 ["Agenda Command..." org-agenda t]
21453 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21454 ("File List for Agenda")
21455 ("Special views current file"
21456 ["TODO Tree" org-show-todo-tree t]
21457 ["Check Deadlines" org-check-deadlines t]
21458 ["Tags/Property tree" org-match-sparse-tree t])
21459 "--"
21460 ["Export/Publish..." org-export-dispatch t]
21461 ("LaTeX"
21462 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21463 :selected org-cdlatex-mode]
21464 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21465 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21466 ["Modify math symbol" org-cdlatex-math-modify
21467 (org-inside-LaTeX-fragment-p)]
21468 ["Insert citation" org-reftex-citation t])
21469 "--"
21470 ("MobileOrg"
21471 ["Push Files and Views" org-mobile-push t]
21472 ["Get Captured and Flagged" org-mobile-pull t]
21473 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21474 "--"
21475 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21476 "--"
21477 ("Documentation"
21478 ["Show Version" org-version t]
21479 ["Info Documentation" org-info t])
21480 ("Customize"
21481 ["Browse Org Group" org-customize t]
21482 "--"
21483 ["Expand This Menu" org-create-customize-menu
21484 (fboundp 'customize-menu-create)])
21485 ["Send bug report" org-submit-bug-report t]
21486 "--"
21487 ("Refresh/Reload"
21488 ["Refresh setup current buffer" org-mode-restart t]
21489 ["Reload Org (after update)" org-reload t]
21490 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21493 (defun org-info (&optional node)
21494 "Read documentation for Org in the info system.
21495 With optional NODE, go directly to that node."
21496 (interactive)
21497 (info (format "(org)%s" (or node ""))))
21499 ;;;###autoload
21500 (defun org-submit-bug-report ()
21501 "Submit a bug report on Org via mail.
21503 Don't hesitate to report any problems or inaccurate documentation.
21505 If you don't have setup sending mail from (X)Emacs, please copy the
21506 output buffer into your mail program, as it gives us important
21507 information about your Org version and configuration."
21508 (interactive)
21509 (require 'reporter)
21510 (defvar reporter-prompt-for-summary-p)
21511 (org-load-modules-maybe)
21512 (org-require-autoloaded-modules)
21513 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21514 (reporter-submit-bug-report
21515 "emacs-orgmode@gnu.org"
21516 (org-version nil 'full)
21517 (let (list)
21518 (save-window-excursion
21519 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21520 (delete-other-windows)
21521 (erase-buffer)
21522 (insert "You are about to submit a bug report to the Org mailing list.
21524 We would like to add your full Org and Outline configuration to the
21525 bug report. This greatly simplifies the work of the maintainer and
21526 other experts on the mailing list.
21528 HOWEVER, some variables you have customized may contain private
21529 information. The names of customers, colleagues, or friends, might
21530 appear in the form of file names, tags, todo states, or search strings.
21531 If you answer yes to the prompt, you might want to check and remove
21532 such private information before sending the email.")
21533 (add-text-properties (point-min) (point-max) '(face org-warning))
21534 (when (yes-or-no-p "Include your Org configuration ")
21535 (mapatoms
21536 (lambda (v)
21537 (and (boundp v)
21538 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21539 (or (and (symbol-value v)
21540 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21541 (and
21542 (get v 'custom-type) (get v 'standard-value)
21543 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21544 (push v list)))))
21545 (kill-buffer (get-buffer "*Warn about privacy*"))
21546 list))
21547 nil nil
21548 "Remember to cover the basics, that is, what you expected to happen and
21549 what in fact did happen. You don't know how to make a good report? See
21551 http://orgmode.org/manual/Feedback.html#Feedback
21553 Your bug report will be posted to the Org mailing list.
21554 ------------------------------------------------------------------------")
21555 (save-excursion
21556 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21557 (replace-match "\\1Bug: \\3 [\\2]")))))
21560 (defun org-install-agenda-files-menu ()
21561 (let ((bl (buffer-list)))
21562 (save-excursion
21563 (while bl
21564 (set-buffer (pop bl))
21565 (when (derived-mode-p 'org-mode) (setq bl nil)))
21566 (when (derived-mode-p 'org-mode)
21567 (easy-menu-change
21568 '("Org") "File List for Agenda"
21569 (append
21570 (list
21571 ["Edit File List" (org-edit-agenda-file-list) t]
21572 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21573 ["Remove Current File from List" org-remove-file t]
21574 ["Cycle through agenda files" org-cycle-agenda-files t]
21575 ["Occur in all agenda files" org-occur-in-agenda-files t]
21576 "--")
21577 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21579 ;;;; Documentation
21581 (defun org-require-autoloaded-modules ()
21582 (interactive)
21583 (mapc #'require
21584 '(org-agenda org-archive org-attach org-clock org-colview org-id
21585 org-table org-timer)))
21587 ;;;###autoload
21588 (defun org-reload (&optional uncompiled)
21589 "Reload all org lisp files.
21590 With prefix arg UNCOMPILED, load the uncompiled versions."
21591 (interactive "P")
21592 (require 'loadhist)
21593 (let* ((org-dir (org-find-library-dir "org"))
21594 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21595 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21596 (remove-re (format "\\`%s\\'"
21597 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21598 (feats (delete-dups
21599 (mapcar 'file-name-sans-extension
21600 (mapcar 'file-name-nondirectory
21601 (delq nil
21602 (mapcar 'feature-file
21603 features))))))
21604 (lfeat (append
21605 (sort
21606 (setq feats
21607 (delq nil (mapcar
21608 (lambda (f)
21609 (if (and (string-match feature-re f)
21610 (not (string-match remove-re f)))
21611 f nil))
21612 feats)))
21613 'string-lessp)
21614 (list "org-version" "org")))
21615 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21616 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21617 load-uncore load-misses)
21618 (setq load-misses
21619 (delq 't
21620 (mapcar (lambda (f)
21621 (or (org-load-noerror-mustsuffix (concat org-dir f))
21622 (and (string= org-dir contrib-dir)
21623 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21624 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21625 (add-to-list 'load-uncore f 'append)
21628 lfeat)))
21629 (when load-uncore
21630 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21631 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21632 (if load-misses
21633 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21634 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21635 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21637 ;;;###autoload
21638 (defun org-customize ()
21639 "Call the customize function with org as argument."
21640 (interactive)
21641 (org-load-modules-maybe)
21642 (org-require-autoloaded-modules)
21643 (customize-browse 'org))
21645 (defun org-create-customize-menu ()
21646 "Create a full customization menu for Org mode, insert it into the menu."
21647 (interactive)
21648 (org-load-modules-maybe)
21649 (org-require-autoloaded-modules)
21650 (if (fboundp 'customize-menu-create)
21651 (progn
21652 (easy-menu-change
21653 '("Org") "Customize"
21654 `(["Browse Org group" org-customize t]
21655 "--"
21656 ,(customize-menu-create 'org)
21657 ["Set" Custom-set t]
21658 ["Save" Custom-save t]
21659 ["Reset to Current" Custom-reset-current t]
21660 ["Reset to Saved" Custom-reset-saved t]
21661 ["Reset to Standard Settings" Custom-reset-standard t]))
21662 (message "\"Org\"-menu now contains full customization menu"))
21663 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21665 ;;;; Miscellaneous stuff
21667 ;;; Generally useful functions
21669 (defun org-get-at-eol (property n)
21670 "Get text property PROPERTY at the end of line less N characters."
21671 (get-text-property (- (point-at-eol) n) property))
21673 (defun org-find-text-property-in-string (prop s)
21674 "Return the first non-nil value of property PROP in string S."
21675 (or (get-text-property 0 prop s)
21676 (get-text-property (or (next-single-property-change 0 prop s) 0)
21677 prop s)))
21679 (defun org-display-warning (message)
21680 "Display the given MESSAGE as a warning."
21681 (display-warning 'org message :warning))
21683 (defun org-eval (form)
21684 "Eval FORM and return result."
21685 (condition-case error
21686 (eval form)
21687 (error (format "%%![Error: %s]" error))))
21689 (defun org-in-clocktable-p ()
21690 "Check if the cursor is in a clocktable."
21691 (let ((pos (point)) start)
21692 (save-excursion
21693 (end-of-line 1)
21694 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21695 (setq start (match-beginning 0))
21696 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21697 (>= (match-end 0) pos)
21698 start))))
21700 (defun org-in-verbatim-emphasis ()
21701 (save-match-data
21702 (and (org-in-regexp org-verbatim-re 2)
21703 (>= (point) (match-beginning 3))
21704 (<= (point) (match-end 4)))))
21706 (defun org-overlay-display (ovl text &optional face evap)
21707 "Make overlay OVL display TEXT with face FACE."
21708 (overlay-put ovl 'display text)
21709 (if face (overlay-put ovl 'face face))
21710 (if evap (overlay-put ovl 'evaporate t)))
21712 (defun org-overlay-before-string (ovl text &optional face evap)
21713 "Make overlay OVL display TEXT with face FACE."
21714 (if face (org-add-props text nil 'face face))
21715 (overlay-put ovl 'before-string text)
21716 (if evap (overlay-put ovl 'evaporate t)))
21718 (defun org-find-overlays (prop &optional pos delete)
21719 "Find all overlays specifying PROP at POS or point.
21720 If DELETE is non-nil, delete all those overlays."
21721 (let (found)
21722 (dolist (ov (overlays-at (or pos (point))) found)
21723 (cond ((not (overlay-get ov prop)))
21724 (delete (delete-overlay ov))
21725 (t (push ov found))))))
21727 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21728 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21729 (if (and marker (marker-buffer marker)
21730 (buffer-live-p (marker-buffer marker)))
21731 (progn
21732 (pop-to-buffer-same-window (marker-buffer marker))
21733 (when (or (> marker (point-max)) (< marker (point-min)))
21734 (widen))
21735 (goto-char marker)
21736 (org-show-context 'org-goto))
21737 (if bookmark
21738 (bookmark-jump bookmark)
21739 (error "Cannot find location"))))
21741 (defun org-quote-csv-field (s)
21742 "Quote field for inclusion in CSV material."
21743 (if (string-match "[\",]" s)
21744 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21747 (defun org-force-self-insert (N)
21748 "Needed to enforce self-insert under remapping."
21749 (interactive "p")
21750 (self-insert-command N))
21752 (defun org-shorten-string (s maxlength)
21753 "Shorten string S so that it is no longer than MAXLENGTH characters.
21754 If the string is shorter or has length MAXLENGTH, just return the
21755 original string. If it is longer, the functions finds a space in the
21756 string, breaks this string off at that locations and adds three dots
21757 as ellipsis. Including the ellipsis, the string will not be longer
21758 than MAXLENGTH. If finding a good breaking point in the string does
21759 not work, the string is just chopped off in the middle of a word
21760 if necessary."
21761 (if (<= (length s) maxlength)
21763 (let* ((n (max (- maxlength 4) 1))
21764 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21765 (if (string-match re s)
21766 (concat (match-string 1 s) "...")
21767 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21769 (defun org-get-indentation (&optional line)
21770 "Get the indentation of the current line, interpreting tabs.
21771 When LINE is given, assume it represents a line and compute its indentation."
21772 (if line
21773 (when (string-match "^ *" (org-remove-tabs line))
21774 (match-end 0))
21775 (save-excursion
21776 (beginning-of-line 1)
21777 (skip-chars-forward " \t")
21778 (current-column))))
21780 (defun org-get-string-indentation (s)
21781 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21782 (let ((n -1) (i 0) (w tab-width) c)
21783 (catch 'exit
21784 (while (< (setq n (1+ n)) (length s))
21785 (setq c (aref s n))
21786 (cond ((= c ?\ ) (setq i (1+ i)))
21787 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21788 (t (throw 'exit t)))))
21791 (defun org-remove-tabs (s &optional width)
21792 "Replace tabulators in S with spaces.
21793 Assumes that s is a single line, starting in column 0."
21794 (setq width (or width tab-width))
21795 (while (string-match "\t" s)
21796 (setq s (replace-match
21797 (make-string
21798 (- (* width (/ (+ (match-beginning 0) width) width))
21799 (match-beginning 0)) ?\ )
21800 t t s)))
21803 (defun org-fix-indentation (line ind)
21804 "Fix indentation in LINE.
21805 IND is a cons cell with target and minimum indentation.
21806 If the current indentation in LINE is smaller than the minimum,
21807 leave it alone. If it is larger than ind, set it to the target."
21808 (let* ((l (org-remove-tabs line))
21809 (i (org-get-indentation l))
21810 (i1 (car ind)) (i2 (cdr ind)))
21811 (when (>= i i2) (setq l (substring line i2)))
21812 (if (> i1 0)
21813 (concat (make-string i1 ?\ ) l)
21814 l)))
21816 (defun org-remove-indentation (code &optional n)
21817 "Remove maximum common indentation in string CODE and return it.
21818 N may optionally be the number of columns to remove. Return CODE
21819 as-is if removal failed."
21820 (with-temp-buffer
21821 (insert code)
21822 (if (org-do-remove-indentation n) (buffer-string) code)))
21824 (defun org-do-remove-indentation (&optional n)
21825 "Remove the maximum common indentation from the buffer.
21826 When optional argument N is a positive integer, remove exactly
21827 that much characters from indentation, if possible. Return nil
21828 if it fails."
21829 (catch :exit
21830 (goto-char (point-min))
21831 ;; Find maximum common indentation, if not specified.
21832 (let ((n (or n
21833 (let ((min-ind (point-max)))
21834 (save-excursion
21835 (while (re-search-forward "^[ \t]*\\S-" nil t)
21836 (let ((ind (1- (current-column))))
21837 (if (zerop ind) (throw :exit nil)
21838 (setq min-ind (min min-ind ind))))))
21839 min-ind))))
21840 (if (zerop n) (throw :exit nil)
21841 ;; Remove exactly N indentation, but give up if not possible.
21842 (while (not (eobp))
21843 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21844 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21845 ((< ind n) (throw :exit nil))
21846 (t (indent-line-to (- ind n))))
21847 (forward-line)))
21848 ;; Signal success.
21849 t))))
21851 (defun org-fill-template (template alist)
21852 "Find each %key of ALIST in TEMPLATE and replace it."
21853 (let ((case-fold-search nil))
21854 (dolist (entry (sort (copy-sequence alist)
21855 (lambda (a b) (< (length (car a)) (length (car b))))))
21856 (setq template
21857 (replace-regexp-in-string
21858 (concat "%" (regexp-quote (car entry)))
21859 (or (cdr entry) "") template t t)))
21860 template))
21862 (defun org-base-buffer (buffer)
21863 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21864 (if (not buffer)
21865 buffer
21866 (or (buffer-base-buffer buffer)
21867 buffer)))
21869 (defun org-wrap (string &optional width lines)
21870 "Wrap string to either a number of lines, or a width in characters.
21871 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21872 that costs. If there is a word longer than WIDTH, the text is actually
21873 wrapped to the length of that word.
21874 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21875 many lines, whatever width that takes.
21876 The return value is a list of lines, without newlines at the end."
21877 (let* ((words (split-string string))
21878 (maxword (apply 'max (mapcar 'org-string-width words)))
21879 w ll)
21880 (cond (width
21881 (org-do-wrap words (max maxword width)))
21882 (lines
21883 (setq w maxword)
21884 (setq ll (org-do-wrap words maxword))
21885 (if (<= (length ll) lines)
21887 (setq ll words)
21888 (while (> (length ll) lines)
21889 (setq w (1+ w))
21890 (setq ll (org-do-wrap words w)))
21891 ll))
21892 (t (error "Cannot wrap this")))))
21894 (defun org-do-wrap (words width)
21895 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21896 (let (lines line)
21897 (while words
21898 (setq line (pop words))
21899 (while (and words (< (+ (length line) (length (car words))) width))
21900 (setq line (concat line " " (pop words))))
21901 (setq lines (push line lines)))
21902 (nreverse lines)))
21904 (defun org-quote-vert (s)
21905 "Replace \"|\" with \"\\vert\"."
21906 (while (string-match "|" s)
21907 (setq s (replace-match "\\vert" t t s)))
21910 (defun org-uuidgen-p (s)
21911 "Is S an ID created by UUIDGEN?"
21912 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21914 (defun org-in-src-block-p (&optional inside)
21915 "Whether point is in a code source block.
21916 When INSIDE is non-nil, don't consider we are within a src block
21917 when point is at #+BEGIN_SRC or #+END_SRC."
21918 (let ((case-fold-search t))
21919 (or (and (eq (get-char-property (point) 'src-block) t))
21920 (and (not inside)
21921 (save-match-data
21922 (save-excursion
21923 (beginning-of-line)
21924 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21926 (defun org-context ()
21927 "Return a list of contexts of the current cursor position.
21928 If several contexts apply, all are returned.
21929 Each context entry is a list with a symbol naming the context, and
21930 two positions indicating start and end of the context. Possible
21931 contexts are:
21933 :headline anywhere in a headline
21934 :headline-stars on the leading stars in a headline
21935 :todo-keyword on a TODO keyword (including DONE) in a headline
21936 :tags on the TAGS in a headline
21937 :priority on the priority cookie in a headline
21938 :item on the first line of a plain list item
21939 :item-bullet on the bullet/number of a plain list item
21940 :checkbox on the checkbox in a plain list item
21941 :table in an Org table
21942 :table-special on a special filed in a table
21943 :table-table in a table.el table
21944 :clocktable in a clocktable
21945 :src-block in a source block
21946 :link on a hyperlink
21947 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21948 :target on a <<target>>
21949 :radio-target on a <<<radio-target>>>
21950 :latex-fragment on a LaTeX fragment
21951 :latex-preview on a LaTeX fragment with overlaid preview image
21953 This function expects the position to be visible because it uses font-lock
21954 faces as a help to recognize the following contexts: :table-special, :link,
21955 and :keyword."
21956 (let* ((f (get-text-property (point) 'face))
21957 (faces (if (listp f) f (list f)))
21958 (case-fold-search t)
21959 (p (point)) clist o)
21960 ;; First the large context
21961 (cond
21962 ((org-at-heading-p t)
21963 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21964 (when (progn
21965 (beginning-of-line 1)
21966 (looking-at org-todo-line-tags-regexp))
21967 (push (org-point-in-group p 1 :headline-stars) clist)
21968 (push (org-point-in-group p 2 :todo-keyword) clist)
21969 (push (org-point-in-group p 4 :tags) clist))
21970 (goto-char p)
21971 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21972 (when (looking-at "\\[#[A-Z0-9]\\]")
21973 (push (org-point-in-group p 0 :priority) clist)))
21975 ((org-at-item-p)
21976 (push (org-point-in-group p 2 :item-bullet) clist)
21977 (push (list :item (point-at-bol)
21978 (save-excursion (org-end-of-item) (point)))
21979 clist)
21980 (and (org-at-item-checkbox-p)
21981 (push (org-point-in-group p 0 :checkbox) clist)))
21983 ((org-at-table-p)
21984 (push (list :table (org-table-begin) (org-table-end)) clist)
21985 (when (memq 'org-formula faces)
21986 (push (list :table-special
21987 (previous-single-property-change p 'face)
21988 (next-single-property-change p 'face)) clist)))
21989 ((org-at-table-p 'any)
21990 (push (list :table-table) clist)))
21991 (goto-char p)
21993 (let ((case-fold-search t))
21994 ;; New the "medium" contexts: clocktables, source blocks
21995 (cond ((org-in-clocktable-p)
21996 (push (list :clocktable
21997 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21998 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21999 (match-beginning 1))
22000 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22001 (match-end 0))) clist))
22002 ((org-in-src-block-p)
22003 (push (list :src-block
22004 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22005 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22006 (match-beginning 1))
22007 (and (search-forward "#+END_SRC" nil t)
22008 (match-beginning 0))) clist))))
22009 (goto-char p)
22011 ;; Now the small context
22012 (cond
22013 ((org-at-timestamp-p)
22014 (push (org-point-in-group p 0 :timestamp) clist))
22015 ((memq 'org-link faces)
22016 (push (list :link
22017 (previous-single-property-change p 'face)
22018 (next-single-property-change p 'face)) clist))
22019 ((memq 'org-special-keyword faces)
22020 (push (list :keyword
22021 (previous-single-property-change p 'face)
22022 (next-single-property-change p 'face)) clist))
22023 ((org-at-target-p)
22024 (push (org-point-in-group p 0 :target) clist)
22025 (goto-char (1- (match-beginning 0)))
22026 (when (looking-at org-radio-target-regexp)
22027 (push (org-point-in-group p 0 :radio-target) clist))
22028 (goto-char p))
22029 ((setq o (cl-some
22030 (lambda (o)
22031 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22033 (overlays-at (point))))
22034 (push (list :latex-fragment
22035 (overlay-start o) (overlay-end o)) clist)
22036 (push (list :latex-preview
22037 (overlay-start o) (overlay-end o)) clist))
22038 ((org-inside-LaTeX-fragment-p)
22039 ;; FIXME: positions wrong.
22040 (push (list :latex-fragment (point) (point)) clist)))
22042 (setq clist (nreverse (delq nil clist)))
22043 clist))
22045 (defun org-in-regexp (regexp &optional nlines visually)
22046 "Check if point is inside a match of REGEXP.
22048 Normally only the current line is checked, but you can include
22049 NLINES extra lines around point into the search. If VISUALLY is
22050 set, require that the cursor is not after the match but really
22051 on, so that the block visually is on the match.
22053 Return nil or a cons cell (BEG . END) where BEG and END are,
22054 respectively, the positions at the beginning and the end of the
22055 match."
22056 (catch :exit
22057 (let ((pos (point))
22058 (eol (line-end-position (if nlines (1+ nlines) 1))))
22059 (save-excursion
22060 (beginning-of-line (- 1 (or nlines 0)))
22061 (while (and (re-search-forward regexp eol t)
22062 (<= (match-beginning 0) pos))
22063 (let ((end (match-end 0)))
22064 (when (or (> end pos) (and (= end pos) (not visually)))
22065 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22067 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22068 "Non-nil when point is between matches of START-RE and END-RE.
22070 Also return a non-nil value when point is on one of the matches.
22072 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22073 buffer positions. Default values are the positions of headlines
22074 surrounding the point.
22076 The functions returns a cons cell whose car (resp. cdr) is the
22077 position before START-RE (resp. after END-RE)."
22078 (save-match-data
22079 (let ((pos (point))
22080 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22081 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22082 beg end)
22083 (save-excursion
22084 ;; Point is on a block when on START-RE or if START-RE can be
22085 ;; found before it...
22086 (and (or (org-in-regexp start-re)
22087 (re-search-backward start-re limit-up t))
22088 (setq beg (match-beginning 0))
22089 ;; ... and END-RE after it...
22090 (goto-char (match-end 0))
22091 (re-search-forward end-re limit-down t)
22092 (> (setq end (match-end 0)) pos)
22093 ;; ... without another START-RE in-between.
22094 (goto-char (match-beginning 0))
22095 (not (re-search-backward start-re (1+ beg) t))
22096 ;; Return value.
22097 (cons beg end))))))
22099 (defun org-in-block-p (names)
22100 "Non-nil when point belongs to a block whose name belongs to NAMES.
22102 NAMES is a list of strings containing names of blocks.
22104 Return first block name matched, or nil. Beware that in case of
22105 nested blocks, the returned name may not belong to the closest
22106 block from point."
22107 (save-match-data
22108 (catch 'exit
22109 (let ((case-fold-search t)
22110 (lim-up (save-excursion (outline-previous-heading)))
22111 (lim-down (save-excursion (outline-next-heading))))
22112 (dolist (name names)
22113 (let ((n (regexp-quote name)))
22114 (when (org-between-regexps-p
22115 (concat "^[ \t]*#\\+begin_" n)
22116 (concat "^[ \t]*#\\+end_" n)
22117 lim-up lim-down)
22118 (throw 'exit n)))))
22119 nil)))
22121 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22122 "Call `multi-occur' with buffers for all agenda files."
22123 (interactive "sOrg-files matching: ")
22124 (let* ((files (org-agenda-files))
22125 (tnames (mapcar #'file-truename files))
22126 (extra org-agenda-text-search-extra-files))
22127 (when (eq (car extra) 'agenda-archives)
22128 (setq extra (cdr extra))
22129 (setq files (org-add-archive-files files)))
22130 (dolist (f extra)
22131 (unless (member (file-truename f) tnames)
22132 (unless (member f files) (setq files (append files (list f))))
22133 (setq tnames (append tnames (list (file-truename f))))))
22134 (multi-occur
22135 (mapcar (lambda (x)
22136 (with-current-buffer
22137 ;; FIXME: Why not just (find-file-noselect x)?
22138 ;; Is it to avoid the "revert buffer" prompt?
22139 (or (get-file-buffer x) (find-file-noselect x))
22140 (widen)
22141 (current-buffer)))
22142 files)
22143 regexp)))
22145 (add-hook 'occur-mode-find-occurrence-hook
22146 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22148 (defun org-occur-link-in-agenda-files ()
22149 "Create a link and search for it in the agendas.
22150 The link is not stored in `org-stored-links', it is just created
22151 for the search purpose."
22152 (interactive)
22153 (let ((link (condition-case nil
22154 (org-store-link nil)
22155 (error "Unable to create a link to here"))))
22156 (org-occur-in-agenda-files (regexp-quote link))))
22158 (defun org-reverse-string (string)
22159 "Return the reverse of STRING."
22160 (apply 'string (reverse (string-to-list string))))
22162 ;; defsubst org-uniquify must be defined before first use
22164 (defun org-uniquify-alist (alist)
22165 "Merge elements of ALIST with the same key.
22167 For example, in this alist:
22169 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22170 => \\='((a 1 3) (b 2))
22172 merge (a 1) and (a 3) into (a 1 3).
22174 The function returns the new ALIST."
22175 (let (rtn)
22176 (dolist (e alist rtn)
22177 (let (n)
22178 (if (not (assoc (car e) rtn))
22179 (push e rtn)
22180 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22181 (setq rtn (assq-delete-all (car e) rtn))
22182 (push n rtn))))))
22184 (defun org-delete-all (elts list)
22185 "Remove all elements in ELTS from LIST.
22186 Comparison is done with `equal'. It is a destructive operation
22187 that may remove elements by altering the list structure."
22188 (while elts
22189 (setq list (delete (pop elts) list)))
22190 list)
22192 (defun org-back-over-empty-lines ()
22193 "Move backwards over whitespace, to the beginning of the first empty line.
22194 Returns the number of empty lines passed."
22195 (let ((pos (point)))
22196 (if (cdr (assq 'heading org-blank-before-new-entry))
22197 (skip-chars-backward " \t\n\r")
22198 (unless (eobp)
22199 (forward-line -1)))
22200 (beginning-of-line 2)
22201 (goto-char (min (point) pos))
22202 (count-lines (point) pos)))
22204 (defun org-skip-whitespace ()
22205 (skip-chars-forward " \t\n\r"))
22207 (defun org-point-in-group (point group &optional context)
22208 "Check if POINT is in match-group GROUP.
22209 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22210 match. If the match group does not exist or point is not inside it,
22211 return nil."
22212 (and (match-beginning group)
22213 (>= point (match-beginning group))
22214 (<= point (match-end group))
22215 (if context
22216 (list context (match-beginning group) (match-end group))
22217 t)))
22219 (defun org-switch-to-buffer-other-window (&rest args)
22220 "Switch to buffer in a second window on the current frame.
22221 In particular, do not allow pop-up frames.
22222 Returns the newly created buffer."
22223 (org-no-popups
22224 (apply 'switch-to-buffer-other-window args)))
22226 (defun org-combine-plists (&rest plists)
22227 "Create a single property list from all plists in PLISTS.
22228 The process starts by copying the first list, and then setting properties
22229 from the other lists. Settings in the last list are the most significant
22230 ones and overrule settings in the other lists."
22231 (let ((rtn (copy-sequence (pop plists)))
22232 p v ls)
22233 (while plists
22234 (setq ls (pop plists))
22235 (while ls
22236 (setq p (pop ls) v (pop ls))
22237 (setq rtn (plist-put rtn p v))))
22238 rtn))
22240 (defun org-replace-escapes (string table)
22241 "Replace %-escapes in STRING with values in TABLE.
22242 TABLE is an association list with keys like \"%a\" and string values.
22243 The sequences in STRING may contain normal field width and padding information,
22244 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22245 so values can contain further %-escapes if they are define later in TABLE."
22246 (let ((tbl (copy-alist table))
22247 (case-fold-search nil)
22248 (pchg 0)
22249 re rpl)
22250 (dolist (e tbl)
22251 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22252 (when (and (cdr e) (string-match re (cdr e)))
22253 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22254 (safe "SREF"))
22255 (add-text-properties 0 3 (list 'sref sref) safe)
22256 (setcdr e (replace-match safe t t (cdr e)))))
22257 (while (string-match re string)
22258 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22259 (cdr e)))
22260 (setq string (replace-match rpl t t string))))
22261 (while (setq pchg (next-property-change pchg string))
22262 (let ((sref (get-text-property pchg 'sref string)))
22263 (when (and sref (string-match "SREF" string pchg))
22264 (setq string (replace-match sref t t string)))))
22265 string))
22267 (defun org-find-base-buffer-visiting (file)
22268 "Like `find-buffer-visiting' but always return the base buffer and
22269 not an indirect buffer."
22270 (let ((buf (or (get-file-buffer file)
22271 (find-buffer-visiting file))))
22272 (if buf
22273 (or (buffer-base-buffer buf) buf)
22274 nil)))
22276 ;;; TODO: Only called once, from ox-odt which should probably use
22277 ;;; org-export-inline-image-p or something.
22278 (defun org-file-image-p (file)
22279 "Return non-nil if FILE is an image."
22280 (save-match-data
22281 (string-match (image-file-name-regexp) file)))
22283 (defun org-get-cursor-date (&optional with-time)
22284 "Return the date at cursor in as a time.
22285 This works in the calendar and in the agenda, anywhere else it just
22286 returns the current time.
22287 If WITH-TIME is non-nil, returns the time of the event at point (in
22288 the agenda) or the current time of the day."
22289 (let (date day defd tp hod mod)
22290 (when with-time
22291 (setq tp (get-text-property (point) 'time))
22292 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22293 (setq hod (string-to-number (match-string 1 tp))
22294 mod (string-to-number (match-string 2 tp))))
22295 (or tp (let ((now (decode-time)))
22296 (setq hod (nth 2 now)
22297 mod (nth 1 now)))))
22298 (cond
22299 ((eq major-mode 'calendar-mode)
22300 (setq date (calendar-cursor-to-date)
22301 defd (encode-time 0 (or mod 0) (or hod 0)
22302 (nth 1 date) (nth 0 date) (nth 2 date))))
22303 ((eq major-mode 'org-agenda-mode)
22304 (setq day (get-text-property (point) 'day))
22305 (when day
22306 (setq date (calendar-gregorian-from-absolute day)
22307 defd (encode-time 0 (or mod 0) (or hod 0)
22308 (nth 1 date) (nth 0 date) (nth 2 date))))))
22309 (or defd (current-time))))
22311 (defun org-mark-subtree (&optional up)
22312 "Mark the current subtree.
22313 This puts point at the start of the current subtree, and mark at
22314 the end. If a numeric prefix UP is given, move up into the
22315 hierarchy of headlines by UP levels before marking the subtree."
22316 (interactive "P")
22317 (org-with-limited-levels
22318 (cond ((org-at-heading-p) (beginning-of-line))
22319 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22320 (t (outline-previous-visible-heading 1))))
22321 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22322 (if (called-interactively-p 'any)
22323 (call-interactively 'org-mark-element)
22324 (org-mark-element)))
22326 (defun org-file-newer-than-p (file time)
22327 "Non-nil if FILE is newer than TIME.
22328 FILE is a filename, as a string, TIME is a list of integers, as
22329 returned by, e.g., `current-time'."
22330 (and (file-exists-p file)
22331 ;; Only compare times up to whole seconds as some file-systems
22332 ;; (e.g. HFS+) do not retain any finer granularity. As
22333 ;; a consequence, make sure we return non-nil when the two
22334 ;; times are equal.
22335 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22336 (cl-subseq time 0 2)))))
22338 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22339 "Compile a SOURCE file using PROCESS.
22341 PROCESS is either a function or a list of shell commands, as
22342 strings. EXT is a file extension, without the leading dot, as
22343 a string. It is used to check if the process actually succeeded.
22345 PROCESS must create a file with the same base name and directory
22346 as SOURCE, but ending with EXT. The function then returns its
22347 filename. Otherwise, it raises an error. The error message can
22348 then be refined by providing string ERR-MSG, which is appended to
22349 the standard message.
22351 If PROCESS is a function, it is called with a single argument:
22352 the SOURCE file.
22354 If it is a list of commands, each of them is called using
22355 `shell-command'. By default, in each command, %b, %f, %F, %o and
22356 %O are replaced with, respectively, SOURCE base name, name, full
22357 name, directory and absolute output file name. It is possible,
22358 however, to use more place-holders by specifying them in optional
22359 argument SPEC, as an alist following the pattern
22361 (CHARACTER . REPLACEMENT-STRING).
22363 When PROCESS is a list of commands, optional argument LOG-BUF can
22364 be set to a buffer or a buffer name. `shell-command' then uses
22365 it for output."
22366 (let* ((base-name (file-name-base source))
22367 (full-name (file-truename source))
22368 (out-dir (or (file-name-directory source) "./"))
22369 (output (expand-file-name (concat base-name "." ext) out-dir))
22370 (time (current-time))
22371 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22372 (save-window-excursion
22373 (pcase process
22374 ((pred functionp) (funcall process (shell-quote-argument source)))
22375 ((pred consp)
22376 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22377 (spec (append spec
22378 `((?b . ,(shell-quote-argument base-name))
22379 (?f . ,(shell-quote-argument source))
22380 (?F . ,(shell-quote-argument full-name))
22381 (?o . ,(shell-quote-argument out-dir))
22382 (?O . ,(shell-quote-argument output))))))
22383 (dolist (command process)
22384 (shell-command (format-spec command spec) log-buf))
22385 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22386 (_ (error "No valid command to process %S%s" source err-msg))))
22387 ;; Check for process failure. Output file is expected to be
22388 ;; located in the same directory as SOURCE.
22389 (unless (org-file-newer-than-p output time)
22390 (error (format "File %S wasn't produced%s" output err-msg)))
22391 output))
22393 ;;; Indentation
22395 (defvar org-element-greater-elements)
22396 (defun org--get-expected-indentation (element contentsp)
22397 "Expected indentation column for current line, according to ELEMENT.
22398 ELEMENT is an element containing point. CONTENTSP is non-nil
22399 when indentation is to be computed according to contents of
22400 ELEMENT."
22401 (let ((type (org-element-type element))
22402 (start (org-element-property :begin element))
22403 (post-affiliated (org-element-property :post-affiliated element)))
22404 (org-with-wide-buffer
22405 (cond
22406 (contentsp
22407 (cl-case type
22408 ((diary-sexp footnote-definition) 0)
22409 ((headline inlinetask nil)
22410 (if (not org-adapt-indentation) 0
22411 (let ((level (org-current-level)))
22412 (if level (1+ level) 0))))
22413 ((item plain-list) (org-list-item-body-column post-affiliated))
22415 (goto-char start)
22416 (org-get-indentation))))
22417 ((memq type '(headline inlinetask nil))
22418 (if (org-match-line "[ \t]*$")
22419 (org--get-expected-indentation element t)
22421 ((memq type '(diary-sexp footnote-definition)) 0)
22422 ;; First paragraph of a footnote definition or an item.
22423 ;; Indent like parent.
22424 ((< (line-beginning-position) start)
22425 (org--get-expected-indentation
22426 (org-element-property :parent element) t))
22427 ;; At first line: indent according to previous sibling, if any,
22428 ;; ignoring footnote definitions and inline tasks, or parent's
22429 ;; contents.
22430 ((= (line-beginning-position) start)
22431 (catch 'exit
22432 (while t
22433 (if (= (point-min) start) (throw 'exit 0)
22434 (goto-char (1- start))
22435 (let* ((previous (org-element-at-point))
22436 (parent previous))
22437 (while (and parent (<= (org-element-property :end parent) start))
22438 (setq previous parent
22439 parent (org-element-property :parent parent)))
22440 (cond
22441 ((not previous) (throw 'exit 0))
22442 ((> (org-element-property :end previous) start)
22443 (throw 'exit (org--get-expected-indentation previous t)))
22444 ((memq (org-element-type previous)
22445 '(footnote-definition inlinetask))
22446 (setq start (org-element-property :begin previous)))
22447 (t (goto-char (org-element-property :begin previous))
22448 (throw 'exit
22449 (if (bolp) (org-get-indentation)
22450 ;; At first paragraph in an item or
22451 ;; a footnote definition.
22452 (org--get-expected-indentation
22453 (org-element-property :parent previous) t))))))))))
22454 ;; Otherwise, move to the first non-blank line above.
22456 (beginning-of-line)
22457 (let ((pos (point)))
22458 (skip-chars-backward " \r\t\n")
22459 (cond
22460 ;; Two blank lines end a footnote definition or a plain
22461 ;; list. When we indent an empty line after them, the
22462 ;; containing list or footnote definition is over, so it
22463 ;; qualifies as a previous sibling. Therefore, we indent
22464 ;; like its first line.
22465 ((and (memq type '(footnote-definition plain-list))
22466 (> (count-lines (point) pos) 2))
22467 (goto-char start)
22468 (org-get-indentation))
22469 ;; Line above is the first one of a paragraph at the
22470 ;; beginning of an item or a footnote definition. Indent
22471 ;; like parent.
22472 ((< (line-beginning-position) start)
22473 (org--get-expected-indentation
22474 (org-element-property :parent element) t))
22475 ;; Line above is the beginning of an element, i.e., point
22476 ;; was originally on the blank lines between element's start
22477 ;; and contents.
22478 ((= (line-beginning-position) post-affiliated)
22479 (org--get-expected-indentation element t))
22480 ;; POS is after contents in a greater element. Indent like
22481 ;; the beginning of the element.
22482 ((and (memq type org-element-greater-elements)
22483 (let ((cend (org-element-property :contents-end element)))
22484 (and cend (<= cend pos))))
22485 ;; As a special case, if point is at the end of a footnote
22486 ;; definition or an item, indent like the very last element
22487 ;; within. If that last element is an item, indent like
22488 ;; its contents.
22489 (if (memq type '(footnote-definition item plain-list))
22490 (let ((last (org-element-at-point)))
22491 (goto-char pos)
22492 (org--get-expected-indentation
22493 last (eq (org-element-type last) 'item)))
22494 (goto-char start)
22495 (org-get-indentation)))
22496 ;; In any other case, indent like the current line.
22497 (t (org-get-indentation)))))))))
22499 (defun org--align-node-property ()
22500 "Align node property at point.
22501 Alignment is done according to `org-property-format', which see."
22502 (when (save-excursion
22503 (beginning-of-line)
22504 (looking-at org-property-re))
22505 (replace-match
22506 (concat (match-string 4)
22507 (org-trim
22508 (format org-property-format (match-string 1) (match-string 3))))
22509 t t)))
22511 (defun org-indent-line ()
22512 "Indent line depending on context.
22514 Indentation is done according to the following rules:
22516 - Footnote definitions, diary sexps, headlines and inline tasks
22517 have to start at column 0.
22519 - On the very first line of an element, consider, in order, the
22520 next rules until one matches:
22522 1. If there's a sibling element before, ignoring footnote
22523 definitions and inline tasks, indent like its first line.
22525 2. If element has a parent, indent like its contents. More
22526 precisely, if parent is an item, indent after the
22527 description part, if any, or the bullet (see
22528 `org-list-description-max-indent'). Else, indent like
22529 parent's first line.
22531 3. Otherwise, indent relatively to current level, if
22532 `org-adapt-indentation' is non-nil, or to left margin.
22534 - On a blank line at the end of an element, indent according to
22535 the type of the element. More precisely
22537 1. If element is a plain list, an item, or a footnote
22538 definition, indent like the very last element within.
22540 2. If element is a paragraph, indent like its last non blank
22541 line.
22543 3. Otherwise, indent like its very first line.
22545 - In the code part of a source block, use language major mode
22546 to indent current line if `org-src-tab-acts-natively' is
22547 non-nil. If it is nil, do nothing.
22549 - Otherwise, indent like the first non-blank line above.
22551 The function doesn't indent an item as it could break the whole
22552 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22553 `\\[org-shiftmetaright]'.
22555 Also align node properties according to `org-property-format'."
22556 (interactive)
22557 (cond
22558 (orgstruct-is-++
22559 (let ((indent-line-function
22560 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22561 (indent-according-to-mode)))
22562 ((org-at-heading-p) 'noindent)
22564 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22565 (type (org-element-type element)))
22566 (cond ((and (memq type '(plain-list item))
22567 (= (line-beginning-position)
22568 (org-element-property :post-affiliated element)))
22569 'noindent)
22570 ((and (eq type 'latex-environment)
22571 (>= (point) (org-element-property :post-affiliated element))
22572 (< (point) (org-with-wide-buffer
22573 (goto-char (org-element-property :end element))
22574 (skip-chars-backward " \r\t\n")
22575 (line-beginning-position 2))))
22576 'noindent)
22577 ((and (eq type 'src-block)
22578 org-src-tab-acts-natively
22579 (> (line-beginning-position)
22580 (org-element-property :post-affiliated element))
22581 (< (line-beginning-position)
22582 (org-with-wide-buffer
22583 (goto-char (org-element-property :end element))
22584 (skip-chars-backward " \r\t\n")
22585 (line-beginning-position))))
22586 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22588 (let ((column (org--get-expected-indentation element nil)))
22589 ;; Preserve current column.
22590 (if (<= (current-column) (current-indentation))
22591 (indent-line-to column)
22592 (save-excursion (indent-line-to column))))
22593 ;; Align node property. Also preserve current column.
22594 (when (eq type 'node-property)
22595 (let ((column (current-column)))
22596 (org--align-node-property)
22597 (org-move-to-column column)))))))))
22599 (defun org-indent-region (start end)
22600 "Indent each non-blank line in the region.
22601 Called from a program, START and END specify the region to
22602 indent. The function will not indent contents of example blocks,
22603 verse blocks and export blocks as leading white spaces are
22604 assumed to be significant there."
22605 (interactive "r")
22606 (save-excursion
22607 (goto-char start)
22608 (skip-chars-forward " \r\t\n")
22609 (unless (eobp) (beginning-of-line))
22610 (let ((indent-to
22611 (lambda (ind pos)
22612 ;; Set IND as indentation for all lines between point and
22613 ;; POS. Blank lines are ignored. Leave point after POS
22614 ;; once done.
22615 (let ((limit (copy-marker pos)))
22616 (while (< (point) limit)
22617 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22618 (forward-line))
22619 (set-marker limit nil))))
22620 (end (copy-marker end)))
22621 (while (< (point) end)
22622 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22623 (let* ((element (org-element-at-point))
22624 (type (org-element-type element))
22625 (element-end (copy-marker (org-element-property :end element)))
22626 (ind (org--get-expected-indentation element nil)))
22627 (cond
22628 ;; Element indented as a single block. Example blocks
22629 ;; preserving indentation are a special case since the
22630 ;; "contents" must not be indented whereas the block
22631 ;; boundaries can.
22632 ((or (memq type '(export-block latex-environment))
22633 (and (eq type 'example-block)
22634 (not
22635 (or org-src-preserve-indentation
22636 (org-element-property :preserve-indent element)))))
22637 (let ((offset (- ind (org-get-indentation))))
22638 (unless (zerop offset)
22639 (indent-rigidly (org-element-property :begin element)
22640 (org-element-property :end element)
22641 offset)))
22642 (goto-char element-end))
22643 ;; Elements indented line wise. Be sure to exclude
22644 ;; example blocks (preserving indentation) and source
22645 ;; blocks from this category as they are treated
22646 ;; specially later.
22647 ((or (memq type '(paragraph table table-row))
22648 (not (or (org-element-property :contents-begin element)
22649 (memq type '(example-block src-block)))))
22650 (when (eq type 'node-property)
22651 (org--align-node-property)
22652 (beginning-of-line))
22653 (funcall indent-to ind (min element-end end)))
22654 ;; Elements consisting of three parts: before the
22655 ;; contents, the contents, and after the contents. The
22656 ;; contents are treated specially, according to the
22657 ;; element type, or not indented at all. Other parts are
22658 ;; indented as a single block.
22660 (let* ((post (copy-marker
22661 (org-element-property :post-affiliated element)))
22662 (cbeg
22663 (copy-marker
22664 (cond
22665 ((not (org-element-property :contents-begin element))
22666 ;; Fake contents for source blocks.
22667 (org-with-wide-buffer
22668 (goto-char post)
22669 (line-beginning-position 2)))
22670 ((memq type '(footnote-definition item plain-list))
22671 ;; Contents in these elements could start on
22672 ;; the same line as the beginning of the
22673 ;; element. Make sure we start indenting
22674 ;; from the second line.
22675 (org-with-wide-buffer
22676 (goto-char post)
22677 (end-of-line)
22678 (skip-chars-forward " \r\t\n")
22679 (if (eobp) (point) (line-beginning-position))))
22680 (t (org-element-property :contents-begin element)))))
22681 (cend (copy-marker
22682 (or (org-element-property :contents-end element)
22683 ;; Fake contents for source blocks.
22684 (org-with-wide-buffer
22685 (goto-char element-end)
22686 (skip-chars-backward " \r\t\n")
22687 (line-beginning-position)))
22688 t)))
22689 ;; Do not change items indentation individually as it
22690 ;; might break the list as a whole. On the other
22691 ;; hand, when at a plain list, indent it as a whole.
22692 (cond ((eq type 'plain-list)
22693 (let ((offset (- ind (org-get-indentation))))
22694 (unless (zerop offset)
22695 (indent-rigidly (org-element-property :begin element)
22696 (org-element-property :end element)
22697 offset))
22698 (goto-char cbeg)))
22699 ((eq type 'item) (goto-char cbeg))
22700 (t (funcall indent-to ind (min cbeg end))))
22701 (when (< (point) end)
22702 (cl-case type
22703 ((example-block verse-block))
22704 (src-block
22705 ;; In a source block, indent source code
22706 ;; according to language major mode, but only if
22707 ;; `org-src-tab-acts-natively' is non-nil.
22708 (when (and (< (point) end) org-src-tab-acts-natively)
22709 (ignore-errors
22710 (org-babel-do-in-edit-buffer
22711 (indent-region (point-min) (point-max))))))
22712 (t (org-indent-region (point) (min cend end))))
22713 (goto-char (min cend end))
22714 (when (< (point) end)
22715 (funcall indent-to ind (min element-end end))))
22716 (set-marker post nil)
22717 (set-marker cbeg nil)
22718 (set-marker cend nil))))
22719 (set-marker element-end nil))))
22720 (set-marker end nil))))
22722 (defun org-indent-drawer ()
22723 "Indent the drawer at point."
22724 (interactive)
22725 (unless (save-excursion
22726 (beginning-of-line)
22727 (looking-at-p org-drawer-regexp))
22728 (user-error "Not at a drawer"))
22729 (let ((element (org-element-at-point)))
22730 (unless (memq (org-element-type element) '(drawer property-drawer))
22731 (user-error "Not at a drawer"))
22732 (org-with-wide-buffer
22733 (org-indent-region (org-element-property :begin element)
22734 (org-element-property :end element))))
22735 (message "Drawer at point indented"))
22737 (defun org-indent-block ()
22738 "Indent the block at point."
22739 (interactive)
22740 (unless (save-excursion
22741 (beginning-of-line)
22742 (let ((case-fold-search t))
22743 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22744 (user-error "Not at a block"))
22745 (let ((element (org-element-at-point)))
22746 (unless (memq (org-element-type element)
22747 '(comment-block center-block dynamic-block example-block
22748 export-block quote-block special-block
22749 src-block verse-block))
22750 (user-error "Not at a block"))
22751 (org-with-wide-buffer
22752 (org-indent-region (org-element-property :begin element)
22753 (org-element-property :end element))))
22754 (message "Block at point indented"))
22757 ;;; Filling
22759 ;; We use our own fill-paragraph and auto-fill functions.
22761 ;; `org-fill-paragraph' relies on adaptive filling and context
22762 ;; checking. Appropriate `fill-prefix' is computed with
22763 ;; `org-adaptive-fill-function'.
22765 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22766 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22767 ;; `org-adaptive-fill-function' value. Internally,
22768 ;; `org-comment-line-break-function' breaks the line.
22770 ;; `org-setup-filling' installs filling and auto-filling related
22771 ;; variables during `org-mode' initialization.
22773 (defvar org-element-paragraph-separate) ; org-element.el
22774 (defun org-setup-filling ()
22775 (require 'org-element)
22776 ;; Prevent auto-fill from inserting unwanted new items.
22777 (when (boundp 'fill-nobreak-predicate)
22778 (setq-local
22779 fill-nobreak-predicate
22780 (org-uniquify
22781 (append fill-nobreak-predicate
22782 '(org-fill-line-break-nobreak-p
22783 org-fill-n-macro-as-item-nobreak-p
22784 org-fill-paragraph-with-timestamp-nobreak-p)))))
22785 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22786 (setq-local paragraph-start paragraph-ending)
22787 (setq-local paragraph-separate paragraph-ending))
22788 (setq-local fill-paragraph-function 'org-fill-paragraph)
22789 (setq-local auto-fill-inhibit-regexp nil)
22790 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22791 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22792 (setq-local comment-line-break-function 'org-comment-line-break-function))
22794 (defun org-fill-line-break-nobreak-p ()
22795 "Non-nil when a new line at point would create an Org line break."
22796 (save-excursion
22797 (skip-chars-backward "[ \t]")
22798 (skip-chars-backward "\\\\")
22799 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22801 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22802 "Non-nil when a new line at point would split a timestamp."
22803 (and (org-at-timestamp-p 'lax)
22804 (not (looking-at org-ts-regexp-both))))
22806 (defun org-fill-n-macro-as-item-nobreak-p ()
22807 "Non-nil when a new line at point would create a new list."
22808 ;; During export, a "n" macro followed by a dot or a closing
22809 ;; parenthesis can end up being parsed as a new list item.
22810 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22812 (declare-function message-in-body-p "message" ())
22813 (defvar orgtbl-line-start-regexp) ; From org-table.el
22814 (defun org-adaptive-fill-function ()
22815 "Compute a fill prefix for the current line.
22816 Return fill prefix, as a string, or nil if current line isn't
22817 meant to be filled. For convenience, if `adaptive-fill-regexp'
22818 matches in paragraphs or comments, use it."
22819 (catch 'exit
22820 (when (derived-mode-p 'message-mode)
22821 (save-excursion
22822 (beginning-of-line)
22823 (cond ((not (message-in-body-p)) (throw 'exit nil))
22824 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22825 ((looking-at message-cite-prefix-regexp)
22826 (throw 'exit (match-string-no-properties 0)))
22827 ((looking-at org-outline-regexp)
22828 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22829 (org-with-wide-buffer
22830 (unless (org-at-heading-p)
22831 (let* ((p (line-beginning-position))
22832 (element (save-excursion
22833 (beginning-of-line)
22834 (org-element-at-point)))
22835 (type (org-element-type element))
22836 (post-affiliated (org-element-property :post-affiliated element)))
22837 (unless (< p post-affiliated)
22838 (cl-case type
22839 (comment
22840 (save-excursion
22841 (beginning-of-line)
22842 (looking-at "[ \t]*")
22843 (concat (match-string 0) "# ")))
22844 (footnote-definition "")
22845 ((item plain-list)
22846 (make-string (org-list-item-body-column post-affiliated) ?\s))
22847 (paragraph
22848 ;; Fill prefix is usually the same as the current line,
22849 ;; unless the paragraph is at the beginning of an item.
22850 (let ((parent (org-element-property :parent element)))
22851 (save-excursion
22852 (beginning-of-line)
22853 (cond ((eq (org-element-type parent) 'item)
22854 (make-string (org-list-item-body-column
22855 (org-element-property :begin parent))
22856 ?\s))
22857 ((and adaptive-fill-regexp
22858 ;; Locally disable
22859 ;; `adaptive-fill-function' to let
22860 ;; `fill-context-prefix' handle
22861 ;; `adaptive-fill-regexp' variable.
22862 (let (adaptive-fill-function)
22863 (fill-context-prefix
22864 post-affiliated
22865 (org-element-property :end element)))))
22866 ((looking-at "[ \t]+") (match-string 0))
22867 (t "")))))
22868 (comment-block
22869 ;; Only fill contents if P is within block boundaries.
22870 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22871 (forward-line)
22872 (point)))
22873 (cend (save-excursion
22874 (goto-char (org-element-property :end element))
22875 (skip-chars-backward " \r\t\n")
22876 (line-beginning-position))))
22877 (when (and (>= p cbeg) (< p cend))
22878 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22879 (match-string 0)
22880 "")))))))))))
22882 (declare-function message-goto-body "message" ())
22883 (defvar message-cite-prefix-regexp) ; From message.el
22885 (defun org-fill-element (&optional justify)
22886 "Fill element at point, when applicable.
22888 This function only applies to comment blocks, comments, example
22889 blocks and paragraphs. Also, as a special case, re-align table
22890 when point is at one.
22892 If JUSTIFY is non-nil (interactively, with prefix argument),
22893 justify as well. If `sentence-end-double-space' is non-nil, then
22894 period followed by one space does not end a sentence, so don't
22895 break a line there. The variable `fill-column' controls the
22896 width for filling.
22898 For convenience, when point is at a plain list, an item or
22899 a footnote definition, try to fill the first paragraph within."
22900 (with-syntax-table org-mode-transpose-word-syntax-table
22901 ;; Move to end of line in order to get the first paragraph within
22902 ;; a plain list or a footnote definition.
22903 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22904 ;; First check if point is in a blank line at the beginning of
22905 ;; the buffer. In that case, ignore filling.
22906 (cl-case (org-element-type element)
22907 ;; Use major mode filling function is src blocks.
22908 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22909 ;; Align Org tables, leave table.el tables as-is.
22910 (table-row (org-table-align) t)
22911 (table
22912 (when (eq (org-element-property :type element) 'org)
22913 (save-excursion
22914 (goto-char (org-element-property :post-affiliated element))
22915 (org-table-align)))
22917 (paragraph
22918 ;; Paragraphs may contain `line-break' type objects.
22919 (let ((beg (max (point-min)
22920 (org-element-property :contents-begin element)))
22921 (end (min (point-max)
22922 (org-element-property :contents-end element))))
22923 ;; Do nothing if point is at an affiliated keyword.
22924 (if (< (line-end-position) beg) t
22925 (when (derived-mode-p 'message-mode)
22926 ;; In `message-mode', do not fill following citation
22927 ;; in current paragraph nor text before message body.
22928 (let ((body-start (save-excursion (message-goto-body))))
22929 (when body-start (setq beg (max body-start beg))))
22930 (when (save-excursion
22931 (re-search-forward
22932 (concat "^" message-cite-prefix-regexp) end t))
22933 (setq end (match-beginning 0))))
22934 ;; Fill paragraph, taking line breaks into account.
22935 (save-excursion
22936 (goto-char beg)
22937 (let ((cuts (list beg)))
22938 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22939 (when (eq 'line-break
22940 (org-element-type
22941 (save-excursion (backward-char)
22942 (org-element-context))))
22943 (push (point) cuts)))
22944 (dolist (c (delq end cuts))
22945 (fill-region-as-paragraph c end justify)
22946 (setq end c))))
22947 t)))
22948 ;; Contents of `comment-block' type elements should be
22949 ;; filled as plain text, but only if point is within block
22950 ;; markers.
22951 (comment-block
22952 (let* ((case-fold-search t)
22953 (beg (save-excursion
22954 (goto-char (org-element-property :begin element))
22955 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22956 (forward-line)
22957 (point)))
22958 (end (save-excursion
22959 (goto-char (org-element-property :end element))
22960 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22961 (line-beginning-position))))
22962 (if (or (< (point) beg) (> (point) end)) t
22963 (fill-region-as-paragraph
22964 (save-excursion (end-of-line)
22965 (re-search-backward "^[ \t]*$" beg 'move)
22966 (line-beginning-position))
22967 (save-excursion (beginning-of-line)
22968 (re-search-forward "^[ \t]*$" end 'move)
22969 (line-beginning-position))
22970 justify))))
22971 ;; Fill comments.
22972 (comment
22973 (let ((begin (org-element-property :post-affiliated element))
22974 (end (org-element-property :end element)))
22975 (when (and (>= (point) begin) (<= (point) end))
22976 (let ((begin (save-excursion
22977 (end-of-line)
22978 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22979 (progn (forward-line) (point))
22980 begin)))
22981 (end (save-excursion
22982 (end-of-line)
22983 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22984 (1- (line-beginning-position))
22985 (skip-chars-backward " \r\t\n")
22986 (line-end-position)))))
22987 ;; Do not fill comments when at a blank line.
22988 (when (> end begin)
22989 (let ((fill-prefix
22990 (save-excursion
22991 (beginning-of-line)
22992 (looking-at "[ \t]*#")
22993 (let ((comment-prefix (match-string 0)))
22994 (goto-char (match-end 0))
22995 (if (looking-at adaptive-fill-regexp)
22996 (concat comment-prefix (match-string 0))
22997 (concat comment-prefix " "))))))
22998 (save-excursion
22999 (fill-region-as-paragraph begin end justify))))))
23001 ;; Ignore every other element.
23002 (otherwise t)))))
23004 (defun org-fill-paragraph (&optional justify region)
23005 "Fill element at point, when applicable.
23007 This function only applies to comment blocks, comments, example
23008 blocks and paragraphs. Also, as a special case, re-align table
23009 when point is at one.
23011 For convenience, when point is at a plain list, an item or
23012 a footnote definition, try to fill the first paragraph within.
23014 If JUSTIFY is non-nil (interactively, with prefix argument),
23015 justify as well. If `sentence-end-double-space' is non-nil, then
23016 period followed by one space does not end a sentence, so don't
23017 break a line there. The variable `fill-column' controls the
23018 width for filling.
23020 The REGION argument is non-nil if called interactively; in that
23021 case, if Transient Mark mode is enabled and the mark is active,
23022 fill each of the elements in the active region, instead of just
23023 filling the current element."
23024 (interactive (progn
23025 (barf-if-buffer-read-only)
23026 (list (if current-prefix-arg 'full) t)))
23027 (cond
23028 ((and (derived-mode-p 'message-mode)
23029 (or (not (message-in-body-p))
23030 (save-excursion (move-beginning-of-line 1)
23031 (looking-at message-cite-prefix-regexp))))
23032 ;; First ensure filling is correct in message-mode.
23033 (let ((fill-paragraph-function
23034 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23035 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23036 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23037 (paragraph-separate
23038 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23039 (fill-paragraph nil)))
23040 ((and region transient-mark-mode mark-active
23041 (not (eq (region-beginning) (region-end))))
23042 (let ((origin (point-marker))
23043 (start (region-beginning)))
23044 (unwind-protect
23045 (progn
23046 (goto-char (region-end))
23047 (while (> (point) start)
23048 (org-backward-paragraph)
23049 (org-fill-element justify)))
23050 (goto-char origin)
23051 (set-marker origin nil))))
23052 (t (org-fill-element justify))))
23053 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23055 (defun org-auto-fill-function ()
23056 "Auto-fill function."
23057 ;; Check if auto-filling is meaningful.
23058 (let ((fc (current-fill-column)))
23059 (when (and fc (> (current-column) fc))
23060 (let* ((fill-prefix (org-adaptive-fill-function))
23061 ;; Enforce empty fill prefix, if required. Otherwise, it
23062 ;; will be computed again.
23063 (adaptive-fill-mode (not (equal fill-prefix ""))))
23064 (when fill-prefix (do-auto-fill))))))
23066 (defun org-comment-line-break-function (&optional soft)
23067 "Break line at point and indent, continuing comment if within one.
23068 The inserted newline is marked hard if variable
23069 `use-hard-newlines' is true, unless optional argument SOFT is
23070 non-nil."
23071 (if soft (insert-and-inherit ?\n) (newline 1))
23072 (save-excursion (forward-char -1) (delete-horizontal-space))
23073 (delete-horizontal-space)
23074 (indent-to-left-margin)
23075 (insert-before-markers-and-inherit fill-prefix))
23078 ;;; Fixed Width Areas
23080 (defun org-toggle-fixed-width ()
23081 "Toggle fixed-width markup.
23083 Add or remove fixed-width markup on current line, whenever it
23084 makes sense. Return an error otherwise.
23086 If a region is active and if it contains only fixed-width areas
23087 or blank lines, remove all fixed-width markup in it. If the
23088 region contains anything else, convert all non-fixed-width lines
23089 to fixed-width ones.
23091 Blank lines at the end of the region are ignored unless the
23092 region only contains such lines."
23093 (interactive)
23094 (if (not (org-region-active-p))
23095 ;; No region:
23097 ;; Remove fixed width marker only in a fixed-with element.
23099 ;; Add fixed width maker in paragraphs, in blank lines after
23100 ;; elements or at the beginning of a headline or an inlinetask,
23101 ;; and before any one-line elements (e.g., a clock).
23102 (progn
23103 (beginning-of-line)
23104 (let* ((element (org-element-at-point))
23105 (type (org-element-type element)))
23106 (cond
23107 ((and (eq type 'fixed-width)
23108 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23109 (replace-match
23110 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23111 ((and (memq type '(babel-call clock comment diary-sexp headline
23112 horizontal-rule keyword paragraph
23113 planning))
23114 (<= (org-element-property :post-affiliated element) (point)))
23115 (skip-chars-forward " \t")
23116 (insert ": "))
23117 ((and (looking-at-p "[ \t]*$")
23118 (or (eq type 'inlinetask)
23119 (save-excursion
23120 (skip-chars-forward " \r\t\n")
23121 (<= (org-element-property :end element) (point)))))
23122 (delete-region (point) (line-end-position))
23123 (org-indent-line)
23124 (insert ": "))
23125 (t (user-error "Cannot insert a fixed-width line here")))))
23126 ;; Region active.
23127 (let* ((begin (save-excursion
23128 (goto-char (region-beginning))
23129 (line-beginning-position)))
23130 (end (copy-marker
23131 (save-excursion
23132 (goto-char (region-end))
23133 (unless (eolp) (beginning-of-line))
23134 (if (save-excursion (re-search-backward "\\S-" begin t))
23135 (progn (skip-chars-backward " \r\t\n") (point))
23136 (point)))))
23137 (all-fixed-width-p
23138 (catch 'not-all-p
23139 (save-excursion
23140 (goto-char begin)
23141 (skip-chars-forward " \r\t\n")
23142 (when (eobp) (throw 'not-all-p nil))
23143 (while (< (point) end)
23144 (let ((element (org-element-at-point)))
23145 (if (eq (org-element-type element) 'fixed-width)
23146 (goto-char (org-element-property :end element))
23147 (throw 'not-all-p nil))))
23148 t))))
23149 (if all-fixed-width-p
23150 (save-excursion
23151 (goto-char begin)
23152 (while (< (point) end)
23153 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23154 (replace-match
23155 "" nil nil nil
23156 (if (= (line-end-position) (match-end 0)) 0 1)))
23157 (forward-line)))
23158 (let ((min-ind (point-max)))
23159 ;; Find minimum indentation across all lines.
23160 (save-excursion
23161 (goto-char begin)
23162 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23163 (setq min-ind 0)
23164 (catch 'zerop
23165 (while (< (point) end)
23166 (unless (looking-at-p "[ \t]*$")
23167 (let ((ind (org-get-indentation)))
23168 (setq min-ind (min min-ind ind))
23169 (when (zerop ind) (throw 'zerop t))))
23170 (forward-line)))))
23171 ;; Loop over all lines and add fixed-width markup everywhere
23172 ;; but in fixed-width lines.
23173 (save-excursion
23174 (goto-char begin)
23175 (while (< (point) end)
23176 (cond
23177 ((org-at-heading-p)
23178 (insert ": ")
23179 (forward-line)
23180 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23181 (insert ":")
23182 (forward-line)))
23183 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23184 (let* ((element (org-element-at-point))
23185 (element-end (org-element-property :end element)))
23186 (if (eq (org-element-type element) 'fixed-width)
23187 (progn (goto-char element-end)
23188 (skip-chars-backward " \r\t\n")
23189 (forward-line))
23190 (let ((limit (min end element-end)))
23191 (while (< (point) limit)
23192 (org-move-to-column min-ind t)
23193 (insert ": ")
23194 (forward-line))))))
23196 (org-move-to-column min-ind t)
23197 (insert ": ")
23198 (forward-line)))))))
23199 (set-marker end nil))))
23202 ;;; Comments
23204 ;; Org comments syntax is quite complex. It requires the entire line
23205 ;; to be just a comment. Also, even with the right syntax at the
23206 ;; beginning of line, some elements (e.g., verse-block or
23207 ;; example-block) don't accept comments. Usual Emacs comment commands
23208 ;; cannot cope with those requirements. Therefore, Org replaces them.
23210 ;; Org still relies on `comment-dwim', but cannot trust
23211 ;; `comment-only-p'. So, `comment-region-function' and
23212 ;; `uncomment-region-function' both point
23213 ;; to`org-comment-or-uncomment-region'. Eventually,
23214 ;; `org-insert-comment' takes care of insertion of comments at the
23215 ;; beginning of line.
23217 ;; `org-setup-comments-handling' install comments related variables
23218 ;; during `org-mode' initialization.
23220 (defun org-setup-comments-handling ()
23221 (interactive)
23222 (setq-local comment-use-syntax nil)
23223 (setq-local comment-start "# ")
23224 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23225 (setq-local comment-insert-comment-function 'org-insert-comment)
23226 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23227 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23229 (defun org-insert-comment ()
23230 "Insert an empty comment above current line.
23231 If the line is empty, insert comment at its beginning. When
23232 point is within a source block, comment according to the related
23233 major mode."
23234 (if (let ((element (org-element-at-point)))
23235 (and (eq (org-element-type element) 'src-block)
23236 (< (save-excursion
23237 (goto-char (org-element-property :post-affiliated element))
23238 (line-end-position))
23239 (point))
23240 (> (save-excursion
23241 (goto-char (org-element-property :end element))
23242 (skip-chars-backward " \r\t\n")
23243 (line-beginning-position))
23244 (point))))
23245 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23246 (beginning-of-line)
23247 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23248 (open-line 1))
23249 (org-indent-line)
23250 (insert "# ")))
23252 (defvar comment-empty-lines) ; From newcomment.el.
23253 (defun org-comment-or-uncomment-region (beg end &rest _)
23254 "Comment or uncomment each non-blank line in the region.
23255 Uncomment each non-blank line between BEG and END if it only
23256 contains commented lines. Otherwise, comment them. If region is
23257 strictly within a source block, use appropriate comment syntax."
23258 (if (let ((element (org-element-at-point)))
23259 (and (eq (org-element-type element) 'src-block)
23260 (< (save-excursion
23261 (goto-char (org-element-property :post-affiliated element))
23262 (line-end-position))
23263 beg)
23264 (>= (save-excursion
23265 (goto-char (org-element-property :end element))
23266 (skip-chars-backward " \r\t\n")
23267 (line-beginning-position))
23268 end)))
23269 ;; Translate region boundaries for the Org buffer to the source
23270 ;; buffer.
23271 (let ((offset (- end beg)))
23272 (save-excursion
23273 (goto-char beg)
23274 (org-babel-do-in-edit-buffer
23275 (comment-or-uncomment-region (point) (+ offset (point))))))
23276 (save-restriction
23277 ;; Restrict region
23278 (narrow-to-region (save-excursion (goto-char beg)
23279 (skip-chars-forward " \r\t\n" end)
23280 (line-beginning-position))
23281 (save-excursion (goto-char end)
23282 (skip-chars-backward " \r\t\n" beg)
23283 (line-end-position)))
23284 (let ((uncommentp
23285 ;; UNCOMMENTP is non-nil when every non blank line between
23286 ;; BEG and END is a comment.
23287 (save-excursion
23288 (goto-char (point-min))
23289 (while (and (not (eobp))
23290 (let ((element (org-element-at-point)))
23291 (and (eq (org-element-type element) 'comment)
23292 (goto-char (min (point-max)
23293 (org-element-property
23294 :end element)))))))
23295 (eobp))))
23296 (if uncommentp
23297 ;; Only blank lines and comments in region: uncomment it.
23298 (save-excursion
23299 (goto-char (point-min))
23300 (while (not (eobp))
23301 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23302 (replace-match "" nil nil nil 1))
23303 (forward-line)))
23304 ;; Comment each line in region.
23305 (let ((min-indent (point-max)))
23306 ;; First find the minimum indentation across all lines.
23307 (save-excursion
23308 (goto-char (point-min))
23309 (while (and (not (eobp)) (not (zerop min-indent)))
23310 (unless (looking-at "[ \t]*$")
23311 (setq min-indent (min min-indent (current-indentation))))
23312 (forward-line)))
23313 ;; Then loop over all lines.
23314 (save-excursion
23315 (goto-char (point-min))
23316 (while (not (eobp))
23317 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23318 ;; Don't get fooled by invisible text (e.g. link path)
23319 ;; when moving to column MIN-INDENT.
23320 (let ((buffer-invisibility-spec nil))
23321 (org-move-to-column min-indent t))
23322 (insert comment-start))
23323 (forward-line)))))))))
23325 (defun org-comment-dwim (_arg)
23326 "Call `comment-dwim' within a source edit buffer if needed."
23327 (interactive "*P")
23328 (if (org-in-src-block-p)
23329 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23330 (call-interactively 'comment-dwim)))
23333 ;;; Timestamps API
23335 ;; This section contains tools to operate on timestamp objects, as
23336 ;; returned by, e.g. `org-element-context'.
23338 (defun org-timestamp--to-internal-time (timestamp &optional end)
23339 "Encode TIMESTAMP object into Emacs internal time.
23340 Use end of date range or time range when END is non-nil."
23341 (apply #'encode-time
23342 (cons 0
23343 (mapcar
23344 (lambda (prop) (or (org-element-property prop timestamp) 0))
23345 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23346 '(:minute-start :hour-start :day-start :month-start
23347 :year-start))))))
23349 (defun org-timestamp-has-time-p (timestamp)
23350 "Non-nil when TIMESTAMP has a time specified."
23351 (org-element-property :hour-start timestamp))
23353 (defun org-timestamp-format (timestamp format &optional end utc)
23354 "Format a TIMESTAMP object into a string.
23356 FORMAT is a format specifier to be passed to
23357 `format-time-string'.
23359 When optional argument END is non-nil, use end of date-range or
23360 time-range, if possible.
23362 When optional argument UTC is non-nil, time will be expressed as
23363 Universal Time."
23364 (format-time-string
23365 format (org-timestamp--to-internal-time timestamp end)
23366 (and utc t)))
23368 (defun org-timestamp-split-range (timestamp &optional end)
23369 "Extract a TIMESTAMP object from a date or time range.
23371 END, when non-nil, means extract the end of the range.
23372 Otherwise, extract its start.
23374 Return a new timestamp object."
23375 (let ((type (org-element-property :type timestamp)))
23376 (if (memq type '(active inactive diary)) timestamp
23377 (let ((split-ts (org-element-copy timestamp)))
23378 ;; Set new type.
23379 (org-element-put-property
23380 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23381 ;; Copy start properties over end properties if END is
23382 ;; non-nil. Otherwise, copy end properties over `start' ones.
23383 (let ((p-alist '((:minute-start . :minute-end)
23384 (:hour-start . :hour-end)
23385 (:day-start . :day-end)
23386 (:month-start . :month-end)
23387 (:year-start . :year-end))))
23388 (dolist (p-cell p-alist)
23389 (org-element-put-property
23390 split-ts
23391 (funcall (if end #'car #'cdr) p-cell)
23392 (org-element-property
23393 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23394 ;; Eventually refresh `:raw-value'.
23395 (org-element-put-property split-ts :raw-value nil)
23396 (org-element-put-property
23397 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23399 (defun org-timestamp-translate (timestamp &optional boundary)
23400 "Translate TIMESTAMP object to custom format.
23402 Format string is defined in `org-time-stamp-custom-formats',
23403 which see.
23405 When optional argument BOUNDARY is non-nil, it is either the
23406 symbol `start' or `end'. In this case, only translate the
23407 starting or ending part of TIMESTAMP if it is a date or time
23408 range. Otherwise, translate both parts.
23410 Return timestamp as-is if `org-display-custom-times' is nil or if
23411 it has a `diary' type."
23412 (let ((type (org-element-property :type timestamp)))
23413 (if (or (not org-display-custom-times) (eq type 'diary))
23414 (org-element-interpret-data timestamp)
23415 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23416 org-time-stamp-custom-formats)))
23417 (if (and (not boundary) (memq type '(active-range inactive-range)))
23418 (concat (org-timestamp-format timestamp fmt)
23419 "--"
23420 (org-timestamp-format timestamp fmt t))
23421 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23425 ;;; Other stuff.
23427 (defvar reftex-docstruct-symbol)
23428 (defvar org--rds)
23430 (defun org-reftex-citation ()
23431 "Use reftex-citation to insert a citation into the buffer.
23432 This looks for a line like
23434 #+BIBLIOGRAPHY: foo plain option:-d
23436 and derives from it that foo.bib is the bibliography file relevant
23437 for this document. It then installs the necessary environment for RefTeX
23438 to work in this buffer and calls `reftex-citation' to insert a citation
23439 into the buffer.
23441 Export of such citations to both LaTeX and HTML is handled by the contributed
23442 package ox-bibtex by Taru Karttunen."
23443 (interactive)
23444 (let ((reftex-docstruct-symbol 'org--rds)
23445 org--rds bib)
23446 (org-with-wide-buffer
23447 (let ((case-fold-search t)
23448 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23449 (if (not (save-excursion
23450 (or (re-search-forward re nil t)
23451 (re-search-backward re nil t))))
23452 (user-error "No bibliography defined in file")
23453 (setq bib (concat (match-string 1) ".bib")
23454 org--rds (list (list 'bib bib))))))
23455 (call-interactively 'reftex-citation)))
23457 ;;;; Functions extending outline functionality
23459 (defun org-beginning-of-line (&optional n)
23460 "Go to the beginning of the current visible line.
23462 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23463 tags on the first attempt, and only move to after the tags when
23464 the cursor is already beyond the end of the headline.
23466 With argument N not nil or 1, move forward N - 1 lines first."
23467 (interactive "^p")
23468 (let ((origin (point))
23469 (special (pcase org-special-ctrl-a/e
23470 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23471 deactivate-mark)
23472 ;; First move to a visible line.
23473 (if (bound-and-true-p visual-line-mode)
23474 (beginning-of-visual-line n)
23475 (move-beginning-of-line n)
23476 ;; `move-beginning-of-line' may leave point after invisible
23477 ;; characters if line starts with such of these (e.g., with
23478 ;; a link at column 0). Really move to the beginning of the
23479 ;; current visible line.
23480 (beginning-of-line))
23481 (cond
23482 ;; No special behavior. Point is already at the beginning of
23483 ;; a line, logical or visual.
23484 ((not special))
23485 ;; `beginning-of-visual-line' left point before logical beginning
23486 ;; of line: point is at the beginning of a visual line. Bail
23487 ;; out.
23488 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23489 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23490 ;; At a headline, special position is before the title, but
23491 ;; after any TODO keyword or priority cookie.
23492 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23493 (line-end-position)))
23494 (bol (point)))
23495 (if (eq special 'reversed)
23496 (when (and (= origin bol) (eq last-command this-command))
23497 (goto-char refpos))
23498 (when (or (> origin refpos) (= origin bol))
23499 (goto-char refpos)))))
23500 ((and (looking-at org-list-full-item-re)
23501 (memq (org-element-type (save-match-data (org-element-at-point)))
23502 '(item plain-list)))
23503 ;; Set special position at first white space character after
23504 ;; bullet, and check-box, if any.
23505 (let ((after-bullet
23506 (let ((box (match-end 3)))
23507 (cond ((not box) (match-end 1))
23508 ((eq (char-after box) ?\s) (1+ box))
23509 (t box)))))
23510 (if (eq special 'reversed)
23511 (when (and (= (point) origin) (eq last-command this-command))
23512 (goto-char after-bullet))
23513 (when (or (> origin after-bullet) (= (point) origin))
23514 (goto-char after-bullet)))))
23515 ;; No special context. Point is already at beginning of line.
23516 (t nil))))
23518 (defun org-end-of-line (&optional n)
23519 "Go to the end of the line, but before ellipsis, if any.
23521 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23522 tags on the first attempt, and only move to after the tags when
23523 the cursor is already beyond the end of the headline.
23525 With argument N not nil or 1, move forward N - 1 lines first."
23526 (interactive "^p")
23527 (let ((origin (point))
23528 (special (pcase org-special-ctrl-a/e
23529 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23530 deactivate-mark)
23531 ;; First move to a visible line.
23532 (if (bound-and-true-p visual-line-mode)
23533 (beginning-of-visual-line n)
23534 (move-beginning-of-line n))
23535 (cond
23536 ;; At a headline, with tags.
23537 ((and special
23538 (save-excursion
23539 (beginning-of-line)
23540 (let ((case-fold-search nil))
23541 (looking-at org-complex-heading-regexp)))
23542 (match-end 5))
23543 (let ((tags (save-excursion
23544 (goto-char (match-beginning 5))
23545 (skip-chars-backward " \t")
23546 (point)))
23547 (visual-end (and (bound-and-true-p visual-line-mode)
23548 (save-excursion
23549 (end-of-visual-line)
23550 (point)))))
23551 ;; If `end-of-visual-line' brings us before end of line or
23552 ;; even tags, i.e., the headline spans over multiple visual
23553 ;; lines, move there.
23554 (cond ((and visual-end
23555 (< visual-end tags)
23556 (<= origin visual-end))
23557 (goto-char visual-end))
23558 ((eq special 'reversed)
23559 (if (and (= origin (line-end-position))
23560 (eq this-command last-command))
23561 (goto-char tags)
23562 (end-of-line)))
23564 (if (or (< origin tags) (= origin (line-end-position)))
23565 (goto-char tags)
23566 (end-of-line))))))
23567 ((bound-and-true-p visual-line-mode)
23568 (let ((bol (line-beginning-position)))
23569 (end-of-visual-line)
23570 ;; If `end-of-visual-line' gets us past the ellipsis at the
23571 ;; end of a line, backtrack and use `end-of-line' instead.
23572 (when (/= bol (line-beginning-position))
23573 (goto-char bol)
23574 (end-of-line))))
23575 (t (end-of-line)))))
23577 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23578 (define-key org-mode-map "\C-e" 'org-end-of-line)
23580 (defun org-backward-sentence (&optional _arg)
23581 "Go to beginning of sentence, or beginning of table field.
23582 This will call `backward-sentence' or `org-table-beginning-of-field',
23583 depending on context."
23584 (interactive)
23585 (let* ((element (org-element-at-point))
23586 (contents-begin (org-element-property :contents-begin element))
23587 (table (org-element-lineage element '(table) t)))
23588 (if (and table
23589 (> (point) contents-begin)
23590 (<= (point) (org-element-property :contents-end table)))
23591 (call-interactively #'org-table-beginning-of-field)
23592 (save-restriction
23593 (when (and contents-begin
23594 (< (point-min) contents-begin)
23595 (> (point) contents-begin))
23596 (narrow-to-region contents-begin
23597 (org-element-property :contents-end element)))
23598 (call-interactively #'backward-sentence)))))
23600 (defun org-forward-sentence (&optional _arg)
23601 "Go to end of sentence, or end of table field.
23602 This will call `forward-sentence' or `org-table-end-of-field',
23603 depending on context."
23604 (interactive)
23605 (if (and (org-at-heading-p)
23606 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23607 (save-restriction
23608 (narrow-to-region (line-beginning-position) (line-end-position))
23609 (call-interactively #'forward-sentence))
23610 (let* ((element (org-element-at-point))
23611 (contents-end (org-element-property :contents-end element))
23612 (table (org-element-lineage element '(table) t)))
23613 (if (and table
23614 (>= (point) (org-element-property :contents-begin table))
23615 (< (point) contents-end))
23616 (call-interactively #'org-table-end-of-field)
23617 (save-restriction
23618 (when (and contents-end
23619 (> (point-max) contents-end)
23620 ;; Skip blank lines between elements.
23621 (< (org-element-property :end element)
23622 (save-excursion (goto-char contents-end)
23623 (skip-chars-forward " \r\t\n"))))
23624 (narrow-to-region (org-element-property :contents-begin element)
23625 contents-end))
23626 (call-interactively #'forward-sentence))))))
23628 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23629 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23631 (defun org-kill-line (&optional _arg)
23632 "Kill line, to tags or end of line."
23633 (interactive)
23634 (cond
23635 ((or (not org-special-ctrl-k)
23636 (bolp)
23637 (not (org-at-heading-p)))
23638 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23639 org-ctrl-k-protect-subtree
23640 (or (eq org-ctrl-k-protect-subtree 'error)
23641 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23642 (user-error "C-k aborted as it would kill a hidden subtree"))
23643 (call-interactively
23644 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23645 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23646 (kill-region (point) (match-beginning 1))
23647 (org-set-tags nil t))
23648 (t (kill-region (point) (point-at-eol)))))
23650 (define-key org-mode-map "\C-k" 'org-kill-line)
23652 (defun org-yank (&optional arg)
23653 "Yank. If the kill is a subtree, treat it specially.
23654 This command will look at the current kill and check if is a single
23655 subtree, or a series of subtrees[1]. If it passes the test, and if the
23656 cursor is at the beginning of a line or after the stars of a currently
23657 empty headline, then the yank is handled specially. How exactly depends
23658 on the value of the following variables.
23660 `org-yank-folded-subtrees'
23661 By default, this variable is non-nil, which results in
23662 subtree(s) being folded after insertion, except if doing so
23663 would swallow text after the yanked text.
23665 `org-yank-adjusted-subtrees'
23666 When non-nil (the default value is nil), the subtree will be
23667 promoted or demoted in order to fit into the local outline tree
23668 structure, which means that the level will be adjusted so that it
23669 becomes the smaller one of the two *visible* surrounding headings.
23671 Any prefix to this command will cause `yank' to be called directly with
23672 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23673 will just
23674 plainly yank the text as it is.
23676 \[1] The test checks if the first non-white line is a heading
23677 and if there are no other headings with fewer stars."
23678 (interactive "P")
23679 (org-yank-generic 'yank arg))
23681 (defun org-yank-generic (command arg)
23682 "Perform some yank-like command.
23684 This function implements the behavior described in the `org-yank'
23685 documentation. However, it has been generalized to work for any
23686 interactive command with similar behavior."
23688 ;; pretend to be command COMMAND
23689 (setq this-command command)
23691 (if arg
23692 (call-interactively command)
23694 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23695 (and (org-kill-is-subtree-p)
23696 (or (bolp)
23697 (and (looking-at "[ \t]*$")
23698 (string-match
23699 "\\`\\*+\\'"
23700 (buffer-substring (point-at-bol) (point)))))))
23701 swallowp)
23702 (cond
23703 ((and subtreep org-yank-folded-subtrees)
23704 (let ((beg (point))
23705 end)
23706 (if (and subtreep org-yank-adjusted-subtrees)
23707 (org-paste-subtree nil nil 'for-yank)
23708 (call-interactively command))
23710 (setq end (point))
23711 (goto-char beg)
23712 (when (and (bolp) subtreep
23713 (not (setq swallowp
23714 (org-yank-folding-would-swallow-text beg end))))
23715 (org-with-limited-levels
23716 (or (looking-at org-outline-regexp)
23717 (re-search-forward org-outline-regexp-bol end t))
23718 (while (and (< (point) end) (looking-at org-outline-regexp))
23719 (outline-hide-subtree)
23720 (org-cycle-show-empty-lines 'folded)
23721 (condition-case nil
23722 (outline-forward-same-level 1)
23723 (error (goto-char end))))))
23724 (when swallowp
23725 (message
23726 "Inserted text not folded because that would swallow text"))
23728 (goto-char end)
23729 (skip-chars-forward " \t\n\r")
23730 (beginning-of-line 1)
23731 (push-mark beg 'nomsg)))
23732 ((and subtreep org-yank-adjusted-subtrees)
23733 (let ((beg (point-at-bol)))
23734 (org-paste-subtree nil nil 'for-yank)
23735 (push-mark beg 'nomsg)))
23737 (call-interactively command))))))
23739 (defun org-yank-folding-would-swallow-text (beg end)
23740 "Would hide-subtree at BEG swallow any text after END?"
23741 (let (level)
23742 (org-with-limited-levels
23743 (save-excursion
23744 (goto-char beg)
23745 (when (or (looking-at org-outline-regexp)
23746 (re-search-forward org-outline-regexp-bol end t))
23747 (setq level (org-outline-level)))
23748 (goto-char end)
23749 (skip-chars-forward " \t\r\n\v\f")
23750 (not (or (eobp)
23751 (and (bolp) (looking-at-p org-outline-regexp)
23752 (<= (org-outline-level) level))))))))
23754 (define-key org-mode-map "\C-y" 'org-yank)
23756 (defun org-truely-invisible-p ()
23757 "Check if point is at a character currently not visible.
23758 This version does not only check the character property, but also
23759 `visible-mode'."
23760 (unless (bound-and-true-p visible-mode)
23761 (org-invisible-p)))
23763 (defun org-invisible-p2 ()
23764 "Check if point is at a character currently not visible.
23766 If the point is at EOL (and not at the beginning of a buffer too),
23767 move it back by one char before doing this check."
23768 (save-excursion
23769 (when (and (eolp) (not (bobp)))
23770 (backward-char 1))
23771 (org-invisible-p)))
23773 (defun org-back-to-heading (&optional invisible-ok)
23774 "Call `outline-back-to-heading', but provide a better error message."
23775 (condition-case nil
23776 (outline-back-to-heading invisible-ok)
23777 (error (error "Before first headline at position %d in buffer %s"
23778 (point) (current-buffer)))))
23780 (defun org-before-first-heading-p ()
23781 "Before first heading?"
23782 (save-excursion
23783 (end-of-line)
23784 (null (re-search-backward org-outline-regexp-bol nil t))))
23786 (defun org-at-heading-p (&optional ignored)
23787 (outline-on-heading-p t))
23789 (defun org-in-commented-heading-p (&optional no-inheritance)
23790 "Non-nil if point is under a commented heading.
23791 This function also checks ancestors of the current headline,
23792 unless optional argument NO-INHERITANCE is non-nil."
23793 (cond
23794 ((org-before-first-heading-p) nil)
23795 ((let ((headline (nth 4 (org-heading-components))))
23796 (and headline
23797 (let ((case-fold-search nil))
23798 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23799 headline)))))
23800 (no-inheritance nil)
23802 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23804 (defun org-at-comment-p nil
23805 "Is cursor in a commented line?"
23806 (save-excursion
23807 (save-match-data
23808 (beginning-of-line)
23809 (looking-at "^[ \t]*# "))))
23811 (defun org-at-drawer-p nil
23812 "Is cursor at a drawer keyword?"
23813 (save-excursion
23814 (move-beginning-of-line 1)
23815 (looking-at org-drawer-regexp)))
23817 (defun org-at-block-p nil
23818 "Is cursor at a block keyword?"
23819 (save-excursion
23820 (move-beginning-of-line 1)
23821 (looking-at org-block-regexp)))
23823 (defun org-point-at-end-of-empty-headline ()
23824 "If point is at the end of an empty headline, return t, else nil.
23825 If the heading only contains a TODO keyword, it is still still considered
23826 empty."
23827 (let ((case-fold-search nil))
23828 (and (looking-at "[ \t]*$")
23829 org-todo-line-regexp
23830 (save-excursion
23831 (beginning-of-line)
23832 (looking-at org-todo-line-regexp)
23833 (string= (match-string 3) "")))))
23835 (defun org-at-heading-or-item-p ()
23836 (or (org-at-heading-p) (org-at-item-p)))
23838 (defun org-at-target-p ()
23839 (or (org-in-regexp org-radio-target-regexp)
23840 (org-in-regexp org-target-regexp)))
23841 ;; Compatibility alias with Org versions < 7.8.03
23842 (defalias 'org-on-target-p 'org-at-target-p)
23844 (defun org-up-heading-all (arg)
23845 "Move to the heading line of which the present line is a subheading.
23846 This function considers both visible and invisible heading lines.
23847 With argument, move up ARG levels."
23848 (outline-up-heading arg t))
23850 (defun org-up-heading-safe ()
23851 "Move to the heading line of which the present line is a subheading.
23852 This version will not throw an error. It will return the level of the
23853 headline found, or nil if no higher level is found.
23855 Also, this function will be a lot faster than `outline-up-heading',
23856 because it relies on stars being the outline starters. This can really
23857 make a significant difference in outlines with very many siblings."
23858 (when (ignore-errors (org-back-to-heading t))
23859 (let ((level-up (1- (funcall outline-level))))
23860 (and (> level-up 0)
23861 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23862 (funcall outline-level)))))
23864 (defun org-first-sibling-p ()
23865 "Is this heading the first child of its parents?"
23866 (interactive)
23867 (let ((re org-outline-regexp-bol)
23868 level l)
23869 (unless (org-at-heading-p t)
23870 (user-error "Not at a heading"))
23871 (setq level (funcall outline-level))
23872 (save-excursion
23873 (if (not (re-search-backward re nil t))
23875 (setq l (funcall outline-level))
23876 (< l level)))))
23878 (defun org-goto-sibling (&optional previous)
23879 "Goto the next sibling, even if it is invisible.
23880 When PREVIOUS is set, go to the previous sibling instead. Returns t
23881 when a sibling was found. When none is found, return nil and don't
23882 move point."
23883 (let ((fun (if previous 're-search-backward 're-search-forward))
23884 (pos (point))
23885 (re org-outline-regexp-bol)
23886 level l)
23887 (when (ignore-errors (org-back-to-heading t))
23888 (setq level (funcall outline-level))
23889 (catch 'exit
23890 (or previous (forward-char 1))
23891 (while (funcall fun re nil t)
23892 (setq l (funcall outline-level))
23893 (when (< l level) (goto-char pos) (throw 'exit nil))
23894 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23895 (goto-char pos)
23896 nil))))
23898 (defun org-show-siblings ()
23899 "Show all siblings of the current headline."
23900 (save-excursion
23901 (while (org-goto-sibling) (org-flag-heading nil)))
23902 (save-excursion
23903 (while (org-goto-sibling 'previous)
23904 (org-flag-heading nil))))
23906 (defun org-goto-first-child ()
23907 "Goto the first child, even if it is invisible.
23908 Return t when a child was found. Otherwise don't move point and
23909 return nil."
23910 (let (level (pos (point)) (re org-outline-regexp-bol))
23911 (when (ignore-errors (org-back-to-heading t))
23912 (setq level (outline-level))
23913 (forward-char 1)
23914 (if (and (re-search-forward re nil t) (> (outline-level) level))
23915 (progn (goto-char (match-beginning 0)) t)
23916 (goto-char pos) nil))))
23918 (defun org-show-hidden-entry ()
23919 "Show an entry where even the heading is hidden."
23920 (save-excursion
23921 (org-show-entry)))
23923 (defun org-flag-heading (flag &optional entry)
23924 "Flag the current heading. FLAG non-nil means make invisible.
23925 When ENTRY is non-nil, show the entire entry."
23926 (save-excursion
23927 (org-back-to-heading t)
23928 ;; Check if we should show the entire entry
23929 (if entry
23930 (progn
23931 (org-show-entry)
23932 (save-excursion
23933 (and (outline-next-heading)
23934 (org-flag-heading nil))))
23935 (outline-flag-region (max (point-min) (1- (point)))
23936 (save-excursion (outline-end-of-heading) (point))
23937 flag))))
23939 (defun org-get-next-sibling ()
23940 "Move to next heading of the same level, and return point.
23941 If there is no such heading, return nil.
23942 This is like outline-next-sibling, but invisible headings are ok."
23943 (let ((level (funcall outline-level)))
23944 (outline-next-heading)
23945 (while (and (not (eobp)) (> (funcall outline-level) level))
23946 (outline-next-heading))
23947 (unless (or (eobp) (< (funcall outline-level) level))
23948 (point))))
23950 (defun org-get-last-sibling ()
23951 "Move to previous heading of the same level, and return point.
23952 If there is no such heading, return nil."
23953 (let ((opoint (point))
23954 (level (funcall outline-level)))
23955 (outline-previous-heading)
23956 (when (and (/= (point) opoint) (outline-on-heading-p t))
23957 (while (and (> (funcall outline-level) level)
23958 (not (bobp)))
23959 (outline-previous-heading))
23960 (unless (< (funcall outline-level) level)
23961 (point)))))
23963 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23964 "Goto to the end of a subtree."
23965 ;; This contains an exact copy of the original function, but it uses
23966 ;; `org-back-to-heading', to make it work also in invisible
23967 ;; trees. And is uses an invisible-ok argument.
23968 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23969 ;; Furthermore, when used inside Org, finding the end of a large subtree
23970 ;; with many children and grandchildren etc, this can be much faster
23971 ;; than the outline version.
23972 (org-back-to-heading invisible-ok)
23973 (let ((first t)
23974 (level (funcall outline-level)))
23975 (if (and (derived-mode-p 'org-mode) (< level 1000))
23976 ;; A true heading (not a plain list item), in Org
23977 ;; This means we can easily find the end by looking
23978 ;; only for the right number of stars. Using a regexp to do
23979 ;; this is so much faster than using a Lisp loop.
23980 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23981 (forward-char 1)
23982 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23983 ;; something else, do it the slow way
23984 (while (and (not (eobp))
23985 (or first (> (funcall outline-level) level)))
23986 (setq first nil)
23987 (outline-next-heading)))
23988 (unless to-heading
23989 (when (memq (preceding-char) '(?\n ?\^M))
23990 ;; Go to end of line before heading
23991 (forward-char -1)
23992 (when (memq (preceding-char) '(?\n ?\^M))
23993 ;; leave blank line before heading
23994 (forward-char -1)))))
23995 (point))
23997 (defun org-end-of-meta-data (&optional full)
23998 "Skip planning line and properties drawer in current entry.
23999 When optional argument FULL is non-nil, also skip empty lines,
24000 clocking lines and regular drawers at the beginning of the
24001 entry."
24002 (org-back-to-heading t)
24003 (forward-line)
24004 (when (looking-at-p org-planning-line-re) (forward-line))
24005 (when (looking-at org-property-drawer-re)
24006 (goto-char (match-end 0))
24007 (forward-line))
24008 (when (and full (not (org-at-heading-p)))
24009 (catch 'exit
24010 (let ((end (save-excursion (outline-next-heading) (point)))
24011 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24012 (while (not (eobp))
24013 (cond ((looking-at-p org-drawer-regexp)
24014 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24015 (forward-line)
24016 (throw 'exit t)))
24017 ((looking-at-p re) (forward-line))
24018 (t (throw 'exit t))))))))
24020 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24021 "Move forward to the ARG'th subheading at same level as this one.
24022 Stop at the first and last subheadings of a superior heading.
24023 Normally this only looks at visible headings, but when INVISIBLE-OK is
24024 non-nil it will also look at invisible ones."
24025 (interactive "p")
24026 (let ((backward? (and arg (< arg 0))))
24027 (if (org-before-first-heading-p)
24028 (if backward? (goto-char (point-min)) (outline-next-heading))
24029 (org-back-to-heading invisible-ok)
24030 (unless backward? (end-of-line)) ;do not match current headline
24031 (let ((level (- (match-end 0) (match-beginning 0) 1))
24032 (f (if backward? #'re-search-backward #'re-search-forward))
24033 (count (if arg (abs arg) 1))
24034 (result (point)))
24035 (while (and (> count 0)
24036 (funcall f org-outline-regexp-bol nil 'move))
24037 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24038 (cond ((< l level) (setq count 0))
24039 ((and (= l level)
24040 (or invisible-ok
24041 (not (org-invisible-p
24042 (line-beginning-position)))))
24043 (cl-decf count)
24044 (when (= l level) (setq result (point)))))))
24045 (goto-char result))
24046 (beginning-of-line))))
24048 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24049 "Move backward to the ARG'th subheading at same level as this one.
24050 Stop at the first and last subheadings of a superior heading."
24051 (interactive "p")
24052 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24054 (defun org-next-visible-heading (arg)
24055 "Move to the next visible heading.
24057 This function wraps `outline-next-visible-heading' with
24058 `org-with-limited-levels' in order to skip over inline tasks and
24059 respect customization of `org-odd-levels-only'."
24060 (interactive "p")
24061 (org-with-limited-levels
24062 (outline-next-visible-heading arg)))
24064 (defun org-previous-visible-heading (arg)
24065 "Move to the previous visible heading.
24067 This function wraps `outline-previous-visible-heading' with
24068 `org-with-limited-levels' in order to skip over inline tasks and
24069 respect customization of `org-odd-levels-only'."
24070 (interactive "p")
24071 (org-with-limited-levels
24072 (outline-previous-visible-heading arg)))
24074 (defun org-next-block (arg &optional backward block-regexp)
24075 "Jump to the next block.
24077 With a prefix argument ARG, jump forward ARG many blocks.
24079 When BACKWARD is non-nil, jump to the previous block.
24081 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24082 Match data is set according to this regexp when the function
24083 returns.
24085 Return point at beginning of the opening line of found block.
24086 Throw an error if no block is found."
24087 (interactive "p")
24088 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24089 (case-fold-search t)
24090 (search-fn (if backward #'re-search-backward #'re-search-forward))
24091 (count (or arg 1))
24092 (origin (point))
24093 last-element)
24094 (if backward (beginning-of-line) (end-of-line))
24095 (while (and (> count 0) (funcall search-fn re nil t))
24096 (let ((element (save-excursion
24097 (goto-char (match-beginning 0))
24098 (save-match-data (org-element-at-point)))))
24099 (when (and (memq (org-element-type element)
24100 '(center-block comment-block dynamic-block
24101 example-block export-block quote-block
24102 special-block src-block verse-block))
24103 (<= (match-beginning 0)
24104 (org-element-property :post-affiliated element)))
24105 (setq last-element element)
24106 (cl-decf count))))
24107 (if (= count 0)
24108 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24109 (save-match-data (org-show-context)))
24110 (goto-char origin)
24111 (user-error "No %s code blocks" (if backward "previous" "further")))))
24113 (defun org-previous-block (arg &optional block-regexp)
24114 "Jump to the previous block.
24115 With a prefix argument ARG, jump backward ARG many source blocks.
24116 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24117 (interactive "p")
24118 (org-next-block arg t block-regexp))
24120 (defun org-forward-paragraph ()
24121 "Move forward to beginning of next paragraph or equivalent.
24123 The function moves point to the beginning of the next visible
24124 structural element, which can be a paragraph, a table, a list
24125 item, etc. It also provides some special moves for convenience:
24127 - On an affiliated keyword, jump to the beginning of the
24128 relative element.
24129 - On an item or a footnote definition, move to the second
24130 element inside, if any.
24131 - On a table or a property drawer, jump after it.
24132 - On a verse or source block, stop after blank lines."
24133 (interactive)
24134 (unless (eobp)
24135 (let* ((deactivate-mark nil)
24136 (element (org-element-at-point))
24137 (type (org-element-type element))
24138 (post-affiliated (org-element-property :post-affiliated element))
24139 (contents-begin (org-element-property :contents-begin element))
24140 (contents-end (org-element-property :contents-end element))
24141 (end (let ((end (org-element-property :end element)) (parent element))
24142 (while (and (setq parent (org-element-property :parent parent))
24143 (= (org-element-property :contents-end parent) end))
24144 (setq end (org-element-property :end parent)))
24145 end)))
24146 (cond ((not element)
24147 (skip-chars-forward " \r\t\n")
24148 (or (eobp) (beginning-of-line)))
24149 ;; On affiliated keywords, move to element's beginning.
24150 ((< (point) post-affiliated)
24151 (goto-char post-affiliated))
24152 ;; At a table row, move to the end of the table. Similarly,
24153 ;; at a node property, move to the end of the property
24154 ;; drawer.
24155 ((memq type '(node-property table-row))
24156 (goto-char (org-element-property
24157 :end (org-element-property :parent element))))
24158 ((memq type '(property-drawer table)) (goto-char end))
24159 ;; Consider blank lines as separators in verse and source
24160 ;; blocks to ease editing.
24161 ((memq type '(src-block verse-block))
24162 (when (eq type 'src-block)
24163 (setq contents-end
24164 (save-excursion (goto-char end)
24165 (skip-chars-backward " \r\t\n")
24166 (line-beginning-position))))
24167 (beginning-of-line)
24168 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24169 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24170 (goto-char end)
24171 (skip-chars-forward " \r\t\n")
24172 (if (= (point) contents-end) (goto-char end)
24173 (beginning-of-line))))
24174 ;; With no contents, just skip element.
24175 ((not contents-begin) (goto-char end))
24176 ;; If contents are invisible, skip the element altogether.
24177 ((org-invisible-p (line-end-position))
24178 (cl-case type
24179 (headline
24180 (org-with-limited-levels (outline-next-visible-heading 1)))
24181 ;; At a plain list, make sure we move to the next item
24182 ;; instead of skipping the whole list.
24183 (plain-list (forward-char)
24184 (org-forward-paragraph))
24185 (otherwise (goto-char end))))
24186 ((>= (point) contents-end) (goto-char end))
24187 ((>= (point) contents-begin)
24188 ;; This can only happen on paragraphs and plain lists.
24189 (cl-case type
24190 (paragraph (goto-char end))
24191 ;; At a plain list, try to move to second element in
24192 ;; first item, if possible.
24193 (plain-list (end-of-line)
24194 (org-forward-paragraph))))
24195 ;; When contents start on the middle of a line (e.g. in
24196 ;; items and footnote definitions), try to reach first
24197 ;; element starting after current line.
24198 ((> (line-end-position) contents-begin)
24199 (end-of-line)
24200 (org-forward-paragraph))
24201 (t (goto-char contents-begin))))))
24203 (defun org-backward-paragraph ()
24204 "Move backward to start of previous paragraph or equivalent.
24206 The function moves point to the beginning of the current
24207 structural element, which can be a paragraph, a table, a list
24208 item, etc., or to the beginning of the previous visible one if
24209 point is already there. It also provides some special moves for
24210 convenience:
24212 - On an affiliated keyword, jump to the first one.
24213 - On a table or a property drawer, move to its beginning.
24214 - On a verse or source block, stop before blank lines."
24215 (interactive)
24216 (unless (bobp)
24217 (let* ((deactivate-mark nil)
24218 (element (org-element-at-point))
24219 (type (org-element-type element))
24220 (contents-begin (org-element-property :contents-begin element))
24221 (contents-end (org-element-property :contents-end element))
24222 (post-affiliated (org-element-property :post-affiliated element))
24223 (begin (org-element-property :begin element)))
24224 (cond
24225 ((not element) (goto-char (point-min)))
24226 ((= (point) begin)
24227 (backward-char)
24228 (org-backward-paragraph))
24229 ((<= (point) post-affiliated) (goto-char begin))
24230 ((memq type '(node-property table-row))
24231 (goto-char (org-element-property
24232 :post-affiliated (org-element-property :parent element))))
24233 ((memq type '(property-drawer table)) (goto-char begin))
24234 ((memq type '(src-block verse-block))
24235 (when (eq type 'src-block)
24236 (setq contents-begin
24237 (save-excursion (goto-char begin) (forward-line) (point))))
24238 (if (= (point) contents-begin) (goto-char post-affiliated)
24239 ;; Inside a verse block, see blank lines as paragraph
24240 ;; separators.
24241 (let ((origin (point)))
24242 (skip-chars-backward " \r\t\n" contents-begin)
24243 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24244 (skip-chars-forward " \r\t\n" origin)
24245 (if (= (point) origin) (goto-char contents-begin)
24246 (beginning-of-line))))))
24247 ((not contents-begin) (goto-char (or post-affiliated begin)))
24248 ((eq type 'paragraph)
24249 (goto-char contents-begin)
24250 ;; When at first paragraph in an item or a footnote definition,
24251 ;; move directly to beginning of line.
24252 (let ((parent-contents
24253 (org-element-property
24254 :contents-begin (org-element-property :parent element))))
24255 (when (and parent-contents (= parent-contents contents-begin))
24256 (beginning-of-line))))
24257 ;; At the end of a greater element, move to the beginning of the
24258 ;; last element within.
24259 ((>= (point) contents-end)
24260 (goto-char (1- contents-end))
24261 (org-backward-paragraph))
24262 (t (goto-char (or post-affiliated begin))))
24263 ;; Ensure we never leave point invisible.
24264 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24266 (defun org-forward-element ()
24267 "Move forward by one element.
24268 Move to the next element at the same level, when possible."
24269 (interactive)
24270 (cond ((eobp) (user-error "Cannot move further down"))
24271 ((org-with-limited-levels (org-at-heading-p))
24272 (let ((origin (point)))
24273 (goto-char (org-end-of-subtree nil t))
24274 (unless (org-with-limited-levels (org-at-heading-p))
24275 (goto-char origin)
24276 (user-error "Cannot move further down"))))
24278 (let* ((elem (org-element-at-point))
24279 (end (org-element-property :end elem))
24280 (parent (org-element-property :parent elem)))
24281 (cond ((and parent (= (org-element-property :contents-end parent) end))
24282 (goto-char (org-element-property :end parent)))
24283 ((integer-or-marker-p end) (goto-char end))
24284 (t (message "No element at point")))))))
24286 (defun org-backward-element ()
24287 "Move backward by one element.
24288 Move to the previous element at the same level, when possible."
24289 (interactive)
24290 (cond ((bobp) (user-error "Cannot move further up"))
24291 ((org-with-limited-levels (org-at-heading-p))
24292 ;; At a headline, move to the previous one, if any, or stay
24293 ;; here.
24294 (let ((origin (point)))
24295 (org-with-limited-levels (org-backward-heading-same-level 1))
24296 ;; When current headline has no sibling above, move to its
24297 ;; parent.
24298 (when (= (point) origin)
24299 (or (org-with-limited-levels (org-up-heading-safe))
24300 (progn (goto-char origin)
24301 (user-error "Cannot move further up"))))))
24303 (let* ((elem (org-element-at-point))
24304 (beg (org-element-property :begin elem)))
24305 (cond
24306 ;; Move to beginning of current element if point isn't
24307 ;; there already.
24308 ((null beg) (message "No element at point"))
24309 ((/= (point) beg) (goto-char beg))
24310 (t (goto-char beg)
24311 (skip-chars-backward " \r\t\n")
24312 (unless (bobp)
24313 (let ((prev (org-element-at-point)))
24314 (goto-char (org-element-property :begin prev))
24315 (while (and (setq prev (org-element-property :parent prev))
24316 (<= (org-element-property :end prev) beg))
24317 (goto-char (org-element-property :begin prev)))))))))))
24319 (defun org-up-element ()
24320 "Move to upper element."
24321 (interactive)
24322 (if (org-with-limited-levels (org-at-heading-p))
24323 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24324 (let* ((elem (org-element-at-point))
24325 (parent (org-element-property :parent elem)))
24326 (if parent (goto-char (org-element-property :begin parent))
24327 (if (org-with-limited-levels (org-before-first-heading-p))
24328 (user-error "No surrounding element")
24329 (org-with-limited-levels (org-back-to-heading)))))))
24331 (defun org-down-element ()
24332 "Move to inner element."
24333 (interactive)
24334 (let ((element (org-element-at-point)))
24335 (cond
24336 ((memq (org-element-type element) '(plain-list table))
24337 (goto-char (org-element-property :contents-begin element))
24338 (forward-char))
24339 ((memq (org-element-type element) org-element-greater-elements)
24340 ;; If contents are hidden, first disclose them.
24341 (when (org-invisible-p (line-end-position)) (org-cycle))
24342 (goto-char (or (org-element-property :contents-begin element)
24343 (user-error "No content for this element"))))
24344 (t (user-error "No inner element")))))
24346 (defun org-drag-element-backward ()
24347 "Move backward element at point."
24348 (interactive)
24349 (let ((elem (or (org-element-at-point)
24350 (user-error "No element at point"))))
24351 (if (eq (org-element-type elem) 'headline)
24352 ;; Preserve point when moving a whole tree, even if point was
24353 ;; on blank lines below the headline.
24354 (let ((offset (skip-chars-backward " \t\n")))
24355 (unwind-protect (org-move-subtree-up)
24356 (forward-char (- offset))))
24357 (let ((prev-elem
24358 (save-excursion
24359 (goto-char (org-element-property :begin elem))
24360 (skip-chars-backward " \r\t\n")
24361 (unless (bobp)
24362 (let* ((beg (org-element-property :begin elem))
24363 (prev (org-element-at-point))
24364 (up prev))
24365 (while (and (setq up (org-element-property :parent up))
24366 (<= (org-element-property :end up) beg))
24367 (setq prev up))
24368 prev)))))
24369 ;; Error out if no previous element or previous element is
24370 ;; a parent of the current one.
24371 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24372 (user-error "Cannot drag element backward")
24373 (let ((pos (point)))
24374 (org-element-swap-A-B prev-elem elem)
24375 (goto-char (+ (org-element-property :begin prev-elem)
24376 (- pos (org-element-property :begin elem))))))))))
24378 (defun org-drag-element-forward ()
24379 "Move forward element at point."
24380 (interactive)
24381 (let* ((pos (point))
24382 (elem (or (org-element-at-point)
24383 (user-error "No element at point"))))
24384 (when (= (point-max) (org-element-property :end elem))
24385 (user-error "Cannot drag element forward"))
24386 (goto-char (org-element-property :end elem))
24387 (let ((next-elem (org-element-at-point)))
24388 (when (or (org-element-nested-p elem next-elem)
24389 (and (eq (org-element-type next-elem) 'headline)
24390 (not (eq (org-element-type elem) 'headline))))
24391 (goto-char pos)
24392 (user-error "Cannot drag element forward"))
24393 ;; Compute new position of point: it's shifted by NEXT-ELEM
24394 ;; body's length (without final blanks) and by the length of
24395 ;; blanks between ELEM and NEXT-ELEM.
24396 (let ((size-next (- (save-excursion
24397 (goto-char (org-element-property :end next-elem))
24398 (skip-chars-backward " \r\t\n")
24399 (forward-line)
24400 ;; Small correction if buffer doesn't end
24401 ;; with a newline character.
24402 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24403 (org-element-property :begin next-elem)))
24404 (size-blank (- (org-element-property :end elem)
24405 (save-excursion
24406 (goto-char (org-element-property :end elem))
24407 (skip-chars-backward " \r\t\n")
24408 (forward-line)
24409 (point)))))
24410 (org-element-swap-A-B elem next-elem)
24411 (goto-char (+ pos size-next size-blank))))))
24413 (defun org-drag-line-forward (arg)
24414 "Drag the line at point ARG lines forward."
24415 (interactive "p")
24416 (dotimes (_ (abs arg))
24417 (let ((c (current-column)))
24418 (if (< 0 arg)
24419 (progn
24420 (beginning-of-line 2)
24421 (transpose-lines 1)
24422 (beginning-of-line 0))
24423 (transpose-lines 1)
24424 (beginning-of-line -1))
24425 (org-move-to-column c))))
24427 (defun org-drag-line-backward (arg)
24428 "Drag the line at point ARG lines backward."
24429 (interactive "p")
24430 (org-drag-line-forward (- arg)))
24432 (defun org-mark-element ()
24433 "Put point at beginning of this element, mark at end.
24435 Interactively, if this command is repeated or (in Transient Mark
24436 mode) if the mark is active, it marks the next element after the
24437 ones already marked."
24438 (interactive)
24439 (let (deactivate-mark)
24440 (if (and (called-interactively-p 'any)
24441 (or (and (eq last-command this-command) (mark t))
24442 (and transient-mark-mode mark-active)))
24443 (set-mark
24444 (save-excursion
24445 (goto-char (mark))
24446 (goto-char (org-element-property :end (org-element-at-point)))))
24447 (let ((element (org-element-at-point)))
24448 (end-of-line)
24449 (push-mark (org-element-property :end element) t t)
24450 (goto-char (org-element-property :begin element))))))
24452 (defun org-narrow-to-element ()
24453 "Narrow buffer to current element."
24454 (interactive)
24455 (let ((elem (org-element-at-point)))
24456 (cond
24457 ((eq (car elem) 'headline)
24458 (narrow-to-region
24459 (org-element-property :begin elem)
24460 (org-element-property :end elem)))
24461 ((memq (car elem) org-element-greater-elements)
24462 (narrow-to-region
24463 (org-element-property :contents-begin elem)
24464 (org-element-property :contents-end elem)))
24466 (narrow-to-region
24467 (org-element-property :begin elem)
24468 (org-element-property :end elem))))))
24470 (defun org-transpose-element ()
24471 "Transpose current and previous elements, keeping blank lines between.
24472 Point is moved after both elements."
24473 (interactive)
24474 (org-skip-whitespace)
24475 (let ((end (org-element-property :end (org-element-at-point))))
24476 (org-drag-element-backward)
24477 (goto-char end)))
24479 (defun org-unindent-buffer ()
24480 "Un-indent the visible part of the buffer.
24481 Relative indentation (between items, inside blocks, etc.) isn't
24482 modified."
24483 (interactive)
24484 (unless (eq major-mode 'org-mode)
24485 (user-error "Cannot un-indent a buffer not in Org mode"))
24486 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24487 (unindent-tree
24488 (lambda (contents)
24489 (dolist (element (reverse contents))
24490 (if (memq (org-element-type element) '(headline section))
24491 (funcall unindent-tree (org-element-contents element))
24492 (save-excursion
24493 (save-restriction
24494 (narrow-to-region
24495 (org-element-property :begin element)
24496 (org-element-property :end element))
24497 (org-do-remove-indentation))))))))
24498 (funcall unindent-tree (org-element-contents parse-tree))))
24500 (defun org-show-children (&optional level)
24501 "Show all direct subheadings of this heading.
24502 Prefix arg LEVEL is how many levels below the current level
24503 should be shown. Default is enough to cause the following
24504 heading to appear."
24505 (interactive "p")
24506 ;; If `orgstruct-mode' is active, use the slower version.
24507 (if orgstruct-mode (call-interactively #'outline-show-children)
24508 (save-excursion
24509 (org-back-to-heading t)
24510 (let* ((current-level (funcall outline-level))
24511 (max-level (org-get-valid-level
24512 current-level
24513 (if level (prefix-numeric-value level) 1)))
24514 (end (save-excursion (org-end-of-subtree t t)))
24515 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24516 (past-first-child nil)
24517 ;; Make sure to skip inlinetasks.
24518 (re (format regexp-fmt
24519 current-level
24520 (cond
24521 ((not (featurep 'org-inlinetask)) "")
24522 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24524 (t (1- org-inlinetask-min-level))))))
24525 ;; Display parent heading.
24526 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24527 (forward-line)
24528 ;; Display children. First child may be deeper than expected
24529 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24530 ;; MAX-LEVEL accordingly.
24531 (while (re-search-forward re end t)
24532 (unless past-first-child
24533 (setq re (format regexp-fmt
24534 current-level
24535 (max (funcall outline-level) max-level)))
24536 (setq past-first-child t))
24537 (outline-flag-region
24538 (line-end-position 0) (line-end-position) nil))))))
24540 (defun org-show-subtree ()
24541 "Show everything after this heading at deeper levels."
24542 (interactive)
24543 (outline-flag-region
24544 (point)
24545 (save-excursion
24546 (org-end-of-subtree t t))
24547 nil))
24549 (defun org-show-entry ()
24550 "Show the body directly following this heading.
24551 Show the heading too, if it is currently invisible."
24552 (interactive)
24553 (save-excursion
24554 (ignore-errors
24555 (org-back-to-heading t)
24556 (outline-flag-region
24557 (max (point-min) (1- (point)))
24558 (save-excursion
24559 (if (re-search-forward
24560 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24561 (match-beginning 1)
24562 (point-max)))
24563 nil)
24564 (org-cycle-hide-drawers 'children))))
24566 (defun org-make-options-regexp (kwds &optional extra)
24567 "Make a regular expression for keyword lines.
24568 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24569 when non-nil, is a regexp matching keywords names."
24570 (concat "^[ \t]*#\\+\\("
24571 (regexp-opt kwds)
24572 (and extra (concat (and kwds "\\|") extra))
24573 "\\):[ \t]*\\(.*\\)"))
24575 ;;;; Integration with and fixes for other packages
24577 ;;; Imenu support
24579 (defvar-local org-imenu-markers nil
24580 "All markers currently used by Imenu.")
24582 (defun org-imenu-new-marker (&optional pos)
24583 "Return a new marker for use by Imenu, and remember the marker."
24584 (let ((m (make-marker)))
24585 (move-marker m (or pos (point)))
24586 (push m org-imenu-markers)
24589 (defun org-imenu-get-tree ()
24590 "Produce the index for Imenu."
24591 (dolist (x org-imenu-markers) (move-marker x nil))
24592 (setq org-imenu-markers nil)
24593 (let* ((case-fold-search nil)
24594 (n org-imenu-depth)
24595 (re (concat "^" (org-get-limited-outline-regexp)))
24596 (subs (make-vector (1+ n) nil))
24597 (last-level 0)
24598 m level head0 head)
24599 (org-with-wide-buffer
24600 (goto-char (point-max))
24601 (while (re-search-backward re nil t)
24602 (setq level (org-reduced-level (funcall outline-level)))
24603 (when (and (<= level n)
24604 (looking-at org-complex-heading-regexp)
24605 (setq head0 (match-string-no-properties 4)))
24606 (setq head (org-link-display-format head0)
24607 m (org-imenu-new-marker))
24608 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24609 (if (>= level last-level)
24610 (push (cons head m) (aref subs level))
24611 (push (cons head (aref subs (1+ level))) (aref subs level))
24612 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24613 (setq last-level level))))
24614 (aref subs 1)))
24616 (eval-after-load "imenu"
24617 '(progn
24618 (add-hook 'imenu-after-jump-hook
24619 (lambda ()
24620 (when (derived-mode-p 'org-mode)
24621 (org-show-context 'org-goto))))))
24623 (defun org-link-display-format (s)
24624 "Replace links in string S with their description.
24625 If there is no description, use the link target."
24626 (save-match-data
24627 (replace-regexp-in-string
24628 org-bracket-link-analytic-regexp
24629 (lambda (m)
24630 (if (match-end 5) (match-string 5 m)
24631 (concat (match-string 1 m) (match-string 3 m))))
24632 s nil t)))
24634 (defun org-toggle-link-display ()
24635 "Toggle the literal or descriptive display of links."
24636 (interactive)
24637 (if org-descriptive-links
24638 (progn (org-remove-from-invisibility-spec '(org-link))
24639 (org-restart-font-lock)
24640 (setq org-descriptive-links nil))
24641 (progn (add-to-invisibility-spec '(org-link))
24642 (org-restart-font-lock)
24643 (setq org-descriptive-links t))))
24645 ;; Speedbar support
24647 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24648 "Overlay marking the agenda restriction line in speedbar.")
24649 (overlay-put org-speedbar-restriction-lock-overlay
24650 'face 'org-agenda-restriction-lock)
24651 (overlay-put org-speedbar-restriction-lock-overlay
24652 'help-echo "Agendas are currently limited to this item.")
24653 (delete-overlay org-speedbar-restriction-lock-overlay)
24655 (defun org-speedbar-set-agenda-restriction ()
24656 "Restrict future agenda commands to the location at point in speedbar.
24657 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24658 (interactive)
24659 (require 'org-agenda)
24660 (let (p m tp np dir txt)
24661 (cond
24662 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24663 'org-imenu t))
24664 (setq m (get-text-property p 'org-imenu-marker))
24665 (with-current-buffer (marker-buffer m)
24666 (goto-char m)
24667 (org-agenda-set-restriction-lock 'subtree)))
24668 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24669 'speedbar-function 'speedbar-find-file))
24670 (setq tp (previous-single-property-change
24671 (1+ p) 'speedbar-function)
24672 np (next-single-property-change
24673 tp 'speedbar-function)
24674 dir (speedbar-line-directory)
24675 txt (buffer-substring-no-properties (or tp (point-min))
24676 (or np (point-max))))
24677 (with-current-buffer (find-file-noselect
24678 (let ((default-directory dir))
24679 (expand-file-name txt)))
24680 (unless (derived-mode-p 'org-mode)
24681 (user-error "Cannot restrict to non-Org mode file"))
24682 (org-agenda-set-restriction-lock 'file)))
24683 (t (user-error "Don't know how to restrict Org mode agenda")))
24684 (move-overlay org-speedbar-restriction-lock-overlay
24685 (point-at-bol) (point-at-eol))
24686 (setq current-prefix-arg nil)
24687 (org-agenda-maybe-redo)))
24689 (defvar speedbar-file-key-map)
24690 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24691 (eval-after-load "speedbar"
24692 '(progn
24693 (speedbar-add-supported-extension ".org")
24694 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24695 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24696 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24697 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24698 (add-hook 'speedbar-visiting-tag-hook
24699 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24701 ;;; Fixes and Hacks for problems with other packages
24703 (defun org--flyspell-object-check-p (element)
24704 "Non-nil when Flyspell can check object at point.
24705 ELEMENT is the element at point."
24706 (let ((object (save-excursion
24707 (when (looking-at-p "\\>") (backward-char))
24708 (org-element-context element))))
24709 (cl-case (org-element-type object)
24710 ;; Prevent checks in links due to keybinding conflict with
24711 ;; Flyspell.
24712 ((code entity export-snippet inline-babel-call
24713 inline-src-block line-break latex-fragment link macro
24714 statistics-cookie target timestamp verbatim)
24715 nil)
24716 (footnote-reference
24717 ;; Only in inline footnotes, within the definition.
24718 (and (eq (org-element-property :type object) 'inline)
24719 (< (save-excursion
24720 (goto-char (org-element-property :begin object))
24721 (search-forward ":" nil t 2))
24722 (point))))
24723 (otherwise t))))
24725 (defun org-mode-flyspell-verify ()
24726 "Function used for `flyspell-generic-check-word-predicate'."
24727 (if (org-at-heading-p)
24728 ;; At a headline or an inlinetask, check title only. This is
24729 ;; faster than relying on `org-element-at-point'.
24730 (and (save-excursion (beginning-of-line)
24731 (and (let ((case-fold-search t))
24732 (not (looking-at-p "\\*+ END[ \t]*$")))
24733 (let ((case-fold-search nil))
24734 (looking-at org-complex-heading-regexp))))
24735 (match-beginning 4)
24736 (>= (point) (match-beginning 4))
24737 (or (not (match-beginning 5))
24738 (< (point) (match-beginning 5))))
24739 (let* ((element (org-element-at-point))
24740 (post-affiliated (org-element-property :post-affiliated element)))
24741 (cond
24742 ;; Ignore checks in all affiliated keywords but captions.
24743 ((< (point) post-affiliated)
24744 (and (save-excursion
24745 (beginning-of-line)
24746 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24747 (> (point) (match-end 0))
24748 (org--flyspell-object-check-p element)))
24749 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24750 ((let ((log (org-log-into-drawer)))
24751 (and log
24752 (let ((drawer (org-element-lineage element '(drawer))))
24753 (and drawer
24754 (eq (compare-strings
24755 log nil nil
24756 (org-element-property :drawer-name drawer) nil nil t)
24757 t)))))
24758 nil)
24760 (cl-case (org-element-type element)
24761 ((comment quote-section) t)
24762 (comment-block
24763 ;; Allow checks between block markers, not on them.
24764 (and (> (line-beginning-position) post-affiliated)
24765 (save-excursion
24766 (end-of-line)
24767 (skip-chars-forward " \r\t\n")
24768 (< (point) (org-element-property :end element)))))
24769 ;; Arbitrary list of keywords where checks are meaningful.
24770 ;; Make sure point is on the value part of the element.
24771 (keyword
24772 (and (member (org-element-property :key element)
24773 '("DESCRIPTION" "TITLE"))
24774 (save-excursion
24775 (search-backward ":" (line-beginning-position) t))))
24776 ;; Check is globally allowed in paragraphs verse blocks and
24777 ;; table rows (after affiliated keywords) but some objects
24778 ;; must not be affected.
24779 ((paragraph table-row verse-block)
24780 (let ((cbeg (org-element-property :contents-begin element))
24781 (cend (org-element-property :contents-end element)))
24782 (and cbeg (>= (point) cbeg) (< (point) cend)
24783 (org--flyspell-object-check-p element))))))))))
24784 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24786 (defun org-remove-flyspell-overlays-in (beg end)
24787 "Remove flyspell overlays in region."
24788 (and (bound-and-true-p flyspell-mode)
24789 (fboundp 'flyspell-delete-region-overlays)
24790 (flyspell-delete-region-overlays beg end)))
24792 (defvar flyspell-delayed-commands)
24793 (eval-after-load "flyspell"
24794 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24796 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24797 (eval-after-load "bookmark"
24798 '(if (boundp 'bookmark-after-jump-hook)
24799 ;; We can use the hook
24800 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24801 ;; Hook not available, use advice
24802 (defadvice bookmark-jump (after org-make-visible activate)
24803 "Make the position visible."
24804 (org-bookmark-jump-unhide))))
24806 ;; Make sure saveplace shows the location if it was hidden
24807 (eval-after-load "saveplace"
24808 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24809 "Make the position visible."
24810 (org-bookmark-jump-unhide)))
24812 ;; Make sure ecb shows the location if it was hidden
24813 (eval-after-load "ecb"
24814 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24815 "Make hierarchy visible when jumping into location from ECB tree buffer."
24816 (when (derived-mode-p 'org-mode)
24817 (org-show-context))))
24819 (defun org-bookmark-jump-unhide ()
24820 "Unhide the current position, to show the bookmark location."
24821 (and (derived-mode-p 'org-mode)
24822 (or (org-invisible-p)
24823 (save-excursion (goto-char (max (point-min) (1- (point))))
24824 (org-invisible-p)))
24825 (org-show-context 'bookmark-jump)))
24827 (defun org-mark-jump-unhide ()
24828 "Make the point visible with `org-show-context' after jumping to the mark."
24829 (when (and (derived-mode-p 'org-mode)
24830 (org-invisible-p))
24831 (org-show-context 'mark-goto)))
24833 (eval-after-load "simple"
24834 '(defadvice pop-to-mark-command (after org-make-visible activate)
24835 "Make the point visible with `org-show-context'."
24836 (org-mark-jump-unhide)))
24838 (eval-after-load "simple"
24839 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24840 "Make the point visible with `org-show-context'."
24841 (org-mark-jump-unhide)))
24843 (eval-after-load "simple"
24844 '(defadvice pop-global-mark (after org-make-visible activate)
24845 "Make the point visible with `org-show-context'."
24846 (org-mark-jump-unhide)))
24848 ;; Make session.el ignore our circular variable
24849 (defvar session-globals-exclude)
24850 (eval-after-load "session"
24851 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24853 ;;;; Finish up
24855 (provide 'org)
24857 (run-hooks 'org-load-hook)
24859 ;;; org.el ends here