Fix curved quotes in error message
[org-mode.git] / lisp / org.el
blobe8e2e4bf828ccbb4c91ee0f503250566974d02cd
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-link-parser "org-element" ())
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-recalculate "org-table" (&optional all noalign))
171 (declare-function org-table-wrap-region "org-table" (arg))
172 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
173 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
174 (declare-function orgtbl-mode "org-table" (&optional arg))
175 (declare-function org-export-get-backend "ox" (name))
176 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
177 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
179 (defsubst org-uniquify (list)
180 "Non-destructively remove duplicate elements from LIST."
181 (let ((res (copy-sequence list))) (delete-dups res)))
183 (defsubst org-get-at-bol (property)
184 "Get text property PROPERTY at the beginning of line."
185 (get-text-property (point-at-bol) property))
187 (defsubst org-trim (s &optional keep-lead)
188 "Remove whitespace at the beginning and the end of string S.
189 When optional argument KEEP-LEAD is non-nil, removing blank lines
190 at the beginning of the string does not affect leading indentation."
191 (replace-regexp-in-string
192 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
193 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
195 ;; load languages based on value of `org-babel-load-languages'
196 (defvar org-babel-load-languages)
198 ;;;###autoload
199 (defun org-babel-do-load-languages (sym value)
200 "Load the languages defined in `org-babel-load-languages'."
201 (set-default sym value)
202 (dolist (pair org-babel-load-languages)
203 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
204 (if active
205 (require (intern (concat "ob-" lang)))
206 (funcall 'fmakunbound
207 (intern (concat "org-babel-execute:" lang)))
208 (funcall 'fmakunbound
209 (intern (concat "org-babel-expand-body:" lang)))))))
211 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
212 ;;;###autoload
213 (defun org-babel-load-file (file &optional compile)
214 "Load Emacs Lisp source code blocks in the Org FILE.
215 This function exports the source code using `org-babel-tangle'
216 and then loads the resulting file using `load-file'. With prefix
217 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
218 file to byte-code before it is loaded."
219 (interactive "fFile to load: \nP")
220 (let* ((age (lambda (file)
221 (float-time
222 (time-subtract (current-time)
223 (nth 5 (or (file-attributes (file-truename file))
224 (file-attributes file)))))))
225 (base-name (file-name-sans-extension file))
226 (exported-file (concat base-name ".el")))
227 ;; tangle if the Org file is newer than the elisp file
228 (unless (and (file-exists-p exported-file)
229 (> (funcall age file) (funcall age exported-file)))
230 ;; Tangle-file traversal returns reversed list of tangled files
231 ;; and we want to evaluate the first target.
232 (setq exported-file
233 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
234 (message "%s %s"
235 (if compile
236 (progn (byte-compile-file exported-file 'load)
237 "Compiled and loaded")
238 (progn (load-file exported-file) "Loaded"))
239 exported-file)))
241 (defcustom org-babel-load-languages '((emacs-lisp . t))
242 "Languages which can be evaluated in Org buffers.
243 This list can be used to load support for any of the languages
244 below, note that each language will depend on a different set of
245 system executables and/or Emacs modes. When a language is
246 \"loaded\", then code blocks in that language can be evaluated
247 with `org-babel-execute-src-block' bound by default to C-c
248 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
249 be set to remove code block evaluation from the C-c C-c
250 keybinding. By default only Emacs Lisp (which has no
251 requirements) is loaded."
252 :group 'org-babel
253 :set 'org-babel-do-load-languages
254 :version "24.1"
255 :type '(alist :tag "Babel Languages"
256 :key-type
257 (choice
258 (const :tag "Awk" awk)
259 (const :tag "C" C)
260 (const :tag "R" R)
261 (const :tag "Asymptote" asymptote)
262 (const :tag "Calc" calc)
263 (const :tag "Clojure" clojure)
264 (const :tag "CSS" css)
265 (const :tag "Ditaa" ditaa)
266 (const :tag "Dot" dot)
267 (const :tag "Emacs Lisp" emacs-lisp)
268 (const :tag "Forth" forth)
269 (const :tag "Fortran" fortran)
270 (const :tag "Gnuplot" gnuplot)
271 (const :tag "Haskell" haskell)
272 (const :tag "IO" io)
273 (const :tag "J" J)
274 (const :tag "Java" java)
275 (const :tag "Javascript" js)
276 (const :tag "LaTeX" latex)
277 (const :tag "Ledger" ledger)
278 (const :tag "Lilypond" lilypond)
279 (const :tag "Lisp" lisp)
280 (const :tag "Makefile" makefile)
281 (const :tag "Maxima" maxima)
282 (const :tag "Matlab" matlab)
283 (const :tag "Mscgen" mscgen)
284 (const :tag "Ocaml" ocaml)
285 (const :tag "Octave" octave)
286 (const :tag "Org" org)
287 (const :tag "Perl" perl)
288 (const :tag "Pico Lisp" picolisp)
289 (const :tag "PlantUML" plantuml)
290 (const :tag "Python" python)
291 (const :tag "Ruby" ruby)
292 (const :tag "Sass" sass)
293 (const :tag "Scala" scala)
294 (const :tag "Scheme" scheme)
295 (const :tag "Screen" screen)
296 (const :tag "Shell Script" shell)
297 (const :tag "Shen" shen)
298 (const :tag "Sql" sql)
299 (const :tag "Sqlite" sqlite)
300 (const :tag "Stan" stan)
301 (const :tag "ebnf2ps" ebnf2ps))
302 :value-type (boolean :tag "Activate" :value t)))
304 ;;;; Customization variables
305 (defcustom org-clone-delete-id nil
306 "Remove ID property of clones of a subtree.
307 When non-nil, clones of a subtree don't inherit the ID property.
308 Otherwise they inherit the ID property with a new unique
309 identifier."
310 :type 'boolean
311 :version "24.1"
312 :group 'org-id)
314 ;;; Version
315 (org-check-version)
317 ;;;###autoload
318 (defun org-version (&optional here full message)
319 "Show the Org version.
320 Interactively, or when MESSAGE is non-nil, show it in echo area.
321 With prefix argument, or when HERE is non-nil, insert it at point.
322 In non-interactive uses, a reduced version string is output unless
323 FULL is given."
324 (interactive (list current-prefix-arg t (not current-prefix-arg)))
325 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
326 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
327 (load-suffixes (list ".el"))
328 (org-install-dir
329 (ignore-errors (org-find-library-dir "org-loaddefs"))))
330 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
331 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
332 (let* ((load-suffixes save-load-suffixes)
333 (release (org-release))
334 (git-version (org-git-version))
335 (version (format "Org mode version %s (%s @ %s)"
336 release
337 git-version
338 (if org-install-dir
339 (if (string= org-dir org-install-dir)
340 org-install-dir
341 (concat "mixed installation! "
342 org-install-dir
343 " and "
344 org-dir))
345 "org-loaddefs.el can not be found!")))
346 (version1 (if full version release)))
347 (when here (insert version1))
348 (when message (message "%s" version1))
349 version1)))
351 (defconst org-version (org-version))
354 ;;; Syntax Constants
356 ;;;; Block
358 (defconst org-block-regexp
359 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
360 "Regular expression for hiding blocks.")
362 (defconst org-dblock-start-re
363 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
364 "Matches the start line of a dynamic block, with parameters.")
366 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
367 "Matches the end of a dynamic block.")
369 ;;;; Clock and Planning
371 (defconst org-clock-string "CLOCK:"
372 "String used as prefix for timestamps clocking work hours on an item.")
374 (defvar org-closed-string "CLOSED:"
375 "String used as the prefix for timestamps logging closing a TODO entry.")
377 (defvar org-deadline-string "DEADLINE:"
378 "String to mark deadline entries.
379 \\<org-mode-map>
380 A deadline is this string, followed by a time stamp. It must be
381 a word, terminated by a colon. You can insert a schedule keyword
382 and a timestamp with `\\[org-deadline]'.")
384 (defvar org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 \\<org-mode-map>
387 A schedule is this string, followed by a time stamp. It must be
388 a word, terminated by a colon. You can insert a schedule keyword
389 and a timestamp with `\\[org-schedule]'.")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (defconst org-comment-string "COMMENT"
529 "Entries starting with this keyword will never be exported.
530 \\<org-mode-map>
531 An entry can be toggled between COMMENT and normal with
532 `\\[org-toggle-comment]'.")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
539 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
546 "Regular expressions for matching embedded LaTeX.")
548 ;;;; Node Property
550 (defconst org-effort-property "Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
554 ;;;; Table
556 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp "^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp "^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
578 ;;;; Timestamp
580 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp-inactive
584 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
585 "Regular expression for fast inactive time stamp matching.")
587 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
588 "Regular expression for fast time stamp matching.")
590 (defconst org-ts-regexp0
591 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.
593 This one does not require the space after the date, so it can be used
594 on a string that terminates immediately after the date.")
596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
597 "Regular expression matching time strings for analysis.")
599 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
600 "Regular expression matching time stamps, with groups.")
602 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
603 "Regular expression matching time stamps (also [..]), with groups.")
605 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tr-regexp-both
609 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
610 "Regular expression matching a time stamp range.")
612 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
613 org-ts-regexp "\\)?")
614 "Regular expression matching a time stamp or time stamp range.")
616 (defconst org-tsr-regexp-both
617 (concat org-ts-regexp-both "\\(--?-?"
618 org-ts-regexp-both "\\)?")
619 "Regular expression matching a time stamp or time stamp range.
620 The time stamps may be either active or inactive.")
622 (defconst org-repeat-re
623 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
624 "Regular expression for specifying repeated events.
625 After a match, group 1 contains the repeat expression.")
627 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
628 "Formats for `format-time-string' which are used for time stamps.")
631 ;;; The custom variables
633 (defgroup org nil
634 "Outline-based notes management and organizer."
635 :tag "Org"
636 :group 'outlines
637 :group 'calendar)
639 (defcustom org-mode-hook nil
640 "Mode hook for Org mode, run after the mode was turned on."
641 :group 'org
642 :type 'hook)
644 (defcustom org-load-hook nil
645 "Hook that is run after org.el has been loaded."
646 :group 'org
647 :type 'hook)
649 (defcustom org-log-buffer-setup-hook nil
650 "Hook that is run after an Org log buffer is created."
651 :group 'org
652 :version "24.1"
653 :type 'hook)
655 (defvar org-modules) ; defined below
656 (defvar org-modules-loaded nil
657 "Have the modules been loaded already?")
659 (defun org-load-modules-maybe (&optional force)
660 "Load all extensions listed in `org-modules'."
661 (when (or force (not org-modules-loaded))
662 (dolist (ext org-modules)
663 (condition-case nil (require ext)
664 (error (message "Problems while trying to load feature `%s'" ext))))
665 (setq org-modules-loaded t)))
667 (defun org-set-modules (var value)
668 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
669 (set var value)
670 (when (featurep 'org)
671 (org-load-modules-maybe 'force)
672 (org-element-cache-reset 'all)))
674 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
675 "Modules that should always be loaded together with org.el.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 You can also use this system to load external packages (i.e. neither Org
682 core modules, nor modules from the CONTRIB directory). Just add symbols
683 to the end of the list. If the package is called org-xyz.el, then you need
684 to add the symbol `xyz', and the package must have a call to:
686 (provide \\='org-xyz)
688 For export specific modules, see also `org-export-backends'."
689 :group 'org
690 :set 'org-set-modules
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type
694 '(set :greedy t
695 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
696 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
697 (const :tag " crypt: Encryption of subtrees" org-crypt)
698 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
699 (const :tag " docview: Links to doc-view buffers" org-docview)
700 (const :tag " eww: Store link to url of eww" org-eww)
701 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
702 (const :tag " habit: Track your consistency with habits" org-habit)
703 (const :tag " id: Global IDs for identifying entries" org-id)
704 (const :tag " info: Links to Info nodes" org-info)
705 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
706 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
707 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
708 (const :tag " mouse: Additional mouse support" org-mouse)
709 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
710 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
711 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
713 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
714 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
715 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
716 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
717 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
718 (const :tag "C collector: Collect properties into tables" org-collector)
719 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
720 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
721 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
722 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
723 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
724 (const :tag "C eval: Include command output as text" org-eval)
725 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
726 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
727 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
728 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
729 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
730 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
731 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
732 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
733 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
734 (const :tag "C man: Support for links to manpages in Org mode" org-man)
735 (const :tag "C mew: Links to Mew folders/messages" org-mew)
736 (const :tag "C mtags: Support for muse-like tags" org-mtags)
737 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
738 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
739 (const :tag "C registry: A registry for Org links" org-registry)
740 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
741 (const :tag "C secretary: Team management with org-mode" org-secretary)
742 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
743 (const :tag "C toc: Table of contents for Org buffer" org-toc)
744 (const :tag "C track: Keep up with Org mode development" org-track)
745 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
746 (const :tag "C vm: Links to VM folders/messages" org-vm)
747 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
748 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
749 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
751 (defvar org-export-registered-backends) ; From ox.el.
752 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
753 (declare-function org-export-backend-name "ox" (backend) t)
754 (defcustom org-export-backends '(ascii html icalendar latex odt)
755 "List of export back-ends that should be always available.
757 If a description starts with <C>, the file is not part of Emacs
758 and loading it will require that you have downloaded and properly
759 installed the Org mode distribution.
761 Unlike to `org-modules', libraries in this list will not be
762 loaded along with Org, but only once the export framework is
763 needed.
765 This variable needs to be set before org.el is loaded. If you
766 need to make a change while Emacs is running, use the customize
767 interface or run the following code, where VAL stands for the new
768 value of the variable, after updating it:
770 (progn
771 (setq org-export-registered-backends
772 (cl-remove-if-not
773 (lambda (backend)
774 (let ((name (org-export-backend-name backend)))
775 (or (memq name val)
776 (catch \\='parentp
777 (dolist (b val)
778 (and (org-export-derived-backend-p b name)
779 (throw \\='parentp t)))))))
780 org-export-registered-backends))
781 (let ((new-list (mapcar #\\='org-export-backend-name
782 org-export-registered-backends)))
783 (dolist (backend val)
784 (cond
785 ((not (load (format \"ox-%s\" backend) t t))
786 (message \"Problems while trying to load export back-end \\=`%s\\='\"
787 backend))
788 ((not (memq backend new-list)) (push backend new-list))))
789 (set-default \\='org-export-backends new-list)))
791 Adding a back-end to this list will also pull the back-end it
792 depends on, if any."
793 :group 'org
794 :group 'org-export
795 :version "26.1"
796 :package-version '(Org . "9.0")
797 :initialize 'custom-initialize-set
798 :set (lambda (var val)
799 (if (not (featurep 'ox)) (set-default var val)
800 ;; Any back-end not required anymore (not present in VAL and not
801 ;; a parent of any back-end in the new value) is removed from the
802 ;; list of registered back-ends.
803 (setq org-export-registered-backends
804 (cl-remove-if-not
805 (lambda (backend)
806 (let ((name (org-export-backend-name backend)))
807 (or (memq name val)
808 (catch 'parentp
809 (dolist (b val)
810 (and (org-export-derived-backend-p b name)
811 (throw 'parentp t)))))))
812 org-export-registered-backends))
813 ;; Now build NEW-LIST of both new back-ends and required
814 ;; parents.
815 (let ((new-list (mapcar #'org-export-backend-name
816 org-export-registered-backends)))
817 (dolist (backend val)
818 (cond
819 ((not (load (format "ox-%s" backend) t t))
820 (message "Problems while trying to load export back-end `%s'"
821 backend))
822 ((not (memq backend new-list)) (push backend new-list))))
823 ;; Set VAR to that list with fixed dependencies.
824 (set-default var new-list))))
825 :type '(set :greedy t
826 (const :tag " ascii Export buffer to ASCII format" ascii)
827 (const :tag " beamer Export buffer to Beamer presentation" beamer)
828 (const :tag " html Export buffer to HTML format" html)
829 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
830 (const :tag " latex Export buffer to LaTeX format" latex)
831 (const :tag " man Export buffer to MAN format" man)
832 (const :tag " md Export buffer to Markdown format" md)
833 (const :tag " odt Export buffer to ODT format" odt)
834 (const :tag " org Export buffer to Org format" org)
835 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
836 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
837 (const :tag "C deck Export buffer to deck.js presentations" deck)
838 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
839 (const :tag "C groff Export buffer to Groff format" groff)
840 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
841 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
842 (const :tag "C s5 Export buffer to s5 presentations" s5)
843 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
845 (eval-after-load 'ox
846 '(dolist (backend org-export-backends)
847 (condition-case nil (require (intern (format "ox-%s" backend)))
848 (error (message "Problems while trying to load export back-end `%s'"
849 backend)))))
851 (defcustom org-support-shift-select nil
852 "Non-nil means make shift-cursor commands select text when possible.
853 \\<org-mode-map>\
855 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
856 start selecting a region, or enlarge regions started in this way.
857 In Org mode, in special contexts, these same keys are used for
858 other purposes, important enough to compete with shift selection.
859 Org tries to balance these needs by supporting `shift-select-mode'
860 outside these special contexts, under control of this variable.
862 The default of this variable is nil, to avoid confusing behavior. Shifted
863 cursor keys will then execute Org commands in the following contexts:
864 - on a headline, changing TODO state (left/right) and priority (up/down)
865 - on a time stamp, changing the time
866 - in a plain list item, changing the bullet type
867 - in a property definition line, switching between allowed values
868 - in the BEGIN line of a clock table (changing the time block).
869 Outside these contexts, the commands will throw an error.
871 When this variable is t and the cursor is not in a special
872 context, Org mode will support shift-selection for making and
873 enlarging regions. To make this more effective, the bullet
874 cycling will no longer happen anywhere in an item line, but only
875 if the cursor is exactly on the bullet.
877 If you set this variable to the symbol `always', then the keys
878 will not be special in headlines, property lines, and item lines,
879 to make shift selection work there as well. If this is what you
880 want, you can use the following alternative commands:
881 `\\[org-todo]' and `\\[org-priority]' \
882 to change TODO state and priority,
883 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
884 can be used to switch TODO sets,
885 `\\[org-ctrl-c-minus]' to cycle item bullet types,
886 and properties can be edited by hand or in column view.
888 However, when the cursor is on a timestamp, shift-cursor commands
889 will still edit the time stamp - this is just too good to give up."
890 :group 'org
891 :type '(choice
892 (const :tag "Never" nil)
893 (const :tag "When outside special context" t)
894 (const :tag "Everywhere except timestamps" always)))
896 (defcustom org-loop-over-headlines-in-active-region nil
897 "Shall some commands act upon headlines in the active region?
899 When set to t, some commands will be performed in all headlines
900 within the active region.
902 When set to `start-level', some commands will be performed in all
903 headlines within the active region, provided that these headlines
904 are of the same level than the first one.
906 When set to a string, those commands will be performed on the
907 matching headlines within the active region. Such string must be
908 a tags/property/todo match as it is used in the agenda tags view.
910 The list of commands is: `org-schedule', `org-deadline',
911 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
912 `org-archive-to-archive-sibling'. The archiving commands skip
913 already archived entries."
914 :type '(choice (const :tag "Don't loop" nil)
915 (const :tag "All headlines in active region" t)
916 (const :tag "In active region, headlines at the same level than the first one" start-level)
917 (string :tag "Tags/Property/Todo matcher"))
918 :version "24.1"
919 :group 'org-todo
920 :group 'org-archive)
922 (defgroup org-startup nil
923 "Options concerning startup of Org mode."
924 :tag "Org Startup"
925 :group 'org)
927 (defcustom org-startup-folded t
928 "Non-nil means entering Org mode will switch to OVERVIEW.
930 This can also be configured on a per-file basis by adding one of
931 the following lines anywhere in the buffer:
933 #+STARTUP: fold (or `overview', this is equivalent)
934 #+STARTUP: nofold (or `showall', this is equivalent)
935 #+STARTUP: content
936 #+STARTUP: showeverything
938 Set `org-agenda-inhibit-startup' to a non-nil value if you want
939 to ignore this option when Org opens agenda files for the first
940 time."
941 :group 'org-startup
942 :type '(choice
943 (const :tag "nofold: show all" nil)
944 (const :tag "fold: overview" t)
945 (const :tag "content: all headlines" content)
946 (const :tag "show everything, even drawers" showeverything)))
948 (defcustom org-startup-truncated t
949 "Non-nil means entering Org mode will set `truncate-lines'.
950 This is useful since some lines containing links can be very long and
951 uninteresting. Also tables look terrible when wrapped.
953 The variable `org-startup-truncated' allows to configure
954 truncation for Org mode different to the other modes that use the
955 variable `truncate-lines' and as a shortcut instead of putting
956 the variable `truncate-lines' into the `org-mode-hook'. If one
957 wants to configure truncation for Org mode not statically but
958 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
959 the variable `truncate-lines' has to be used because in such a
960 case it is too late to set the variable `org-startup-truncated'."
961 :group 'org-startup
962 :type 'boolean)
964 (defcustom org-startup-indented nil
965 "Non-nil means turn on `org-indent-mode' on startup.
966 This can also be configured on a per-file basis by adding one of
967 the following lines anywhere in the buffer:
969 #+STARTUP: indent
970 #+STARTUP: noindent"
971 :group 'org-structure
972 :type '(choice
973 (const :tag "Not" nil)
974 (const :tag "Globally (slow on startup in large files)" t)))
976 (defcustom org-use-sub-superscripts t
977 "Non-nil means interpret \"_\" and \"^\" for display.
979 If you want to control how Org exports those characters, see
980 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
981 used to be an alias for `org-export-with-sub-superscripts' in
982 Org <8.0, it is not anymore.
984 When this option is turned on, you can use TeX-like syntax for
985 sub- and superscripts within the buffer. Several characters after
986 \"_\" or \"^\" will be considered as a single item - so grouping
987 with {} is normally not needed. For example, the following things
988 will be parsed as single sub- or superscripts:
990 10^24 or 10^tau several digits will be considered 1 item.
991 10^-12 or 10^-tau a leading sign with digits or a word
992 x^2-y^3 will be read as x^2 - y^3, because items are
993 terminated by almost any nonword/nondigit char.
994 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
996 Still, ambiguity is possible. So when in doubt, use {} to enclose
997 the sub/superscript. If you set this variable to the symbol `{}',
998 the braces are *required* in order to trigger interpretations as
999 sub/superscript. This can be helpful in documents that need \"_\"
1000 frequently in plain text."
1001 :group 'org-startup
1002 :version "24.4"
1003 :package-version '(Org . "8.0")
1004 :type '(choice
1005 (const :tag "Always interpret" t)
1006 (const :tag "Only with braces" {})
1007 (const :tag "Never interpret" nil)))
1009 (defcustom org-startup-with-beamer-mode nil
1010 "Non-nil means turn on `org-beamer-mode' on startup.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1014 #+STARTUP: beamer"
1015 :group 'org-startup
1016 :version "24.1"
1017 :type 'boolean)
1019 (defcustom org-startup-align-all-tables nil
1020 "Non-nil means align all tables when visiting a file.
1021 This is useful when the column width in tables is forced with <N> cookies
1022 in table fields. Such tables will look correct only after the first re-align.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: align
1026 #+STARTUP: noalign"
1027 :group 'org-startup
1028 :type 'boolean)
1030 (defcustom org-startup-with-inline-images nil
1031 "Non-nil means show inline images when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: inlineimages
1035 #+STARTUP: noinlineimages"
1036 :group 'org-startup
1037 :version "24.1"
1038 :type 'boolean)
1040 (defcustom org-startup-with-latex-preview nil
1041 "Non-nil means preview LaTeX fragments when loading a new Org file.
1043 This can also be configured on a per-file basis by adding one of
1044 the following lines anywhere in the buffer:
1045 #+STARTUP: latexpreview
1046 #+STARTUP: nolatexpreview"
1047 :group 'org-startup
1048 :version "24.4"
1049 :package-version '(Org . "8.0")
1050 :type 'boolean)
1052 (defcustom org-insert-mode-line-in-empty-file nil
1053 "Non-nil means insert the first line setting Org mode in empty files.
1054 When the function `org-mode' is called interactively in an empty file, this
1055 normally means that the file name does not automatically trigger Org mode.
1056 To ensure that the file will always be in Org mode in the future, a
1057 line enforcing Org mode will be inserted into the buffer, if this option
1058 has been set."
1059 :group 'org-startup
1060 :type 'boolean)
1062 (defcustom org-replace-disputed-keys nil
1063 "Non-nil means use alternative key bindings for some keys.
1064 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1065 These keys are also used by other packages like shift-selection-mode'
1066 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1067 If you want to use Org mode together with one of these other modes,
1068 or more generally if you would like to move some Org mode commands to
1069 other keys, set this variable and configure the keys with the variable
1070 `org-disputed-keys'.
1072 This option is only relevant at load-time of Org mode, and must be set
1073 *before* org.el is loaded. Changing it requires a restart of Emacs to
1074 become effective."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defcustom org-use-extra-keys nil
1079 "Non-nil means use extra key sequence definitions for certain commands.
1080 This happens automatically if `window-system' is nil. This
1081 variable lets you do the same manually. You must set it before
1082 loading Org."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1088 (defcustom org-disputed-keys
1089 '(([(shift up)] . [(meta p)])
1090 ([(shift down)] . [(meta n)])
1091 ([(shift left)] . [(meta -)])
1092 ([(shift right)] . [(meta +)])
1093 ([(control shift right)] . [(meta shift +)])
1094 ([(control shift left)] . [(meta shift -)]))
1095 "Keys for which Org mode and other modes compete.
1096 This is an alist, cars are the default keys, second element specifies
1097 the alternative to use when `org-replace-disputed-keys' is t.
1099 Keys can be specified in any syntax supported by `define-key'.
1100 The value of this option takes effect only at Org mode startup,
1101 therefore you'll have to restart Emacs to apply it after changing."
1102 :group 'org-startup
1103 :type 'alist)
1105 (defun org-key (key)
1106 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1107 Or return the original if not disputed."
1108 (when org-replace-disputed-keys
1109 (let* ((nkey (key-description key))
1110 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 key)
1115 (defun org-defkey (keymap key def)
1116 "Define a key, possibly translated, as returned by `org-key'."
1117 (define-key keymap (org-key key) def))
1119 (defcustom org-ellipsis nil
1120 "The ellipsis to use in the Org mode outline.
1122 When nil, just use the standard three dots. When a non-empty string,
1123 use that string instead.
1125 The change affects only Org mode (which will then use its own display table).
1126 Changing this requires executing `\\[org-mode]' in a buffer to become
1127 effective."
1128 :group 'org-startup
1129 :type '(choice (const :tag "Default" nil)
1130 (string :tag "String" :value "...#"))
1131 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1133 (defvar org-display-table nil
1134 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1136 (defgroup org-keywords nil
1137 "Keywords in Org mode."
1138 :tag "Org Keywords"
1139 :group 'org)
1141 (defcustom org-closed-keep-when-no-todo nil
1142 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1143 :group 'org-todo
1144 :group 'org-keywords
1145 :version "24.4"
1146 :package-version '(Org . "8.0")
1147 :type 'boolean)
1149 (defgroup org-structure nil
1150 "Options concerning the general structure of Org files."
1151 :tag "Org Structure"
1152 :group 'org)
1154 (defgroup org-reveal-location nil
1155 "Options about how to make context of a location visible."
1156 :tag "Org Reveal Location"
1157 :group 'org-structure)
1159 (defcustom org-show-context-detail '((agenda . local)
1160 (bookmark-jump . lineage)
1161 (isearch . lineage)
1162 (default . ancestors))
1163 "Alist between context and visibility span when revealing a location.
1165 \\<org-mode-map>Some actions may move point into invisible
1166 locations. As a consequence, Org always expose a neighborhood
1167 around point. How much is shown depends on the initial action,
1168 or context. Valid contexts are
1170 agenda when exposing an entry from the agenda
1171 org-goto when using the command `org-goto' (`\\[org-goto]')
1172 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1173 tags-tree when constructing a sparse tree based on tags matches
1174 link-search when exposing search matches associated with a link
1175 mark-goto when exposing the jump goal of a mark
1176 bookmark-jump when exposing a bookmark location
1177 isearch when exiting from an incremental search
1178 default default for all contexts not set explicitly
1180 Allowed visibility spans are
1182 minimal show current headline; if point is not on headline,
1183 also show entry
1185 local show current headline, entry and next headline
1187 ancestors show current headline and its direct ancestors; if
1188 point is not on headline, also show entry
1190 lineage show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and first child
1194 tree show current headline, its direct ancestors and all
1195 their children; if point is not on headline, also show
1196 entry and all children
1198 canonical show current headline, its direct ancestors along with
1199 their entries and children; if point is not located on
1200 the headline, also show current entry and all children
1202 As special cases, a nil or t value means show all contexts in
1203 `minimal' or `canonical' view, respectively.
1205 Some views can make displayed information very compact, but also
1206 make it harder to edit the location of the match. In such
1207 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1208 more context."
1209 :group 'org-reveal-location
1210 :version "26.1"
1211 :package-version '(Org . "9.0")
1212 :type '(choice
1213 (const :tag "Canonical" t)
1214 (const :tag "Minimal" nil)
1215 (repeat :greedy t :tag "Individual contexts"
1216 (cons
1217 (choice :tag "Context"
1218 (const agenda)
1219 (const org-goto)
1220 (const occur-tree)
1221 (const tags-tree)
1222 (const link-search)
1223 (const mark-goto)
1224 (const bookmark-jump)
1225 (const isearch)
1226 (const default))
1227 (choice :tag "Detail level"
1228 (const minimal)
1229 (const local)
1230 (const ancestors)
1231 (const lineage)
1232 (const tree)
1233 (const canonical))))))
1235 (defcustom org-indirect-buffer-display 'other-window
1236 "How should indirect tree buffers be displayed?
1238 This applies to indirect buffers created with the commands
1239 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1241 Valid values are:
1242 current-window Display in the current window
1243 other-window Just display in another window.
1244 dedicated-frame Create one new frame, and re-use it each time.
1245 new-frame Make a new frame each time. Note that in this case
1246 previously-made indirect buffers are kept, and you need to
1247 kill these buffers yourself."
1248 :group 'org-structure
1249 :group 'org-agenda-windows
1250 :type '(choice
1251 (const :tag "In current window" current-window)
1252 (const :tag "In current frame, other window" other-window)
1253 (const :tag "Each time a new frame" new-frame)
1254 (const :tag "One dedicated frame" dedicated-frame)))
1256 (defcustom org-use-speed-commands nil
1257 "Non-nil means activate single letter commands at beginning of a headline.
1258 This may also be a function to test for appropriate locations where speed
1259 commands should be active.
1261 For example, to activate speed commands when the point is on any
1262 star at the beginning of the headline, you can do this:
1264 (setq org-use-speed-commands
1265 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1266 :group 'org-structure
1267 :type '(choice
1268 (const :tag "Never" nil)
1269 (const :tag "At beginning of headline stars" t)
1270 (function)))
1272 (defcustom org-speed-commands-user nil
1273 "Alist of additional speed commands.
1274 This list will be checked before `org-speed-commands-default'
1275 when the variable `org-use-speed-commands' is non-nil
1276 and when the cursor is at the beginning of a headline.
1277 The car if each entry is a string with a single letter, which must
1278 be assigned to `self-insert-command' in the global map.
1279 The cdr is either a command to be called interactively, a function
1280 to be called, or a form to be evaluated.
1281 An entry that is just a list with a single string will be interpreted
1282 as a descriptive headline that will be added when listing the speed
1283 commands in the Help buffer using the `?' speed command."
1284 :group 'org-structure
1285 :type '(repeat :value ("k" . ignore)
1286 (choice :value ("k" . ignore)
1287 (list :tag "Descriptive Headline" (string :tag "Headline"))
1288 (cons :tag "Letter and Command"
1289 (string :tag "Command letter")
1290 (choice
1291 (function)
1292 (sexp))))))
1294 (defcustom org-bookmark-names-plist
1295 '(:last-capture "org-capture-last-stored"
1296 :last-refile "org-refile-last-stored"
1297 :last-capture-marker "org-capture-last-stored-marker")
1298 "Names for bookmarks automatically set by some Org commands.
1299 This can provide strings as names for a number of bookmarks Org sets
1300 automatically. The following keys are currently implemented:
1301 :last-capture
1302 :last-capture-marker
1303 :last-refile
1304 When a key does not show up in the property list, the corresponding bookmark
1305 is not set."
1306 :group 'org-structure
1307 :type 'plist)
1309 (defgroup org-cycle nil
1310 "Options concerning visibility cycling in Org mode."
1311 :tag "Org Cycle"
1312 :group 'org-structure)
1314 (defcustom org-cycle-skip-children-state-if-no-children t
1315 "Non-nil means skip CHILDREN state in entries that don't have any."
1316 :group 'org-cycle
1317 :type 'boolean)
1319 (defcustom org-cycle-max-level nil
1320 "Maximum level which should still be subject to visibility cycling.
1321 Levels higher than this will, for cycling, be treated as text, not a headline.
1322 When `org-odd-levels-only' is set, a value of N in this variable actually
1323 means 2N-1 stars as the limiting headline.
1324 When nil, cycle all levels.
1325 Note that the limiting level of cycling is also influenced by
1326 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1327 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1328 than its value."
1329 :group 'org-cycle
1330 :type '(choice
1331 (const :tag "No limit" nil)
1332 (integer :tag "Maximum level")))
1334 (defcustom org-hide-block-startup nil
1335 "Non-nil means entering Org mode will fold all blocks.
1336 This can also be set in on a per-file basis with
1338 #+STARTUP: hideblocks
1339 #+STARTUP: showblocks"
1340 :group 'org-startup
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-global-at-bob nil
1345 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1347 This makes it possible to do global cycling without having to use `S-TAB'
1348 or `\\[universal-argument] TAB'. For this special case to work, the first \
1349 line of the buffer
1350 must not be a headline -- it may be empty or some other text.
1352 When used in this way, `org-cycle-hook' is disabled temporarily to make
1353 sure the cursor stays at the beginning of the buffer.
1355 When this option is nil, don't do anything special at the beginning of
1356 the buffer."
1357 :group 'org-cycle
1358 :type 'boolean)
1360 (defcustom org-cycle-level-after-item/entry-creation t
1361 "Non-nil means cycle entry level or item indentation in new empty entries.
1363 When the cursor is at the end of an empty headline, i.e., with only stars
1364 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1365 and then all possible ancestor states, before returning to the original state.
1366 This makes data entry extremely fast: M-RET to create a new headline,
1367 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1369 When the cursor is at the end of an empty plain list item, one TAB will
1370 make it a subitem, two or more tabs will back up to make this an item
1371 higher up in the item hierarchy."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-emulate-tab t
1376 "Where should `org-cycle' emulate TAB.
1377 nil Never
1378 white Only in completely white lines
1379 whitestart Only at the beginning of lines, before the first non-white char
1380 t Everywhere except in headlines
1381 exc-hl-bol Everywhere except at the start of a headline
1382 If TAB is used in a place where it does not emulate TAB, the current subtree
1383 visibility is cycled."
1384 :group 'org-cycle
1385 :type '(choice (const :tag "Never" nil)
1386 (const :tag "Only in completely white lines" white)
1387 (const :tag "Before first char in a line" whitestart)
1388 (const :tag "Everywhere except in headlines" t)
1389 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1391 (defcustom org-cycle-separator-lines 2
1392 "Number of empty lines needed to keep an empty line between collapsed trees.
1393 If you leave an empty line between the end of a subtree and the following
1394 headline, this empty line is hidden when the subtree is folded.
1395 Org mode will leave (exactly) one empty line visible if the number of
1396 empty lines is equal or larger to the number given in this variable.
1397 So the default 2 means at least 2 empty lines after the end of a subtree
1398 are needed to produce free space between a collapsed subtree and the
1399 following headline.
1401 If the number is negative, and the number of empty lines is at least -N,
1402 all empty lines are shown.
1404 Special case: when 0, never leave empty lines in collapsed view."
1405 :group 'org-cycle
1406 :type 'integer)
1407 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1409 (defcustom org-pre-cycle-hook nil
1410 "Hook that is run before visibility cycling is happening.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that will be set right after running this hook. The
1413 argument is a symbol. Before a global state change, it can have the values
1414 `overview', `content', or `all'. Before a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook)
1419 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1420 org-cycle-hide-drawers
1421 org-cycle-show-empty-lines
1422 org-optimize-window-after-visibility-change)
1423 "Hook that is run after `org-cycle' has changed the buffer visibility.
1424 The function(s) in this hook must accept a single argument which indicates
1425 the new state that was set by the most recent `org-cycle' command. The
1426 argument is a symbol. After a global state change, it can have the values
1427 `overview', `contents', or `all'. After a local state change, it can have
1428 the values `folded', `children', or `subtree'."
1429 :group 'org-cycle
1430 :type 'hook
1431 :version "26.1"
1432 :package-version '(Org . "8.3"))
1434 (defgroup org-edit-structure nil
1435 "Options concerning structure editing in Org mode."
1436 :tag "Org Edit Structure"
1437 :group 'org-structure)
1439 (defcustom org-odd-levels-only nil
1440 "Non-nil means skip even levels and only use odd levels for the outline.
1441 This has the effect that two stars are being added/taken away in
1442 promotion/demotion commands. It also influences how levels are
1443 handled by the exporters.
1444 Changing it requires restart of `font-lock-mode' to become effective
1445 for fontification also in regions already fontified.
1446 You may also set this on a per-file basis by adding one of the following
1447 lines to the buffer:
1449 #+STARTUP: odd
1450 #+STARTUP: oddeven"
1451 :group 'org-edit-structure
1452 :group 'org-appearance
1453 :type 'boolean)
1455 (defcustom org-adapt-indentation t
1456 "Non-nil means adapt indentation to outline node level.
1458 When this variable is set, Org assumes that you write outlines by
1459 indenting text in each node to align with the headline (after the
1460 stars). The following issues are influenced by this variable:
1462 - The indentation is increased by one space in a demotion
1463 command, and decreased by one in a promotion command. However,
1464 in the latter case, if shifting some line in the entry body
1465 would alter document structure (e.g., insert a new headline),
1466 indentation is not changed at all.
1468 - Property drawers and planning information is inserted indented
1469 when this variable is set. When nil, they will not be indented.
1471 - TAB indents a line relative to current level. The lines below
1472 a headline will be indented when this variable is set.
1474 Note that this is all about true indentation, by adding and
1475 removing space characters. See also `org-indent.el' which does
1476 level-dependent indentation in a virtual way, i.e. at display
1477 time in Emacs."
1478 :group 'org-edit-structure
1479 :type 'boolean)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 \\<org-mode-map>
1619 When nil, the new heading is created directly after the current line.
1620 The commands `\\[org-insert-heading-respect-content]' and \
1621 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1622 for the duration of the command."
1623 :group 'org-structure
1624 :type 'boolean)
1626 (defcustom org-blank-before-new-entry '((heading . auto)
1627 (plain-list-item . auto))
1628 "Should `org-insert-heading' leave a blank line before new heading/item?
1629 The value is an alist, with `heading' and `plain-list-item' as CAR,
1630 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1631 which case Org will look at the surrounding headings/items and try to
1632 make an intelligent decision whether to insert a blank line or not."
1633 :group 'org-edit-structure
1634 :type '(list
1635 (cons (const heading)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))
1639 (cons (const plain-list-item)
1640 (choice (const :tag "Never" nil)
1641 (const :tag "Always" t)
1642 (const :tag "Auto" auto)))))
1644 (defcustom org-insert-heading-hook nil
1645 "Hook being run after inserting a new heading."
1646 :group 'org-edit-structure
1647 :type 'hook)
1649 (defcustom org-enable-fixed-width-editor t
1650 "Non-nil means lines starting with \":\" are treated as fixed-width.
1651 This currently only means they are never auto-wrapped.
1652 When nil, such lines will be treated like ordinary lines."
1653 :group 'org-edit-structure
1654 :type 'boolean)
1656 (defcustom org-goto-auto-isearch t
1657 "Non-nil means typing characters in `org-goto' starts incremental search.
1658 When nil, you can use these keybindings to navigate the buffer:
1660 q Quit the org-goto interface
1661 n Go to the next visible heading
1662 p Go to the previous visible heading
1663 f Go one heading forward on same level
1664 b Go one heading backward on same level
1665 u Go one heading up"
1666 :group 'org-edit-structure
1667 :type 'boolean)
1669 (defgroup org-sparse-trees nil
1670 "Options concerning sparse trees in Org mode."
1671 :tag "Org Sparse Trees"
1672 :group 'org-structure)
1674 (defcustom org-highlight-sparse-tree-matches t
1675 "Non-nil means highlight all matches that define a sparse tree.
1676 The highlights will automatically disappear the next time the buffer is
1677 changed by an edit command."
1678 :group 'org-sparse-trees
1679 :type 'boolean)
1681 (defcustom org-remove-highlights-with-change t
1682 "Non-nil means any change to the buffer will remove temporary highlights.
1683 \\<org-mode-map>\
1684 Such highlights are created by `org-occur' and `org-clock-display'.
1685 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1686 to get rid of the highlights.
1687 The highlights created by `org-toggle-latex-fragment' always need
1688 `\\[org-toggle-latex-fragment]' to be removed."
1689 :group 'org-sparse-trees
1690 :group 'org-time
1691 :type 'boolean)
1693 (defcustom org-occur-case-fold-search t
1694 "Non-nil means `org-occur' should be case-insensitive.
1695 If set to `smart' the search will be case-insensitive only if it
1696 doesn't specify any upper case character."
1697 :group 'org-sparse-trees
1698 :version "26.1"
1699 :type '(choice
1700 (const :tag "Case-sensitive" nil)
1701 (const :tag "Case-insensitive" t)
1702 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1704 (defcustom org-occur-hook '(org-first-headline-recenter)
1705 "Hook that is run after `org-occur' has constructed a sparse tree.
1706 This can be used to recenter the window to show as much of the structure
1707 as possible."
1708 :group 'org-sparse-trees
1709 :type 'hook)
1711 (defgroup org-imenu-and-speedbar nil
1712 "Options concerning imenu and speedbar in Org mode."
1713 :tag "Org Imenu and Speedbar"
1714 :group 'org-structure)
1716 (defcustom org-imenu-depth 2
1717 "The maximum level for Imenu access to Org headlines.
1718 This also applied for speedbar access."
1719 :group 'org-imenu-and-speedbar
1720 :type 'integer)
1722 (defgroup org-table nil
1723 "Options concerning tables in Org mode."
1724 :tag "Org Table"
1725 :group 'org)
1727 (defcustom org-enable-table-editor 'optimized
1728 "Non-nil means lines starting with \"|\" are handled by the table editor.
1729 When nil, such lines will be treated like ordinary lines.
1731 When equal to the symbol `optimized', the table editor will be optimized to
1732 do the following:
1733 - Automatic overwrite mode in front of whitespace in table fields.
1734 This makes the structure of the table stay in tact as long as the edited
1735 field does not exceed the column width.
1736 - Minimize the number of realigns. Normally, the table is aligned each time
1737 TAB or RET are pressed to move to another field. With optimization this
1738 happens only if changes to a field might have changed the column width.
1739 Optimization requires replacing the functions `self-insert-command',
1740 `delete-char', and `backward-delete-char' in Org buffers, with a
1741 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1742 good at guessing when a re-align will be necessary, but you can always
1743 force one with `\\[org-ctrl-c-ctrl-c]'.
1745 If you would like to use the optimized version in Org mode, but the
1746 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1748 This variable can be used to turn on and off the table editor during a session,
1749 but in order to toggle optimization, a restart is required.
1751 See also the variable `org-table-auto-blank-field'."
1752 :group 'org-table
1753 :type '(choice
1754 (const :tag "off" nil)
1755 (const :tag "on" t)
1756 (const :tag "on, optimized" optimized)))
1758 (defcustom org-self-insert-cluster-for-undo nil
1759 "Non-nil means cluster self-insert commands for undo when possible.
1760 If this is set, then, like in the Emacs command loop, 20 consecutive
1761 characters will be undone together.
1762 This is configurable, because there is some impact on typing performance."
1763 :group 'org-table
1764 :type 'boolean)
1766 (defcustom org-table-tab-recognizes-table.el t
1767 "Non-nil means TAB will automatically notice a table.el table.
1768 When it sees such a table, it moves point into it and - if necessary -
1769 calls `table-recognize-table'."
1770 :group 'org-table-editing
1771 :type 'boolean)
1773 (defgroup org-link nil
1774 "Options concerning links in Org mode."
1775 :tag "Org Link"
1776 :group 'org)
1778 (defvar-local org-link-abbrev-alist-local nil
1779 "Buffer-local version of `org-link-abbrev-alist', which see.
1780 The value of this is taken from the #+LINK lines.")
1782 (defcustom org-link-parameters
1783 '(("doi" :follow org--open-doi-link)
1784 ("elisp" :follow org--open-elisp-link)
1785 ("file" :complete org-file-complete-link)
1786 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1787 ("help" :follow org--open-help-link)
1788 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1789 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1790 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1791 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1792 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1793 ("shell" :follow org--open-shell-link))
1794 "An alist of properties that defines all the links in Org mode.
1795 The key in each association is a string of the link type.
1796 Subsequent optional elements make up a p-list of link properties.
1798 :follow - A function that takes the link path as an argument.
1800 :export - A function that takes the link path, description and
1801 export-backend as arguments.
1803 :store - A function responsible for storing the link. See the
1804 function `org-store-link-functions'.
1806 :complete - A function that inserts a link with completion. The
1807 function takes one optional prefix arg.
1809 :face - A face for the link, or a function that returns a face.
1810 The function takes one argument which is the link path. The
1811 default face is `org-link'.
1813 :mouse-face - The mouse-face. The default is `highlight'.
1815 :display - `full' will not fold the link in descriptive
1816 display. Default is `org-link'.
1818 :help-echo - A string or function that takes (window object position)
1819 as arguments and returns a string.
1821 :keymap - A keymap that is active on the link. The default is
1822 `org-mouse-map'.
1824 :htmlize-link - A function for the htmlize-link. Defaults
1825 to (list :uri \"type:path\")
1827 :activate-func - A function to run at the end of font-lock
1828 activation. The function must accept (link-start link-end path bracketp)
1829 as arguments."
1830 :group 'org-link
1831 :type '(alist :tag "Link display parameters"
1832 :value-type plist))
1834 (defun org-link-get-parameter (type key)
1835 "Get TYPE link property for KEY.
1836 TYPE is a string and KEY is a plist keyword."
1837 (plist-get
1838 (cdr (assoc type org-link-parameters))
1839 key))
1841 (defun org-link-set-parameters (type &rest parameters)
1842 "Set link TYPE properties to PARAMETERS.
1843 PARAMETERS should be :key val pairs."
1844 (let ((data (assoc type org-link-parameters)))
1845 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1846 (push (cons type parameters) org-link-parameters)
1847 (org-make-link-regexps)
1848 (org-element-update-syntax))))
1850 (defun org-link-types ()
1851 "Return a list of known link types."
1852 (mapcar #'car org-link-parameters))
1854 (defcustom org-link-abbrev-alist nil
1855 "Alist of link abbreviations.
1856 The car of each element is a string, to be replaced at the start of a link.
1857 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1858 links in Org buffers can have an optional tag after a double colon, e.g.,
1860 [[linkkey:tag][description]]
1862 The `linkkey' must be a single word, starting with a letter, followed
1863 by letters, numbers, `-' or `_'.
1865 If REPLACE is a string, the tag will simply be appended to create the link.
1866 If the string contains \"%s\", the tag will be inserted there. If the string
1867 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1868 at that point (see the function `url-hexify-string'). If the string contains
1869 the specifier \"%(my-function)\", then the custom function `my-function' will
1870 be invoked: this function takes the tag as its only argument and must return
1871 a string.
1873 REPLACE may also be a function that will be called with the tag as the
1874 only argument to create the link, which should be returned as a string.
1876 See the manual for examples."
1877 :group 'org-link
1878 :type '(repeat
1879 (cons
1880 (string :tag "Protocol")
1881 (choice
1882 (string :tag "Format")
1883 (function)))))
1885 (defcustom org-descriptive-links t
1886 "Non-nil means Org will display descriptive links.
1887 E.g. [[http://orgmode.org][Org website]] will be displayed as
1888 \"Org Website\", hiding the link itself and just displaying its
1889 description. When set to nil, Org will display the full links
1890 literally.
1892 You can interactively set the value of this variable by calling
1893 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1894 :group 'org-link
1895 :type 'boolean)
1897 (defcustom org-link-file-path-type 'adaptive
1898 "How the path name in file links should be stored.
1899 Valid values are:
1901 relative Relative to the current directory, i.e. the directory of the file
1902 into which the link is being inserted.
1903 absolute Absolute path, if possible with ~ for home directory.
1904 noabbrev Absolute path, no abbreviation of home directory.
1905 adaptive Use relative path for files in the current directory and sub-
1906 directories of it. For other files, use an absolute path."
1907 :group 'org-link
1908 :type '(choice
1909 (const relative)
1910 (const absolute)
1911 (const noabbrev)
1912 (const adaptive)))
1914 (defvaralias 'org-activate-links 'org-highlight-links)
1915 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1916 "Types of links that should be highlighted in Org files.
1918 This is a list of symbols, each one of them leading to the
1919 highlighting of a certain link type.
1921 You can still open links that are not highlighted.
1923 In principle, it does not hurt to turn on highlighting for all
1924 link types. There may be a small gain when turning off unused
1925 link types. The types are:
1927 bracket The recommended [[link][description]] or [[link]] links with hiding.
1928 angle Links in angular brackets that may contain whitespace like
1929 <bbdb:Carsten Dominik>.
1930 plain Plain links in normal text, no whitespace, like http://google.com.
1931 radio Text that is matched by a radio target, see manual for details.
1932 tag Tag settings in a headline (link to tag search).
1933 date Time stamps (link to calendar).
1934 footnote Footnote labels.
1936 If you set this variable during an Emacs session, use `org-mode-restart'
1937 in the Org buffer so that the change takes effect."
1938 :group 'org-link
1939 :group 'org-appearance
1940 :type '(set :greedy t
1941 (const :tag "Double bracket links" bracket)
1942 (const :tag "Angular bracket links" angle)
1943 (const :tag "Plain text links" plain)
1944 (const :tag "Radio target matches" radio)
1945 (const :tag "Tags" tag)
1946 (const :tag "Timestamps" date)
1947 (const :tag "Footnotes" footnote)))
1949 (defcustom org-make-link-description-function nil
1950 "Function to use for generating link descriptions from links.
1951 When nil, the link location will be used. This function must take
1952 two parameters: the first one is the link, the second one is the
1953 description generated by `org-insert-link'. The function should
1954 return the description to use."
1955 :group 'org-link
1956 :type '(choice (const nil) (function)))
1958 (defgroup org-link-store nil
1959 "Options concerning storing links in Org mode."
1960 :tag "Org Store Link"
1961 :group 'org-link)
1963 (defcustom org-url-hexify-p t
1964 "When non-nil, hexify URL when creating a link."
1965 :type 'boolean
1966 :version "24.3"
1967 :group 'org-link-store)
1969 (defcustom org-email-link-description-format "Email %c: %.30s"
1970 "Format of the description part of a link to an email or usenet message.
1971 The following %-escapes will be replaced by corresponding information:
1973 %F full \"From\" field
1974 %f name, taken from \"From\" field, address if no name
1975 %T full \"To\" field
1976 %t first name in \"To\" field, address if no name
1977 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1978 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1979 %s subject
1980 %d date
1981 %m message-id.
1983 You may use normal field width specification between the % and the letter.
1984 This is for example useful to limit the length of the subject.
1986 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1987 :group 'org-link-store
1988 :type 'string)
1990 (defcustom org-from-is-user-regexp
1991 (let (r1 r2)
1992 (when (and user-mail-address (not (string= user-mail-address "")))
1993 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1994 (when (and user-full-name (not (string= user-full-name "")))
1995 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1996 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1997 "Regexp matched against the \"From:\" header of an email or usenet message.
1998 It should match if the message is from the user him/herself."
1999 :group 'org-link-store
2000 :type 'regexp)
2002 (defcustom org-context-in-file-links t
2003 "Non-nil means file links from `org-store-link' contain context.
2004 \\<org-mode-map>
2005 A search string will be added to the file name with :: as separator
2006 and used to find the context when the link is activated by the command
2007 `org-open-at-point'. When this option is t, the entire active region
2008 will be placed in the search string of the file link. If set to a
2009 positive integer, only the first n lines of context will be stored.
2011 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2012 \\[org-store-link]')
2013 negates this setting for the duration of the command."
2014 :group 'org-link-store
2015 :type '(choice boolean integer))
2017 (defcustom org-keep-stored-link-after-insertion nil
2018 "Non-nil means keep link in list for entire session.
2019 \\<org-mode-map>
2020 The command `org-store-link' adds a link pointing to the current
2021 location to an internal list. These links accumulate during a session.
2022 The command `org-insert-link' can be used to insert links into any
2023 Org file (offering completion for all stored links).
2025 When this option is nil, every link which has been inserted once using
2026 `\\[org-insert-link]' will be removed from the list, to make completing the \
2027 unused
2028 links more efficient."
2029 :group 'org-link-store
2030 :type 'boolean)
2032 (defgroup org-link-follow nil
2033 "Options concerning following links in Org mode."
2034 :tag "Org Follow Link"
2035 :group 'org-link)
2037 (defcustom org-link-translation-function nil
2038 "Function to translate links with different syntax to Org syntax.
2039 This can be used to translate links created for example by the Planner
2040 or emacs-wiki packages to Org syntax.
2041 The function must accept two parameters, a TYPE containing the link
2042 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2043 which is everything after the link protocol. It should return a cons
2044 with possibly modified values of type and path.
2045 Org contains a function for this, so if you set this variable to
2046 `org-translate-link-from-planner', you should be able follow many
2047 links created by planner."
2048 :group 'org-link-follow
2049 :type '(choice (const nil) (function)))
2051 (defcustom org-follow-link-hook nil
2052 "Hook that is run after a link has been followed."
2053 :group 'org-link-follow
2054 :type 'hook)
2056 (defcustom org-tab-follows-link nil
2057 "Non-nil means on links TAB will follow the link.
2058 Needs to be set before org.el is loaded.
2059 This really should not be used, it does not make sense, and the
2060 implementation is bad."
2061 :group 'org-link-follow
2062 :type 'boolean)
2064 (defcustom org-return-follows-link nil
2065 "Non-nil means on links RET will follow the link.
2066 In tables, the special behavior of RET has precedence."
2067 :group 'org-link-follow
2068 :type 'boolean)
2070 (defcustom org-mouse-1-follows-link
2071 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2072 "Non-nil means mouse-1 on a link will follow the link.
2073 A longer mouse click will still set point. Needs to be set
2074 before org.el is loaded."
2075 :group 'org-link-follow
2076 :version "24.4"
2077 :package-version '(Org . "8.3")
2078 :type '(choice
2079 (const :tag "A double click follows the link" double)
2080 (const :tag "Unconditionally follow the link with mouse-1" t)
2081 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2083 (defcustom org-mark-ring-length 4
2084 "Number of different positions to be recorded in the ring.
2085 Changing this requires a restart of Emacs to work correctly."
2086 :group 'org-link-follow
2087 :type 'integer)
2089 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2090 "Non-nil means internal fuzzy links can only match headlines.
2092 When nil, the a fuzzy link may point to a target or a named
2093 construct in the document. When set to the special value
2094 `query-to-create', offer to create a new headline when none
2095 matched.
2097 Spaces and statistics cookies are ignored during heading searches."
2098 :group 'org-link-follow
2099 :version "24.1"
2100 :type '(choice
2101 (const :tag "Use fuzzy text search" nil)
2102 (const :tag "Match only exact headline" t)
2103 (const :tag "Match exact headline or query to create it"
2104 query-to-create))
2105 :safe #'symbolp)
2107 (defcustom org-link-frame-setup
2108 '((vm . vm-visit-folder-other-frame)
2109 (vm-imap . vm-visit-imap-folder-other-frame)
2110 (gnus . org-gnus-no-new-news)
2111 (file . find-file-other-window)
2112 (wl . wl-other-frame))
2113 "Setup the frame configuration for following links.
2114 When following a link with Emacs, it may often be useful to display
2115 this link in another window or frame. This variable can be used to
2116 set this up for the different types of links.
2117 For VM, use any of
2118 `vm-visit-folder'
2119 `vm-visit-folder-other-window'
2120 `vm-visit-folder-other-frame'
2121 For Gnus, use any of
2122 `gnus'
2123 `gnus-other-frame'
2124 `org-gnus-no-new-news'
2125 For FILE, use any of
2126 `find-file'
2127 `find-file-other-window'
2128 `find-file-other-frame'
2129 For Wanderlust use any of
2130 `wl'
2131 `wl-other-frame'
2132 For the calendar, use the variable `calendar-setup'.
2133 For BBDB, it is currently only possible to display the matches in
2134 another window."
2135 :group 'org-link-follow
2136 :type '(list
2137 (cons (const vm)
2138 (choice
2139 (const vm-visit-folder)
2140 (const vm-visit-folder-other-window)
2141 (const vm-visit-folder-other-frame)))
2142 (cons (const vm-imap)
2143 (choice
2144 (const vm-visit-imap-folder)
2145 (const vm-visit-imap-folder-other-window)
2146 (const vm-visit-imap-folder-other-frame)))
2147 (cons (const gnus)
2148 (choice
2149 (const gnus)
2150 (const gnus-other-frame)
2151 (const org-gnus-no-new-news)))
2152 (cons (const file)
2153 (choice
2154 (const find-file)
2155 (const find-file-other-window)
2156 (const find-file-other-frame)))
2157 (cons (const wl)
2158 (choice
2159 (const wl)
2160 (const wl-other-frame)))))
2162 (defcustom org-display-internal-link-with-indirect-buffer nil
2163 "Non-nil means use indirect buffer to display infile links.
2164 Activating internal links (from one location in a file to another location
2165 in the same file) normally just jumps to the location. When the link is
2166 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2167 is displayed in
2168 another window. When this option is set, the other window actually displays
2169 an indirect buffer clone of the current buffer, to avoid any visibility
2170 changes to the current buffer."
2171 :group 'org-link-follow
2172 :type 'boolean)
2174 (defcustom org-open-non-existing-files nil
2175 "Non-nil means `org-open-file' will open non-existing files.
2176 When nil, an error will be generated.
2177 This variable applies only to external applications because they
2178 might choke on non-existing files. If the link is to a file that
2179 will be opened in Emacs, the variable is ignored."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-directory-means-index-dot-org nil
2184 "Non-nil means a link to a directory really means to index.org.
2185 When nil, following a directory link will run dired or open a finder/explorer
2186 window on that directory."
2187 :group 'org-link-follow
2188 :type 'boolean)
2190 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2191 "Non-nil means ask for confirmation before executing shell links.
2192 Shell links can be dangerous: just think about a link
2194 [[shell:rm -rf ~/*][Google Search]]
2196 This link would show up in your Org document as \"Google Search\",
2197 but really it would remove your entire home directory.
2198 Therefore we advise against setting this variable to nil.
2199 Just change it to `y-or-n-p' if you want to confirm with a
2200 single keystroke rather than having to type \"yes\"."
2201 :group 'org-link-follow
2202 :type '(choice
2203 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2204 (const :tag "with y-or-n (faster)" y-or-n-p)
2205 (const :tag "no confirmation (dangerous)" nil)))
2206 (put 'org-confirm-shell-link-function
2207 'safe-local-variable
2208 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2210 (defcustom org-confirm-shell-link-not-regexp ""
2211 "A regexp to skip confirmation for shell links."
2212 :group 'org-link-follow
2213 :version "24.1"
2214 :type 'regexp)
2216 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2217 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2218 Elisp links can be dangerous: just think about a link
2220 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2222 This link would show up in your Org document as \"Google Search\",
2223 but really it would remove your entire home directory.
2224 Therefore we advise against setting this variable to nil.
2225 Just change it to `y-or-n-p' if you want to confirm with a
2226 single keystroke rather than having to type \"yes\"."
2227 :group 'org-link-follow
2228 :type '(choice
2229 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2230 (const :tag "with y-or-n (faster)" y-or-n-p)
2231 (const :tag "no confirmation (dangerous)" nil)))
2232 (put 'org-confirm-shell-link-function
2233 'safe-local-variable
2234 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2236 (defcustom org-confirm-elisp-link-not-regexp ""
2237 "A regexp to skip confirmation for Elisp links."
2238 :group 'org-link-follow
2239 :version "24.1"
2240 :type 'regexp)
2242 (defconst org-file-apps-defaults-gnu
2243 '((remote . emacs)
2244 (system . mailcap)
2245 (t . mailcap))
2246 "Default file applications on a UNIX or GNU/Linux system.
2247 See `org-file-apps'.")
2249 (defconst org-file-apps-defaults-macosx
2250 '((remote . emacs)
2251 (system . "open %s")
2252 ("ps.gz" . "gv %s")
2253 ("eps.gz" . "gv %s")
2254 ("dvi" . "xdvi %s")
2255 ("fig" . "xfig %s")
2256 (t . "open %s"))
2257 "Default file applications on a macOS system.
2258 The system \"open\" is known as a default, but we use X11 applications
2259 for some files for which the OS does not have a good default.
2260 See `org-file-apps'.")
2262 (defconst org-file-apps-defaults-windowsnt
2263 (list '(remote . emacs)
2264 (cons 'system (lambda (file _path)
2265 (with-no-warnings (w32-shell-execute "open" file))))
2266 (cons t (lambda (file _path)
2267 (with-no-warnings (w32-shell-execute "open" file)))))
2268 "Default file applications on a Windows NT system.
2269 The system \"open\" is used for most files.
2270 See `org-file-apps'.")
2272 (defcustom org-file-apps
2273 '((auto-mode . emacs)
2274 ("\\.mm\\'" . default)
2275 ("\\.x?html?\\'" . default)
2276 ("\\.pdf\\'" . default))
2277 "External applications for opening `file:path' items in a document.
2278 \\<org-mode-map>\
2280 Org mode uses system defaults for different file types, but
2281 you can use this variable to set the application for a given file
2282 extension. The entries in this list are cons cells where the car identifies
2283 files and the cdr the corresponding command.
2285 Possible values for the file identifier are:
2287 \"string\" A string as a file identifier can be interpreted in different
2288 ways, depending on its contents:
2290 - Alphanumeric characters only:
2291 Match links with this file extension.
2292 Example: (\"pdf\" . \"evince %s\")
2293 to open PDFs with evince.
2295 - Regular expression: Match links where the
2296 filename matches the regexp. If you want to
2297 use groups here, use shy groups.
2299 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2300 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2301 to open *.html and *.xhtml with firefox.
2303 - Regular expression which contains (non-shy) groups:
2304 Match links where the whole link, including \"::\", and
2305 anything after that, matches the regexp.
2306 In a custom command string, %1, %2, etc. are replaced with
2307 the parts of the link that were matched by the groups.
2308 For backwards compatibility, if a command string is given
2309 that does not use any of the group matches, this case is
2310 handled identically to the second one (i.e. match against
2311 file name only).
2312 In a custom function, you can access the group matches with
2313 (match-string n link).
2315 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2316 \"evince -p %1 %s\")
2317 to open [[file:document.pdf::5]] with evince at page 5.
2319 `directory' Matches a directory
2320 `remote' Matches a remote file, accessible through tramp or efs.
2321 Remote files most likely should be visited through Emacs
2322 because external applications cannot handle such paths.
2323 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2324 so all files Emacs knows how to handle. Using this with
2325 command `emacs' will open most files in Emacs. Beware that this
2326 will also open html files inside Emacs, unless you add
2327 (\"html\" . default) to the list as well.
2328 `system' The system command to open files, like `open' on Windows
2329 and macOS, and mailcap under GNU/Linux. This is the command
2330 that will be selected if you call `org-open-at-point' with a
2331 double prefix argument (`\\[universal-argument] \
2332 \\[universal-argument] \\[org-open-at-point]').
2333 t Default for files not matched by any of the other options.
2335 Possible values for the command are:
2337 `emacs' The file will be visited by the current Emacs process.
2338 `default' Use the default application for this file type, which is the
2339 association for t in the list, most likely in the system-specific
2340 part. This can be used to overrule an unwanted setting in the
2341 system-specific variable.
2342 `system' Use the system command for opening files, like \"open\".
2343 This command is specified by the entry whose car is `system'.
2344 Most likely, the system-specific version of this variable
2345 does define this command, but you can overrule/replace it
2346 here.
2347 `mailcap' Use command specified in the mailcaps.
2348 string A command to be executed by a shell; %s will be replaced
2349 by the path to the file.
2350 function A Lisp function, which will be called with two arguments:
2351 the file path and the original link string, without the
2352 \"file:\" prefix.
2354 For more examples, see the system specific constants
2355 `org-file-apps-defaults-macosx'
2356 `org-file-apps-defaults-windowsnt'
2357 `org-file-apps-defaults-gnu'."
2358 :group 'org-link-follow
2359 :type '(repeat
2360 (cons (choice :value ""
2361 (string :tag "Extension")
2362 (const :tag "System command to open files" system)
2363 (const :tag "Default for unrecognized files" t)
2364 (const :tag "Remote file" remote)
2365 (const :tag "Links to a directory" directory)
2366 (const :tag "Any files that have Emacs modes"
2367 auto-mode))
2368 (choice :value ""
2369 (const :tag "Visit with Emacs" emacs)
2370 (const :tag "Use default" default)
2371 (const :tag "Use the system command" system)
2372 (string :tag "Command")
2373 (function :tag "Function")))))
2375 (defcustom org-doi-server-url "http://dx.doi.org/"
2376 "The URL of the DOI server."
2377 :type 'string
2378 :version "24.3"
2379 :group 'org-link-follow)
2381 (defgroup org-refile nil
2382 "Options concerning refiling entries in Org mode."
2383 :tag "Org Refile"
2384 :group 'org)
2386 (defcustom org-directory "~/org"
2387 "Directory with Org files.
2388 This is just a default location to look for Org files. There is no need
2389 at all to put your files into this directory. It is used in the
2390 following situations:
2392 1. When a capture template specifies a target file that is not an
2393 absolute path. The path will then be interpreted relative to
2394 `org-directory'
2395 2. When the value of variable `org-agenda-files' is a single file, any
2396 relative paths in this file will be taken as relative to
2397 `org-directory'."
2398 :group 'org-refile
2399 :group 'org-capture
2400 :type 'directory)
2402 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2403 "Default target for storing notes.
2404 Used as a fall back file for org-capture.el, for templates that
2405 do not specify a target file."
2406 :group 'org-refile
2407 :group 'org-capture
2408 :type 'file)
2410 (defcustom org-goto-interface 'outline
2411 "The default interface to be used for `org-goto'.
2412 Allowed values are:
2413 outline The interface shows an outline of the relevant file
2414 and the correct heading is found by moving through
2415 the outline or by searching with incremental search.
2416 outline-path-completion Headlines in the current buffer are offered via
2417 completion. This is the interface also used by
2418 the refile command."
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Outline" outline)
2422 (const :tag "Outline-path-completion" outline-path-completion)))
2424 (defcustom org-goto-max-level 5
2425 "Maximum target level when running `org-goto' with refile interface."
2426 :group 'org-refile
2427 :type 'integer)
2429 (defcustom org-reverse-note-order nil
2430 "Non-nil means store new notes at the beginning of a file or entry.
2431 When nil, new notes will be filed to the end of a file or entry.
2432 This can also be a list with cons cells of regular expressions that
2433 are matched against file names, and values."
2434 :group 'org-capture
2435 :group 'org-refile
2436 :type '(choice
2437 (const :tag "Reverse always" t)
2438 (const :tag "Reverse never" nil)
2439 (repeat :tag "By file name regexp"
2440 (cons regexp boolean))))
2442 (defcustom org-log-refile nil
2443 "Information to record when a task is refiled.
2445 Possible values are:
2447 nil Don't add anything
2448 time Add a time stamp to the task
2449 note Prompt for a note and add it with template `org-log-note-headings'
2451 This option can also be set with on a per-file-basis with
2453 #+STARTUP: nologrefile
2454 #+STARTUP: logrefile
2455 #+STARTUP: lognoterefile
2457 You can have local logging settings for a subtree by setting the LOGGING
2458 property to one or more of these keywords.
2460 When bulk-refiling from the agenda, the value `note' is forbidden and
2461 will temporarily be changed to `time'."
2462 :group 'org-refile
2463 :group 'org-progress
2464 :version "24.1"
2465 :type '(choice
2466 (const :tag "No logging" nil)
2467 (const :tag "Record timestamp" time)
2468 (const :tag "Record timestamp with note." note)))
2470 (defcustom org-refile-targets nil
2471 "Targets for refiling entries with `\\[org-refile]'.
2472 This is a list of cons cells. Each cell contains:
2473 - a specification of the files to be considered, either a list of files,
2474 or a symbol whose function or variable value will be used to retrieve
2475 a file name or a list of file names. If you use `org-agenda-files' for
2476 that, all agenda files will be scanned for targets. Nil means consider
2477 headings in the current buffer.
2478 - A specification of how to find candidate refile targets. This may be
2479 any of:
2480 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2481 This tag has to be present in all target headlines, inheritance will
2482 not be considered.
2483 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2484 todo keyword.
2485 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2486 headlines that are refiling targets.
2487 - a cons cell (:level . N). Any headline of level N is considered a target.
2488 Note that, when `org-odd-levels-only' is set, level corresponds to
2489 order in hierarchy, not to the number of stars.
2490 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2491 Note that, when `org-odd-levels-only' is set, level corresponds to
2492 order in hierarchy, not to the number of stars.
2494 Each element of this list generates a set of possible targets.
2495 The union of these sets is presented (with completion) to
2496 the user by `org-refile'.
2498 You can set the variable `org-refile-target-verify-function' to a function
2499 to verify each headline found by the simple criteria above.
2501 When this variable is nil, all top-level headlines in the current buffer
2502 are used, equivalent to the value `((nil . (:level . 1))'."
2503 :group 'org-refile
2504 :type '(repeat
2505 (cons
2506 (choice :value org-agenda-files
2507 (const :tag "All agenda files" org-agenda-files)
2508 (const :tag "Current buffer" nil)
2509 (function) (variable) (file))
2510 (choice :tag "Identify target headline by"
2511 (cons :tag "Specific tag" (const :value :tag) (string))
2512 (cons :tag "TODO keyword" (const :value :todo) (string))
2513 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2514 (cons :tag "Level number" (const :value :level) (integer))
2515 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2517 (defcustom org-refile-target-verify-function nil
2518 "Function to verify if the headline at point should be a refile target.
2519 The function will be called without arguments, with point at the
2520 beginning of the headline. It should return t and leave point
2521 where it is if the headline is a valid target for refiling.
2523 If the target should not be selected, the function must return nil.
2524 In addition to this, it may move point to a place from where the search
2525 should be continued. For example, the function may decide that the entire
2526 subtree of the current entry should be excluded and move point to the end
2527 of the subtree."
2528 :group 'org-refile
2529 :type '(choice
2530 (const nil)
2531 (function)))
2533 (defcustom org-refile-use-cache nil
2534 "Non-nil means cache refile targets to speed up the process.
2535 \\<org-mode-map>\
2536 The cache for a particular file will be updated automatically when
2537 the buffer has been killed, or when any of the marker used for flagging
2538 refile targets no longer points at a live buffer.
2539 If you have added new entries to a buffer that might themselves be targets,
2540 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2541 if you find that easier, \
2542 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2543 \\[org-refile]'."
2544 :group 'org-refile
2545 :version "24.1"
2546 :type 'boolean)
2548 (defcustom org-refile-use-outline-path nil
2549 "Non-nil means provide refile targets as paths.
2550 So a level 3 headline will be available as level1/level2/level3.
2552 When the value is `file', also include the file name (without directory)
2553 into the path. In this case, you can also stop the completion after
2554 the file name, to get entries inserted as top level in the file.
2556 When `full-file-path', include the full file path."
2557 :group 'org-refile
2558 :type '(choice
2559 (const :tag "Not" nil)
2560 (const :tag "Yes" t)
2561 (const :tag "Start with file name" file)
2562 (const :tag "Start with full file path" full-file-path)))
2564 (defcustom org-outline-path-complete-in-steps t
2565 "Non-nil means complete the outline path in hierarchical steps.
2566 When Org uses the refile interface to select an outline path (see
2567 `org-refile-use-outline-path'), the completion of the path can be
2568 done in a single go, or it can be done in steps down the headline
2569 hierarchy. Going in steps is probably the best if you do not use
2570 a special completion package like `ido' or `icicles'. However,
2571 when using these packages, going in one step can be very fast,
2572 while still showing the whole path to the entry."
2573 :group 'org-refile
2574 :type 'boolean)
2576 (defcustom org-refile-allow-creating-parent-nodes nil
2577 "Non-nil means allow the creation of new nodes as refile targets.
2578 New nodes are then created by adding \"/new node name\" to the completion
2579 of an existing node. When the value of this variable is `confirm',
2580 new node creation must be confirmed by the user (recommended).
2581 When nil, the completion must match an existing entry.
2583 Note that, if the new heading is not seen by the criteria
2584 listed in `org-refile-targets', multiple instances of the same
2585 heading would be created by trying again to file under the new
2586 heading."
2587 :group 'org-refile
2588 :type '(choice
2589 (const :tag "Never" nil)
2590 (const :tag "Always" t)
2591 (const :tag "Prompt for confirmation" confirm)))
2593 (defcustom org-refile-active-region-within-subtree nil
2594 "Non-nil means also refile active region within a subtree.
2596 By default `org-refile' doesn't allow refiling regions if they
2597 don't contain a set of subtrees, but it might be convenient to
2598 do so sometimes: in that case, the first line of the region is
2599 converted to a headline before refiling."
2600 :group 'org-refile
2601 :version "24.1"
2602 :type 'boolean)
2604 (defgroup org-todo nil
2605 "Options concerning TODO items in Org mode."
2606 :tag "Org TODO"
2607 :group 'org)
2609 (defgroup org-progress nil
2610 "Options concerning Progress logging in Org mode."
2611 :tag "Org Progress"
2612 :group 'org-time)
2614 (defvar org-todo-interpretation-widgets
2615 '((:tag "Sequence (cycling hits every state)" sequence)
2616 (:tag "Type (cycling directly to DONE)" type))
2617 "The available interpretation symbols for customizing `org-todo-keywords'.
2618 Interested libraries should add to this list.")
2620 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2621 "List of TODO entry keyword sequences and their interpretation.
2622 \\<org-mode-map>This is a list of sequences.
2624 Each sequence starts with a symbol, either `sequence' or `type',
2625 indicating if the keywords should be interpreted as a sequence of
2626 action steps, or as different types of TODO items. The first
2627 keywords are states requiring action - these states will select a headline
2628 for inclusion into the global TODO list Org produces. If one of the
2629 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2630 signify that no further action is necessary. If \"|\" is not found,
2631 the last keyword is treated as the only DONE state of the sequence.
2633 The command `\\[org-todo]' cycles an entry through these states, and one
2634 additional state where no keyword is present. For details about this
2635 cycling, see the manual.
2637 TODO keywords and interpretation can also be set on a per-file basis with
2638 the special #+SEQ_TODO and #+TYP_TODO lines.
2640 Each keyword can optionally specify a character for fast state selection
2641 \(in combination with the variable `org-use-fast-todo-selection')
2642 and specifiers for state change logging, using the same syntax that
2643 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2644 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2645 indicates to record a time stamp each time this state is selected.
2647 Each keyword may also specify if a timestamp or a note should be
2648 recorded when entering or leaving the state, by adding additional
2649 characters in the parenthesis after the keyword. This looks like this:
2650 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2651 record only the time of the state change. With X and Y being either
2652 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2653 Y when leaving the state if and only if the *target* state does not
2654 define X. You may omit any of the fast-selection key or X or /Y,
2655 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2657 For backward compatibility, this variable may also be just a list
2658 of keywords. In this case the interpretation (sequence or type) will be
2659 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2660 :group 'org-todo
2661 :group 'org-keywords
2662 :type '(choice
2663 (repeat :tag "Old syntax, just keywords"
2664 (string :tag "Keyword"))
2665 (repeat :tag "New syntax"
2666 (cons
2667 (choice
2668 :tag "Interpretation"
2669 ;;Quick and dirty way to see
2670 ;;`org-todo-interpretations'. This takes the
2671 ;;place of item arguments
2672 :convert-widget
2673 (lambda (widget)
2674 (widget-put widget
2675 :args (mapcar
2676 (lambda (x)
2677 (widget-convert
2678 (cons 'const x)))
2679 org-todo-interpretation-widgets))
2680 widget))
2681 (repeat
2682 (string :tag "Keyword"))))))
2684 (defvar-local org-todo-keywords-1 nil
2685 "All TODO and DONE keywords active in a buffer.")
2686 (defvar org-todo-keywords-for-agenda nil)
2687 (defvar org-done-keywords-for-agenda nil)
2688 (defvar org-todo-keyword-alist-for-agenda nil)
2689 (defvar org-tag-alist-for-agenda nil
2690 "Alist of all tags from all agenda files.")
2691 (defvar org-tag-groups-alist-for-agenda nil
2692 "Alist of all groups tags from all current agenda files.")
2693 (defvar-local org-tag-groups-alist nil)
2694 (defvar org-agenda-contributing-files nil)
2695 (defvar-local org-current-tag-alist nil
2696 "Alist of all tag groups in current buffer.
2697 This variable takes into consideration `org-tag-alist',
2698 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2699 (defvar-local org-not-done-keywords nil)
2700 (defvar-local org-done-keywords nil)
2701 (defvar-local org-todo-heads nil)
2702 (defvar-local org-todo-sets nil)
2703 (defvar-local org-todo-log-states nil)
2704 (defvar-local org-todo-kwd-alist nil)
2705 (defvar-local org-todo-key-alist nil)
2706 (defvar-local org-todo-key-trigger nil)
2708 (defcustom org-todo-interpretation 'sequence
2709 "Controls how TODO keywords are interpreted.
2710 This variable is in principle obsolete and is only used for
2711 backward compatibility, if the interpretation of todo keywords is
2712 not given already in `org-todo-keywords'. See that variable for
2713 more information."
2714 :group 'org-todo
2715 :group 'org-keywords
2716 :type '(choice (const sequence)
2717 (const type)))
2719 (defcustom org-use-fast-todo-selection t
2720 "\\<org-mode-map>\
2721 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2722 This variable describes if and under what circumstances the cycling
2723 mechanism for TODO keywords will be replaced by a single-key, direct
2724 selection scheme.
2726 When nil, fast selection is never used.
2728 When the symbol `prefix', it will be used when `org-todo' is called
2729 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2730 in an Org buffer, and
2731 `\\[universal-argument] t' in an agenda buffer.
2733 When t, fast selection is used by default. In this case, the prefix
2734 argument forces cycling instead.
2736 In all cases, the special interface is only used if access keys have
2737 actually been assigned by the user, i.e. if keywords in the configuration
2738 are followed by a letter in parenthesis, like TODO(t)."
2739 :group 'org-todo
2740 :type '(choice
2741 (const :tag "Never" nil)
2742 (const :tag "By default" t)
2743 (const :tag "Only with C-u C-c C-t" prefix)))
2745 (defcustom org-provide-todo-statistics t
2746 "Non-nil means update todo statistics after insert and toggle.
2747 ALL-HEADLINES means update todo statistics by including headlines
2748 with no TODO keyword as well, counting them as not done.
2749 A list of TODO keywords means the same, but skip keywords that are
2750 not in this list.
2751 When set to a list of two lists, the first list contains keywords
2752 to consider as TODO keywords, the second list contains keywords
2753 to consider as DONE keywords.
2755 When this is set, todo statistics is updated in the parent of the
2756 current entry each time a todo state is changed."
2757 :group 'org-todo
2758 :type '(choice
2759 (const :tag "Yes, only for TODO entries" t)
2760 (const :tag "Yes, including all entries" all-headlines)
2761 (repeat :tag "Yes, for TODOs in this list"
2762 (string :tag "TODO keyword"))
2763 (list :tag "Yes, for TODOs and DONEs in these lists"
2764 (repeat (string :tag "TODO keyword"))
2765 (repeat (string :tag "DONE keyword")))
2766 (other :tag "No TODO statistics" nil)))
2768 (defcustom org-hierarchical-todo-statistics t
2769 "Non-nil means TODO statistics covers just direct children.
2770 When nil, all entries in the subtree are considered.
2771 This has only an effect if `org-provide-todo-statistics' is set.
2772 To set this to nil for only a single subtree, use a COOKIE_DATA
2773 property and include the word \"recursive\" into the value."
2774 :group 'org-todo
2775 :type 'boolean)
2777 (defcustom org-after-todo-state-change-hook nil
2778 "Hook which is run after the state of a TODO item was changed.
2779 The new state (a string with a TODO keyword, or nil) is available in the
2780 Lisp variable `org-state'."
2781 :group 'org-todo
2782 :type 'hook)
2784 (defvar org-blocker-hook nil
2785 "Hook for functions that are allowed to block a state change.
2787 Functions in this hook should not modify the buffer.
2788 Each function gets as its single argument a property list,
2789 see `org-trigger-hook' for more information about this list.
2791 If any of the functions in this hook returns nil, the state change
2792 is blocked.")
2794 (defvar org-trigger-hook nil
2795 "Hook for functions that are triggered by a state change.
2797 Each function gets as its single argument a property list with at
2798 least the following elements:
2800 (:type type-of-change :position pos-at-entry-start
2801 :from old-state :to new-state)
2803 Depending on the type, more properties may be present.
2805 This mechanism is currently implemented for:
2807 TODO state changes
2808 ------------------
2809 :type todo-state-change
2810 :from previous state (keyword as a string), or nil, or a symbol
2811 `todo' or `done', to indicate the general type of state.
2812 :to new state, like in :from")
2814 (defcustom org-enforce-todo-dependencies nil
2815 "Non-nil means undone TODO entries will block switching the parent to DONE.
2816 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2817 be blocked if any prior sibling is not yet done.
2818 Finally, if the parent is blocked because of ordered siblings of its own,
2819 the child will also be blocked."
2820 :set (lambda (var val)
2821 (set var val)
2822 (if val
2823 (add-hook 'org-blocker-hook
2824 'org-block-todo-from-children-or-siblings-or-parent)
2825 (remove-hook 'org-blocker-hook
2826 'org-block-todo-from-children-or-siblings-or-parent)))
2827 :group 'org-todo
2828 :type 'boolean)
2830 (defcustom org-enforce-todo-checkbox-dependencies nil
2831 "Non-nil means unchecked boxes will block switching the parent to DONE.
2832 When this is nil, checkboxes have no influence on switching TODO states.
2833 When non-nil, you first need to check off all check boxes before the TODO
2834 entry can be switched to DONE.
2835 This variable needs to be set before org.el is loaded, and you need to
2836 restart Emacs after a change to make the change effective. The only way
2837 to change is while Emacs is running is through the customize interface."
2838 :set (lambda (var val)
2839 (set var val)
2840 (if val
2841 (add-hook 'org-blocker-hook
2842 'org-block-todo-from-checkboxes)
2843 (remove-hook 'org-blocker-hook
2844 'org-block-todo-from-checkboxes)))
2845 :group 'org-todo
2846 :type 'boolean)
2848 (defcustom org-treat-insert-todo-heading-as-state-change nil
2849 "Non-nil means inserting a TODO heading is treated as state change.
2850 So when the command `\\[org-insert-todo-heading]' is used, state change
2851 logging will apply if appropriate. When nil, the new TODO item will
2852 be inserted directly, and no logging will take place."
2853 :group 'org-todo
2854 :type 'boolean)
2856 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2857 "Non-nil means switching TODO states with S-cursor counts as state change.
2858 This is the default behavior. However, setting this to nil allows a
2859 convenient way to select a TODO state and bypass any logging associated
2860 with that."
2861 :group 'org-todo
2862 :type 'boolean)
2864 (defcustom org-todo-state-tags-triggers nil
2865 "Tag changes that should be triggered by TODO state changes.
2866 This is a list. Each entry is
2868 (state-change (tag . flag) .......)
2870 State-change can be a string with a state, and empty string to indicate the
2871 state that has no TODO keyword, or it can be one of the symbols `todo'
2872 or `done', meaning any not-done or done state, respectively."
2873 :group 'org-todo
2874 :group 'org-tags
2875 :type '(repeat
2876 (cons (choice :tag "When changing to"
2877 (const :tag "Not-done state" todo)
2878 (const :tag "Done state" done)
2879 (string :tag "State"))
2880 (repeat
2881 (cons :tag "Tag action"
2882 (string :tag "Tag")
2883 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2885 (defcustom org-log-done nil
2886 "Information to record when a task moves to the DONE state.
2888 Possible values are:
2890 nil Don't add anything, just change the keyword
2891 time Add a time stamp to the task
2892 note Prompt for a note and add it with template `org-log-note-headings'
2894 This option can also be set with on a per-file-basis with
2896 #+STARTUP: nologdone
2897 #+STARTUP: logdone
2898 #+STARTUP: lognotedone
2900 You can have local logging settings for a subtree by setting the LOGGING
2901 property to one or more of these keywords."
2902 :group 'org-todo
2903 :group 'org-progress
2904 :type '(choice
2905 (const :tag "No logging" nil)
2906 (const :tag "Record CLOSED timestamp" time)
2907 (const :tag "Record CLOSED timestamp with note." note)))
2909 ;; Normalize old uses of org-log-done.
2910 (cond
2911 ((eq org-log-done t) (setq org-log-done 'time))
2912 ((and (listp org-log-done) (memq 'done org-log-done))
2913 (setq org-log-done 'note)))
2915 (defcustom org-log-reschedule nil
2916 "Information to record when the scheduling date of a tasks is modified.
2918 Possible values are:
2920 nil Don't add anything, just change the date
2921 time Add a time stamp to the task
2922 note Prompt for a note and add it with template `org-log-note-headings'
2924 This option can also be set with on a per-file-basis with
2926 #+STARTUP: nologreschedule
2927 #+STARTUP: logreschedule
2928 #+STARTUP: lognotereschedule"
2929 :group 'org-todo
2930 :group 'org-progress
2931 :type '(choice
2932 (const :tag "No logging" nil)
2933 (const :tag "Record timestamp" time)
2934 (const :tag "Record timestamp with note." note)))
2936 (defcustom org-log-redeadline nil
2937 "Information to record when the deadline date of a tasks is modified.
2939 Possible values are:
2941 nil Don't add anything, just change the date
2942 time Add a time stamp to the task
2943 note Prompt for a note and add it with template `org-log-note-headings'
2945 This option can also be set with on a per-file-basis with
2947 #+STARTUP: nologredeadline
2948 #+STARTUP: logredeadline
2949 #+STARTUP: lognoteredeadline
2951 You can have local logging settings for a subtree by setting the LOGGING
2952 property to one or more of these keywords."
2953 :group 'org-todo
2954 :group 'org-progress
2955 :type '(choice
2956 (const :tag "No logging" nil)
2957 (const :tag "Record timestamp" time)
2958 (const :tag "Record timestamp with note." note)))
2960 (defcustom org-log-note-clock-out nil
2961 "Non-nil means record a note when clocking out of an item.
2962 This can also be configured on a per-file basis by adding one of
2963 the following lines anywhere in the buffer:
2965 #+STARTUP: lognoteclock-out
2966 #+STARTUP: nolognoteclock-out"
2967 :group 'org-todo
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-done-with-time t
2972 "Non-nil means the CLOSED time stamp will contain date and time.
2973 When nil, only the date will be recorded."
2974 :group 'org-progress
2975 :type 'boolean)
2977 (defcustom org-log-note-headings
2978 '((done . "CLOSING NOTE %t")
2979 (state . "State %-12s from %-12S %t")
2980 (note . "Note taken on %t")
2981 (reschedule . "Rescheduled from %S on %t")
2982 (delschedule . "Not scheduled, was %S on %t")
2983 (redeadline . "New deadline from %S on %t")
2984 (deldeadline . "Removed deadline, was %S on %t")
2985 (refile . "Refiled on %t")
2986 (clock-out . ""))
2987 "Headings for notes added to entries.
2989 The value is an alist, with the car being a symbol indicating the
2990 note context, and the cdr is the heading to be used. The heading
2991 may also be the empty string. The following placeholders can be
2992 used:
2994 %t a time stamp.
2995 %T an active time stamp instead the default inactive one
2996 %d a short-format time stamp.
2997 %D an active short-format time stamp.
2998 %s the new TODO state or time stamp (inactive), in double quotes.
2999 %S the old TODO state or time stamp (inactive), in double quotes.
3000 %u the user name.
3001 %U full user name.
3003 In fact, it is not a good idea to change the `state' entry,
3004 because Agenda Log mode depends on the format of these entries."
3005 :group 'org-todo
3006 :group 'org-progress
3007 :type '(list :greedy t
3008 (cons (const :tag "Heading when closing an item" done) string)
3009 (cons (const :tag
3010 "Heading when changing todo state (todo sequence only)"
3011 state) string)
3012 (cons (const :tag "Heading when just taking a note" note) string)
3013 (cons (const :tag "Heading when rescheduling" reschedule) string)
3014 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3015 (cons (const :tag "Heading when changing deadline" redeadline) string)
3016 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3017 (cons (const :tag "Heading when refiling" refile) string)
3018 (cons (const :tag "Heading when clocking out" clock-out) string)))
3020 (unless (assq 'note org-log-note-headings)
3021 (push '(note . "%t") org-log-note-headings))
3023 (defcustom org-log-into-drawer nil
3024 "Non-nil means insert state change notes and time stamps into a drawer.
3025 When nil, state changes notes will be inserted after the headline and
3026 any scheduling and clock lines, but not inside a drawer.
3028 The value of this variable should be the name of the drawer to use.
3029 LOGBOOK is proposed as the default drawer for this purpose, you can
3030 also set this to a string to define the drawer of your choice.
3032 A value of t is also allowed, representing \"LOGBOOK\".
3034 A value of t or nil can also be set with on a per-file-basis with
3036 #+STARTUP: logdrawer
3037 #+STARTUP: nologdrawer
3039 If this variable is set, `org-log-state-notes-insert-after-drawers'
3040 will be ignored.
3042 You can set the property LOG_INTO_DRAWER to overrule this setting for
3043 a subtree.
3045 Do not check directly this variable in a Lisp program. Call
3046 function `org-log-into-drawer' instead."
3047 :group 'org-todo
3048 :group 'org-progress
3049 :type '(choice
3050 (const :tag "Not into a drawer" nil)
3051 (const :tag "LOGBOOK" t)
3052 (string :tag "Other")))
3054 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3056 (defun org-log-into-drawer ()
3057 "Name of the log drawer, as a string, or nil.
3058 This is the value of `org-log-into-drawer'. However, if the
3059 current entry has or inherits a LOG_INTO_DRAWER property, it will
3060 be used instead of the default value."
3061 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3062 (cond ((equal p "nil") nil)
3063 ((equal p "t") "LOGBOOK")
3064 ((stringp p) p)
3065 (p "LOGBOOK")
3066 ((stringp org-log-into-drawer) org-log-into-drawer)
3067 (org-log-into-drawer "LOGBOOK"))))
3069 (defcustom org-log-state-notes-insert-after-drawers nil
3070 "Non-nil means insert state change notes after any drawers in entry.
3071 Only the drawers that *immediately* follow the headline and the
3072 deadline/scheduled line are skipped.
3073 When nil, insert notes right after the heading and perhaps the line
3074 with deadline/scheduling if present.
3076 This variable will have no effect if `org-log-into-drawer' is
3077 set."
3078 :group 'org-todo
3079 :group 'org-progress
3080 :type 'boolean)
3082 (defcustom org-log-states-order-reversed t
3083 "Non-nil means the latest state note will be directly after heading.
3084 When nil, the state change notes will be ordered according to time.
3086 This option can also be set with on a per-file-basis with
3088 #+STARTUP: logstatesreversed
3089 #+STARTUP: nologstatesreversed"
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-todo-repeat-to-state nil
3095 "The TODO state to which a repeater should return the repeating task.
3096 By default this is the first task in a TODO sequence, or the previous state
3097 in a TODO_TYP set. But you can specify another task here.
3098 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3099 :group 'org-todo
3100 :version "24.1"
3101 :type '(choice (const :tag "Head of sequence" nil)
3102 (string :tag "Specific state")))
3104 (defcustom org-log-repeat 'time
3105 "Non-nil means record moving through the DONE state when triggering repeat.
3106 An auto-repeating task is immediately switched back to TODO when
3107 marked DONE. If you are not logging state changes (by adding \"@\"
3108 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3109 record a closing note, there will be no record of the task moving
3110 through DONE. This variable forces taking a note anyway.
3112 nil Don't force a record
3113 time Record a time stamp
3114 note Prompt for a note and add it with template `org-log-note-headings'
3116 This option can also be set with on a per-file-basis with
3118 #+STARTUP: nologrepeat
3119 #+STARTUP: logrepeat
3120 #+STARTUP: lognoterepeat
3122 You can have local logging settings for a subtree by setting the LOGGING
3123 property to one or more of these keywords."
3124 :group 'org-todo
3125 :group 'org-progress
3126 :type '(choice
3127 (const :tag "Don't force a record" nil)
3128 (const :tag "Force recording the DONE state" time)
3129 (const :tag "Force recording a note with the DONE state" note)))
3132 (defgroup org-priorities nil
3133 "Priorities in Org mode."
3134 :tag "Org Priorities"
3135 :group 'org-todo)
3137 (defcustom org-enable-priority-commands t
3138 "Non-nil means priority commands are active.
3139 When nil, these commands will be disabled, so that you never accidentally
3140 set a priority."
3141 :group 'org-priorities
3142 :type 'boolean)
3144 (defcustom org-highest-priority ?A
3145 "The highest priority of TODO items. A character like ?A, ?B etc.
3146 Must have a smaller ASCII number than `org-lowest-priority'."
3147 :group 'org-priorities
3148 :type 'character)
3150 (defcustom org-lowest-priority ?C
3151 "The lowest priority of TODO items. A character like ?A, ?B etc.
3152 Must have a larger ASCII number than `org-highest-priority'."
3153 :group 'org-priorities
3154 :type 'character)
3156 (defcustom org-default-priority ?B
3157 "The default priority of TODO items.
3158 This is the priority an item gets if no explicit priority is given.
3159 When starting to cycle on an empty priority the first step in the cycle
3160 depends on `org-priority-start-cycle-with-default'. The resulting first
3161 step priority must not exceed the range from `org-highest-priority' to
3162 `org-lowest-priority' which means that `org-default-priority' has to be
3163 in this range exclusive or inclusive the range boundaries. Else the
3164 first step refuses to set the default and the second will fall back
3165 to (depending on the command used) the highest or lowest priority."
3166 :group 'org-priorities
3167 :type 'character)
3169 (defcustom org-priority-start-cycle-with-default t
3170 "Non-nil means start with default priority when starting to cycle.
3171 When this is nil, the first step in the cycle will be (depending on the
3172 command used) one higher or lower than the default priority.
3173 See also `org-default-priority'."
3174 :group 'org-priorities
3175 :type 'boolean)
3177 (defcustom org-get-priority-function nil
3178 "Function to extract the priority from a string.
3179 The string is normally the headline. If this is nil Org computes the
3180 priority from the priority cookie like [#A] in the headline. It returns
3181 an integer, increasing by 1000 for each priority level.
3182 The user can set a different function here, which should take a string
3183 as an argument and return the numeric priority."
3184 :group 'org-priorities
3185 :version "24.1"
3186 :type '(choice
3187 (const nil)
3188 (function)))
3190 (defgroup org-time nil
3191 "Options concerning time stamps and deadlines in Org mode."
3192 :tag "Org Time"
3193 :group 'org)
3195 (defcustom org-time-stamp-rounding-minutes '(0 5)
3196 "Number of minutes to round time stamps to.
3197 \\<org-mode-map>\
3198 These are two values, the first applies when first creating a time stamp.
3199 The second applies when changing it with the commands `S-up' and `S-down'.
3200 When changing the time stamp, this means that it will change in steps
3201 of N minutes, as given by the second value.
3203 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3204 numbers should be factors of 60, so for example 5, 10, 15.
3206 When this is larger than 1, you can still force an exact time stamp by using
3207 a double prefix argument to a time stamp command like \
3208 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3209 and by using a prefix arg to `S-up/down' to specify the exact number
3210 of minutes to shift."
3211 :group 'org-time
3212 :get (lambda (var) ; Make sure both elements are there
3213 (if (integerp (default-value var))
3214 (list (default-value var) 5)
3215 (default-value var)))
3216 :type '(list
3217 (integer :tag "when inserting times")
3218 (integer :tag "when modifying times")))
3220 ;; Normalize old customizations of this variable.
3221 (when (integerp org-time-stamp-rounding-minutes)
3222 (setq org-time-stamp-rounding-minutes
3223 (list org-time-stamp-rounding-minutes
3224 org-time-stamp-rounding-minutes)))
3226 (defcustom org-display-custom-times nil
3227 "Non-nil means overlay custom formats over all time stamps.
3228 The formats are defined through the variable `org-time-stamp-custom-formats'.
3229 To turn this on on a per-file basis, insert anywhere in the file:
3230 #+STARTUP: customtime"
3231 :group 'org-time
3232 :set 'set-default
3233 :type 'sexp)
3234 (make-variable-buffer-local 'org-display-custom-times)
3236 (defcustom org-time-stamp-custom-formats
3237 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3238 "Custom formats for time stamps. See `format-time-string' for the syntax.
3239 These are overlaid over the default ISO format if the variable
3240 `org-display-custom-times' is set. Time like %H:%M should be at the
3241 end of the second format. The custom formats are also honored by export
3242 commands, if custom time display is turned on at the time of export."
3243 :group 'org-time
3244 :type 'sexp)
3246 (defun org-time-stamp-format (&optional long inactive)
3247 "Get the right format for a time string."
3248 (let ((f (if long (cdr org-time-stamp-formats)
3249 (car org-time-stamp-formats))))
3250 (if inactive
3251 (concat "[" (substring f 1 -1) "]")
3252 f)))
3254 (defcustom org-time-clocksum-format
3255 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3256 "The format string used when creating CLOCKSUM lines.
3257 This is also used when Org mode generates a time duration.
3259 The value can be a single format string containing two
3260 %-sequences, which will be filled with the number of hours and
3261 minutes in that order.
3263 Alternatively, the value can be a plist associating any of the
3264 keys :years, :months, :weeks, :days, :hours or :minutes with
3265 format strings. The time duration is formatted using only the
3266 time components that are needed and concatenating the results.
3267 If a time unit in absent, it falls back to the next smallest
3268 unit.
3270 The keys :require-years, :require-months, :require-days,
3271 :require-weeks, :require-hours, :require-minutes are also
3272 meaningful. A non-nil value for these keys indicates that the
3273 corresponding time component should always be included, even if
3274 its value is 0.
3277 For example,
3279 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3280 :require-minutes t)
3282 means durations longer than a day will be expressed in days,
3283 hours and minutes, and durations less than a day will always be
3284 expressed in hours and minutes (even for durations less than an
3285 hour).
3287 The value
3289 (:days \"%dd\" :minutes \"%dm\")
3291 means durations longer than a day will be expressed in days and
3292 minutes, and durations less than a day will be expressed entirely
3293 in minutes (even for durations longer than an hour)."
3294 :group 'org-time
3295 :group 'org-clock
3296 :version "24.4"
3297 :package-version '(Org . "8.0")
3298 :type '(choice (string :tag "Format string")
3299 (set :tag "Plist"
3300 (group :inline t (const :tag "Years" :years)
3301 (string :tag "Format string"))
3302 (group :inline t
3303 (const :tag "Always show years" :require-years)
3304 (const t))
3305 (group :inline t (const :tag "Months" :months)
3306 (string :tag "Format string"))
3307 (group :inline t
3308 (const :tag "Always show months" :require-months)
3309 (const t))
3310 (group :inline t (const :tag "Weeks" :weeks)
3311 (string :tag "Format string"))
3312 (group :inline t
3313 (const :tag "Always show weeks" :require-weeks)
3314 (const t))
3315 (group :inline t (const :tag "Days" :days)
3316 (string :tag "Format string"))
3317 (group :inline t
3318 (const :tag "Always show days" :require-days)
3319 (const t))
3320 (group :inline t (const :tag "Hours" :hours)
3321 (string :tag "Format string"))
3322 (group :inline t
3323 (const :tag "Always show hours" :require-hours)
3324 (const t))
3325 (group :inline t (const :tag "Minutes" :minutes)
3326 (string :tag "Format string"))
3327 (group :inline t
3328 (const :tag "Always show minutes" :require-minutes)
3329 (const t)))))
3331 (defcustom org-time-clocksum-use-fractional nil
3332 "When non-nil, `\\[org-clock-display]' uses fractional times.
3333 See `org-time-clocksum-format' for more on time clock formats."
3334 :group 'org-time
3335 :group 'org-clock
3336 :version "24.3"
3337 :type 'boolean)
3339 (defcustom org-time-clocksum-use-effort-durations nil
3340 "When non-nil, `\\[org-clock-display]' uses effort durations.
3341 E.g. by default, one day is considered to be a 8 hours effort,
3342 so a task that has been clocked for 16 hours will be displayed
3343 as during 2 days in the clock display or in the clocktable.
3345 See `org-effort-durations' on how to set effort durations
3346 and `org-time-clocksum-format' for more on time clock formats."
3347 :group 'org-time
3348 :group 'org-clock
3349 :version "24.4"
3350 :package-version '(Org . "8.0")
3351 :type 'boolean)
3353 (defcustom org-time-clocksum-fractional-format "%.2f"
3354 "The format string used when creating CLOCKSUM lines,
3355 or when Org mode generates a time duration, if
3356 `org-time-clocksum-use-fractional' is enabled.
3358 The value can be a single format string containing one
3359 %-sequence, which will be filled with the number of hours as
3360 a float.
3362 Alternatively, the value can be a plist associating any of the
3363 keys :years, :months, :weeks, :days, :hours or :minutes with
3364 a format string. The time duration is formatted using the
3365 largest time unit which gives a non-zero integer part. If all
3366 specified formats have zero integer part, the smallest time unit
3367 is used."
3368 :group 'org-time
3369 :type '(choice (string :tag "Format string")
3370 (set (group :inline t (const :tag "Years" :years)
3371 (string :tag "Format string"))
3372 (group :inline t (const :tag "Months" :months)
3373 (string :tag "Format string"))
3374 (group :inline t (const :tag "Weeks" :weeks)
3375 (string :tag "Format string"))
3376 (group :inline t (const :tag "Days" :days)
3377 (string :tag "Format string"))
3378 (group :inline t (const :tag "Hours" :hours)
3379 (string :tag "Format string"))
3380 (group :inline t (const :tag "Minutes" :minutes)
3381 (string :tag "Format string")))))
3383 (defcustom org-deadline-warning-days 14
3384 "Number of days before expiration during which a deadline becomes active.
3385 This variable governs the display in sparse trees and in the agenda.
3386 When 0 or negative, it means use this number (the absolute value of it)
3387 even if a deadline has a different individual lead time specified.
3389 Custom commands can set this variable in the options section."
3390 :group 'org-time
3391 :group 'org-agenda-daily/weekly
3392 :type 'integer)
3394 (defcustom org-scheduled-delay-days 0
3395 "Number of days before a scheduled item becomes active.
3396 This variable governs the display in sparse trees and in the agenda.
3397 The default value (i.e. 0) means: don't delay scheduled item.
3398 When negative, it means use this number (the absolute value of it)
3399 even if a scheduled item has a different individual delay time
3400 specified.
3402 Custom commands can set this variable in the options section."
3403 :group 'org-time
3404 :group 'org-agenda-daily/weekly
3405 :version "24.4"
3406 :package-version '(Org . "8.0")
3407 :type 'integer)
3409 (defcustom org-read-date-prefer-future t
3410 "Non-nil means assume future for incomplete date input from user.
3411 This affects the following situations:
3412 1. The user gives a month but not a year.
3413 For example, if it is April and you enter \"feb 2\", this will be read
3414 as Feb 2, *next* year. \"May 5\", however, will be this year.
3415 2. The user gives a day, but no month.
3416 For example, if today is the 15th, and you enter \"3\", Org will read
3417 this as the third of *next* month. However, if you enter \"17\",
3418 it will be considered as *this* month.
3420 If you set this variable to the symbol `time', then also the following
3421 will work:
3423 3. If the user gives a time.
3424 If the time is before now, it will be interpreted as tomorrow.
3426 Currently none of this works for ISO week specifications.
3428 When this option is nil, the current day, month and year will always be
3429 used as defaults.
3431 See also `org-agenda-jump-prefer-future'."
3432 :group 'org-time
3433 :type '(choice
3434 (const :tag "Never" nil)
3435 (const :tag "Check month and day" t)
3436 (const :tag "Check month, day, and time" time)))
3438 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3439 "Should the agenda jump command prefer the future for incomplete dates?
3440 The default is to do the same as configured in `org-read-date-prefer-future'.
3441 But you can also set a deviating value here.
3442 This may t or nil, or the symbol `org-read-date-prefer-future'."
3443 :group 'org-agenda
3444 :group 'org-time
3445 :version "24.1"
3446 :type '(choice
3447 (const :tag "Use org-read-date-prefer-future"
3448 org-read-date-prefer-future)
3449 (const :tag "Never" nil)
3450 (const :tag "Always" t)))
3452 (defcustom org-read-date-force-compatible-dates t
3453 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3455 Depending on the system Emacs is running on, certain dates cannot
3456 be represented with the type used internally to represent time.
3457 Dates between 1970-1-1 and 2038-1-1 can always be represented
3458 correctly. Some systems allow for earlier dates, some for later,
3459 some for both. One way to find out it to insert any date into an
3460 Org buffer, putting the cursor on the year and hitting S-up and
3461 S-down to test the range.
3463 When this variable is set to t, the date/time prompt will not let
3464 you specify dates outside the 1970-2037 range, so it is certain that
3465 these dates will work in whatever version of Emacs you are
3466 running, and also that you can move a file from one Emacs implementation
3467 to another. WHenever Org is forcing the year for you, it will display
3468 a message and beep.
3470 When this variable is nil, Org will check if the date is
3471 representable in the specific Emacs implementation you are using.
3472 If not, it will force a year, usually the current year, and beep
3473 to remind you. Currently this setting is not recommended because
3474 the likelihood that you will open your Org files in an Emacs that
3475 has limited date range is not negligible.
3477 A workaround for this problem is to use diary sexp dates for time
3478 stamps outside of this range."
3479 :group 'org-time
3480 :version "24.1"
3481 :type 'boolean)
3483 (defcustom org-read-date-display-live t
3484 "Non-nil means display current interpretation of date prompt live.
3485 This display will be in an overlay, in the minibuffer."
3486 :group 'org-time
3487 :type 'boolean)
3489 (defcustom org-read-date-popup-calendar t
3490 "Non-nil means pop up a calendar when prompting for a date.
3491 In the calendar, the date can be selected with mouse-1. However, the
3492 minibuffer will also be active, and you can simply enter the date as well.
3493 When nil, only the minibuffer will be available."
3494 :group 'org-time
3495 :type 'boolean)
3496 (defvaralias 'org-popup-calendar-for-date-prompt
3497 'org-read-date-popup-calendar)
3499 (defcustom org-extend-today-until 0
3500 "The hour when your day really ends. Must be an integer.
3501 This has influence for the following applications:
3502 - When switching the agenda to \"today\". It it is still earlier than
3503 the time given here, the day recognized as TODAY is actually yesterday.
3504 - When a date is read from the user and it is still before the time given
3505 here, the current date and time will be assumed to be yesterday, 23:59.
3506 Also, timestamps inserted in capture templates follow this rule.
3508 IMPORTANT: This is a feature whose implementation is and likely will
3509 remain incomplete. Really, it is only here because past midnight seems to
3510 be the favorite working time of John Wiegley :-)"
3511 :group 'org-time
3512 :type 'integer)
3514 (defcustom org-use-effective-time nil
3515 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3516 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3517 \"effective time\" of any timestamps between midnight and 8am will be
3518 23:59 of the previous day."
3519 :group 'org-time
3520 :version "24.1"
3521 :type 'boolean)
3523 (defcustom org-use-last-clock-out-time-as-effective-time nil
3524 "When non-nil, use the last clock out time for `org-todo'.
3525 Note that this option has precedence over the combined use of
3526 `org-use-effective-time' and `org-extend-today-until'."
3527 :group 'org-time
3528 :version "24.4"
3529 :package-version '(Org . "8.0")
3530 :type 'boolean)
3532 (defcustom org-edit-timestamp-down-means-later nil
3533 "Non-nil means S-down will increase the time in a time stamp.
3534 When nil, S-up will increase."
3535 :group 'org-time
3536 :type 'boolean)
3538 (defcustom org-calendar-follow-timestamp-change t
3539 "Non-nil means make the calendar window follow timestamp changes.
3540 When a timestamp is modified and the calendar window is visible, it will be
3541 moved to the new date."
3542 :group 'org-time
3543 :type 'boolean)
3545 (defgroup org-tags nil
3546 "Options concerning tags in Org mode."
3547 :tag "Org Tags"
3548 :group 'org)
3550 (defcustom org-tag-alist nil
3551 "Default tags available in Org files.
3553 The value of this variable is an alist. Associations either:
3555 (TAG)
3556 (TAG . SELECT)
3557 (SPECIAL)
3559 where TAG is a tag as a string, SELECT is character, used to
3560 select that tag through the fast tag selection interface, and
3561 SPECIAL is one of the following keywords: `:startgroup',
3562 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3563 `:newline'. These keywords are used to define a hierarchy of
3564 tags. See manual for details.
3566 When this variable is nil, Org mode bases tag input on what is
3567 already in the buffer. The value can be overridden locally by
3568 using a TAGS keyword, e.g.,
3570 #+TAGS: tag1 tag2
3572 See also `org-tag-persistent-alist' to sidestep this behavior."
3573 :group 'org-tags
3574 :type '(repeat
3575 (choice
3576 (cons (string :tag "Tag name")
3577 (character :tag "Access char"))
3578 (const :tag "Start radio group" (:startgroup))
3579 (const :tag "Start tag group, non distinct" (:startgrouptag))
3580 (const :tag "Group tags delimiter" (:grouptags))
3581 (const :tag "End radio group" (:endgroup))
3582 (const :tag "End tag group, non distinct" (:endgrouptag))
3583 (const :tag "New line" (:newline)))))
3585 (defcustom org-tag-persistent-alist nil
3586 "Tags always available in Org files.
3588 The value of this variable is an alist. Associations either:
3590 (TAG)
3591 (TAG . SELECT)
3592 (SPECIAL)
3594 where TAG is a tag as a string, SELECT is a character, used to
3595 select that tag through the fast tag selection interface, and
3596 SPECIAL is one of the following keywords: `:startgroup',
3597 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3598 `:newline'. These keywords are used to define a hierarchy of
3599 tags. See manual for details.
3601 Unlike to `org-tag-alist', tags defined in this variable do not
3602 depend on a local TAGS keyword. Instead, to disable these tags
3603 on a per-file basis, insert anywhere in the file:
3605 #+STARTUP: noptag"
3606 :group 'org-tags
3607 :type '(repeat
3608 (choice
3609 (cons (string :tag "Tag name")
3610 (character :tag "Access char"))
3611 (const :tag "Start radio group" (:startgroup))
3612 (const :tag "Start tag group, non distinct" (:startgrouptag))
3613 (const :tag "Group tags delimiter" (:grouptags))
3614 (const :tag "End radio group" (:endgroup))
3615 (const :tag "End tag group, non distinct" (:endgrouptag))
3616 (const :tag "New line" (:newline)))))
3618 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3619 "If non-nil, always offer completion for all tags of all agenda files.
3620 Instead of customizing this variable directly, you might want to
3621 set it locally for capture buffers, because there no list of
3622 tags in that file can be created dynamically (there are none).
3624 (add-hook \\='org-capture-mode-hook
3625 (lambda ()
3626 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3627 :group 'org-tags
3628 :version "24.1"
3629 :type 'boolean)
3631 (defvar org-file-tags nil
3632 "List of tags that can be inherited by all entries in the file.
3633 The tags will be inherited if the variable `org-use-tag-inheritance'
3634 says they should be.
3635 This variable is populated from #+FILETAGS lines.")
3637 (defcustom org-use-fast-tag-selection 'auto
3638 "Non-nil means use fast tag selection scheme.
3639 This is a special interface to select and deselect tags with single keys.
3640 When nil, fast selection is never used.
3641 When the symbol `auto', fast selection is used if and only if selection
3642 characters for tags have been configured, either through the variable
3643 `org-tag-alist' or through a #+TAGS line in the buffer.
3644 When t, fast selection is always used and selection keys are assigned
3645 automatically if necessary."
3646 :group 'org-tags
3647 :type '(choice
3648 (const :tag "Always" t)
3649 (const :tag "Never" nil)
3650 (const :tag "When selection characters are configured" auto)))
3652 (defcustom org-fast-tag-selection-single-key nil
3653 "Non-nil means fast tag selection exits after first change.
3654 When nil, you have to press RET to exit it.
3655 During fast tag selection, you can toggle this flag with `C-c'.
3656 This variable can also have the value `expert'. In this case, the window
3657 displaying the tags menu is not even shown, until you press C-c again."
3658 :group 'org-tags
3659 :type '(choice
3660 (const :tag "No" nil)
3661 (const :tag "Yes" t)
3662 (const :tag "Expert" expert)))
3664 (defvar org-fast-tag-selection-include-todo nil
3665 "Non-nil means fast tags selection interface will also offer TODO states.
3666 This is an undocumented feature, you should not rely on it.")
3668 (defcustom org-tags-column -77
3669 "The column to which tags should be indented in a headline.
3670 If this number is positive, it specifies the column. If it is negative,
3671 it means that the tags should be flushright to that column. For example,
3672 -80 works well for a normal 80 character screen.
3673 When 0, place tags directly after headline text, with only one space in
3674 between."
3675 :group 'org-tags
3676 :type 'integer)
3678 (defcustom org-auto-align-tags t
3679 "Non-nil keeps tags aligned when modifying headlines.
3680 Some operations (i.e. demoting) change the length of a headline and
3681 therefore shift the tags around. With this option turned on, after
3682 each such operation the tags are again aligned to `org-tags-column'."
3683 :group 'org-tags
3684 :type 'boolean)
3686 (defcustom org-use-tag-inheritance t
3687 "Non-nil means tags in levels apply also for sublevels.
3688 When nil, only the tags directly given in a specific line apply there.
3689 This may also be a list of tags that should be inherited, or a regexp that
3690 matches tags that should be inherited. Additional control is possible
3691 with the variable `org-tags-exclude-from-inheritance' which gives an
3692 explicit list of tags to be excluded from inheritance, even if the value of
3693 `org-use-tag-inheritance' would select it for inheritance.
3695 If this option is t, a match early-on in a tree can lead to a large
3696 number of matches in the subtree when constructing the agenda or creating
3697 a sparse tree. If you only want to see the first match in a tree during
3698 a search, check out the variable `org-tags-match-list-sublevels'."
3699 :group 'org-tags
3700 :type '(choice
3701 (const :tag "Not" nil)
3702 (const :tag "Always" t)
3703 (repeat :tag "Specific tags" (string :tag "Tag"))
3704 (regexp :tag "Tags matched by regexp")))
3706 (defcustom org-tags-exclude-from-inheritance nil
3707 "List of tags that should never be inherited.
3708 This is a way to exclude a few tags from inheritance. For way to do
3709 the opposite, to actively allow inheritance for selected tags,
3710 see the variable `org-use-tag-inheritance'."
3711 :group 'org-tags
3712 :type '(repeat (string :tag "Tag")))
3714 (defun org-tag-inherit-p (tag)
3715 "Check if TAG is one that should be inherited."
3716 (cond
3717 ((member tag org-tags-exclude-from-inheritance) nil)
3718 ((eq org-use-tag-inheritance t) t)
3719 ((not org-use-tag-inheritance) nil)
3720 ((stringp org-use-tag-inheritance)
3721 (string-match org-use-tag-inheritance tag))
3722 ((listp org-use-tag-inheritance)
3723 (member tag org-use-tag-inheritance))
3724 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3726 (defcustom org-tags-match-list-sublevels t
3727 "Non-nil means list also sublevels of headlines matching a search.
3728 This variable applies to tags/property searches, and also to stuck
3729 projects because this search is based on a tags match as well.
3731 When set to the symbol `indented', sublevels are indented with
3732 leading dots.
3734 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3735 the sublevels of a headline matching a tag search often also match
3736 the same search. Listing all of them can create very long lists.
3737 Setting this variable to nil causes subtrees of a match to be skipped.
3739 This variable is semi-obsolete and probably should always be true. It
3740 is better to limit inheritance to certain tags using the variables
3741 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3742 :group 'org-tags
3743 :type '(choice
3744 (const :tag "No, don't list them" nil)
3745 (const :tag "Yes, do list them" t)
3746 (const :tag "List them, indented with leading dots" indented)))
3748 (defcustom org-tags-sort-function nil
3749 "When set, tags are sorted using this function as a comparator."
3750 :group 'org-tags
3751 :type '(choice
3752 (const :tag "No sorting" nil)
3753 (const :tag "Alphabetical" string<)
3754 (const :tag "Reverse alphabetical" string>)
3755 (function :tag "Custom function" nil)))
3757 (defvar org-tags-history nil
3758 "History of minibuffer reads for tags.")
3759 (defvar org-last-tags-completion-table nil
3760 "The last used completion table for tags.")
3761 (defvar org-after-tags-change-hook nil
3762 "Hook that is run after the tags in a line have changed.")
3764 (defgroup org-properties nil
3765 "Options concerning properties in Org mode."
3766 :tag "Org Properties"
3767 :group 'org)
3769 (defcustom org-property-format "%-10s %s"
3770 "How property key/value pairs should be formatted by `indent-line'.
3771 When `indent-line' hits a property definition, it will format the line
3772 according to this format, mainly to make sure that the values are
3773 lined-up with respect to each other."
3774 :group 'org-properties
3775 :type 'string)
3777 (defcustom org-properties-postprocess-alist nil
3778 "Alist of properties and functions to adjust inserted values.
3779 Elements of this alist must be of the form
3781 ([string] [function])
3783 where [string] must be a property name and [function] must be a
3784 lambda expression: this lambda expression must take one argument,
3785 the value to adjust, and return the new value as a string.
3787 For example, this element will allow the property \"Remaining\"
3788 to be updated wrt the relation between the \"Effort\" property
3789 and the clock summary:
3791 ((\"Remaining\" (lambda(value)
3792 (let ((clocksum (org-clock-sum-current-item))
3793 (effort (org-duration-string-to-minutes
3794 (org-entry-get (point) \"Effort\"))))
3795 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3796 :group 'org-properties
3797 :version "24.1"
3798 :type '(alist :key-type (string :tag "Property")
3799 :value-type (function :tag "Function")))
3801 (defcustom org-use-property-inheritance nil
3802 "Non-nil means properties apply also for sublevels.
3804 This setting is chiefly used during property searches. Turning it on can
3805 cause significant overhead when doing a search, which is why it is not
3806 on by default.
3808 When nil, only the properties directly given in the current entry count.
3809 When t, every property is inherited. The value may also be a list of
3810 properties that should have inheritance, or a regular expression matching
3811 properties that should be inherited.
3813 However, note that some special properties use inheritance under special
3814 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3815 and the properties ending in \"_ALL\" when they are used as descriptor
3816 for valid values of a property.
3818 Note for programmers:
3819 When querying an entry with `org-entry-get', you can control if inheritance
3820 should be used. By default, `org-entry-get' looks only at the local
3821 properties. You can request inheritance by setting the inherit argument
3822 to t (to force inheritance) or to `selective' (to respect the setting
3823 in this variable)."
3824 :group 'org-properties
3825 :type '(choice
3826 (const :tag "Not" nil)
3827 (const :tag "Always" t)
3828 (repeat :tag "Specific properties" (string :tag "Property"))
3829 (regexp :tag "Properties matched by regexp")))
3831 (defun org-property-inherit-p (property)
3832 "Return a non-nil value if PROPERTY should be inherited."
3833 (cond
3834 ((eq org-use-property-inheritance t) t)
3835 ((not org-use-property-inheritance) nil)
3836 ((stringp org-use-property-inheritance)
3837 (string-match org-use-property-inheritance property))
3838 ((listp org-use-property-inheritance)
3839 (member-ignore-case property org-use-property-inheritance))
3840 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3842 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3843 "The default column format, if no other format has been defined.
3844 This variable can be set on the per-file basis by inserting a line
3846 #+COLUMNS: %25ITEM ....."
3847 :group 'org-properties
3848 :type 'string)
3850 (defcustom org-columns-ellipses ".."
3851 "The ellipses to be used when a field in column view is truncated.
3852 When this is the empty string, as many characters as possible are shown,
3853 but then there will be no visual indication that the field has been truncated.
3854 When this is a string of length N, the last N characters of a truncated
3855 field are replaced by this string. If the column is narrower than the
3856 ellipses string, only part of the ellipses string will be shown."
3857 :group 'org-properties
3858 :type 'string)
3860 (defconst org-global-properties-fixed
3861 '(("VISIBILITY_ALL" . "folded children content all")
3862 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3863 "List of property/value pairs that can be inherited by any entry.
3865 These are fixed values, for the preset properties. The user variable
3866 that can be used to add to this list is `org-global-properties'.
3868 The entries in this list are cons cells where the car is a property
3869 name and cdr is a string with the value. If the value represents
3870 multiple items like an \"_ALL\" property, separate the items by
3871 spaces.")
3873 (defcustom org-global-properties nil
3874 "List of property/value pairs that can be inherited by any entry.
3876 This list will be combined with the constant `org-global-properties-fixed'.
3878 The entries in this list are cons cells where the car is a property
3879 name and cdr is a string with the value.
3881 You can set buffer-local values for the same purpose in the variable
3882 `org-file-properties' this by adding lines like
3884 #+PROPERTY: NAME VALUE"
3885 :group 'org-properties
3886 :type '(repeat
3887 (cons (string :tag "Property")
3888 (string :tag "Value"))))
3890 (defvar-local org-file-properties nil
3891 "List of property/value pairs that can be inherited by any entry.
3892 Valid for the current buffer.
3893 This variable is populated from #+PROPERTY lines.")
3895 (defgroup org-agenda nil
3896 "Options concerning agenda views in Org mode."
3897 :tag "Org Agenda"
3898 :group 'org)
3900 (defvar-local org-category nil
3901 "Variable used by org files to set a category for agenda display.
3902 Such files should use a file variable to set it, for example
3904 # -*- mode: org; org-category: \"ELisp\"
3906 or contain a special line
3908 #+CATEGORY: ELisp
3910 If the file does not specify a category, then file's base name
3911 is used instead.")
3912 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3914 (defcustom org-agenda-files nil
3915 "The files to be used for agenda display.
3917 If an entry is a directory, all files in that directory that are matched
3918 by `org-agenda-file-regexp' will be part of the file list.
3920 If the value of the variable is not a list but a single file name, then
3921 the list of agenda files is actually stored and maintained in that file,
3922 one agenda file per line. In this file paths can be given relative to
3923 `org-directory'. Tilde expansion and environment variable substitution
3924 are also made.
3926 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3927 and removed with `\\[org-remove-file]'."
3928 :group 'org-agenda
3929 :type '(choice
3930 (repeat :tag "List of files and directories" file)
3931 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3933 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3934 "Regular expression to match files for `org-agenda-files'.
3935 If any element in the list in that variable contains a directory instead
3936 of a normal file, all files in that directory that are matched by this
3937 regular expression will be included."
3938 :group 'org-agenda
3939 :type 'regexp)
3941 (defcustom org-agenda-text-search-extra-files nil
3942 "List of extra files to be searched by text search commands.
3943 These files will be searched in addition to the agenda files by the
3944 commands `org-search-view' (`\\[org-agenda] s') \
3945 and `org-occur-in-agenda-files'.
3946 Note that these files will only be searched for text search commands,
3947 not for the other agenda views like todo lists, tag searches or the weekly
3948 agenda. This variable is intended to list notes and possibly archive files
3949 that should also be searched by these two commands.
3950 In fact, if the first element in the list is the symbol `agenda-archives',
3951 then all archive files of all agenda files will be added to the search
3952 scope."
3953 :group 'org-agenda
3954 :type '(set :greedy t
3955 (const :tag "Agenda Archives" agenda-archives)
3956 (repeat :inline t (file))))
3958 (defvaralias 'org-agenda-multi-occur-extra-files
3959 'org-agenda-text-search-extra-files)
3961 (defcustom org-agenda-skip-unavailable-files nil
3962 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3963 A nil value means to remove them, after a query, from the list."
3964 :group 'org-agenda
3965 :type 'boolean)
3967 (defcustom org-calendar-to-agenda-key [?c]
3968 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3969 The command `org-calendar-goto-agenda' will be bound to this key. The
3970 default is the character `c' because then `c' can be used to switch back and
3971 forth between agenda and calendar."
3972 :group 'org-agenda
3973 :type 'sexp)
3975 (defcustom org-calendar-insert-diary-entry-key [?i]
3976 "The key to be installed in `calendar-mode-map' for adding diary entries.
3977 This option is irrelevant until `org-agenda-diary-file' has been configured
3978 to point to an Org file. When that is the case, the command
3979 `org-agenda-diary-entry' will be bound to the key given here, by default
3980 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3981 if you want to continue doing this, you need to change this to a different
3982 key."
3983 :group 'org-agenda
3984 :type 'sexp)
3986 (defcustom org-agenda-diary-file 'diary-file
3987 "File to which to add new entries with the `i' key in agenda and calendar.
3988 When this is the symbol `diary-file', the functionality in the Emacs
3989 calendar will be used to add entries to the `diary-file'. But when this
3990 points to a file, `org-agenda-diary-entry' will be used instead."
3991 :group 'org-agenda
3992 :type '(choice
3993 (const :tag "The standard Emacs diary file" diary-file)
3994 (file :tag "Special Org file diary entries")))
3996 (eval-after-load "calendar"
3997 '(progn
3998 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3999 'org-calendar-goto-agenda)
4000 (add-hook 'calendar-mode-hook
4001 (lambda ()
4002 (unless (eq org-agenda-diary-file 'diary-file)
4003 (define-key calendar-mode-map
4004 org-calendar-insert-diary-entry-key
4005 'org-agenda-diary-entry))))))
4007 (defgroup org-latex nil
4008 "Options for embedding LaTeX code into Org mode."
4009 :tag "Org LaTeX"
4010 :group 'org)
4012 (defcustom org-format-latex-options
4013 '(:foreground default :background default :scale 1.0
4014 :html-foreground "Black" :html-background "Transparent"
4015 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4016 "Options for creating images from LaTeX fragments.
4017 This is a property list with the following properties:
4018 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4019 `default' means use the foreground of the default face.
4020 `auto' means use the foreground from the text face.
4021 :background the background color, or \"Transparent\".
4022 `default' means use the background of the default face.
4023 `auto' means use the background from the text face.
4024 :scale a scaling factor for the size of the images, to get more pixels
4025 :html-foreground, :html-background, :html-scale
4026 the same numbers for HTML export.
4027 :matchers a list indicating which matchers should be used to
4028 find LaTeX fragments. Valid members of this list are:
4029 \"begin\" find environments
4030 \"$1\" find single characters surrounded by $.$
4031 \"$\" find math expressions surrounded by $...$
4032 \"$$\" find math expressions surrounded by $$....$$
4033 \"\\(\" find math expressions surrounded by \\(...\\)
4034 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4035 :group 'org-latex
4036 :type 'plist)
4038 (defcustom org-format-latex-signal-error t
4039 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4040 When nil, just push out a message."
4041 :group 'org-latex
4042 :version "24.1"
4043 :type 'boolean)
4045 (defcustom org-latex-to-mathml-jar-file nil
4046 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4047 Use this to specify additional executable file say a jar file.
4049 When using MathToWeb as the converter, specify the full-path to
4050 your mathtoweb.jar file."
4051 :group 'org-latex
4052 :version "24.1"
4053 :type '(choice
4054 (const :tag "None" nil)
4055 (file :tag "JAR file" :must-match t)))
4057 (defcustom org-latex-to-mathml-convert-command nil
4058 "Command to convert LaTeX fragments to MathML.
4059 Replace format-specifiers in the command as noted below and use
4060 `shell-command' to convert LaTeX to MathML.
4061 %j: Executable file in fully expanded form as specified by
4062 `org-latex-to-mathml-jar-file'.
4063 %I: Input LaTeX file in fully expanded form.
4064 %i: The latex fragment to be converted.
4065 %o: Output MathML file.
4067 This command is used by `org-create-math-formula'.
4069 When using MathToWeb as the converter, set this option to
4070 \"java -jar %j -unicode -force -df %o %I\".
4072 When using LaTeXML set this option to
4073 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4074 :group 'org-latex
4075 :version "24.1"
4076 :type '(choice
4077 (const :tag "None" nil)
4078 (string :tag "\nShell command")))
4080 (defcustom org-preview-latex-default-process 'dvipng
4081 "The default process to convert LaTeX fragments to image files.
4082 All available processes and theirs documents can be found in
4083 `org-preview-latex-process-alist', which see."
4084 :group 'org-latex
4085 :version "26.1"
4086 :package-version '(Org . "9.0")
4087 :type 'symbol)
4089 (defcustom org-preview-latex-process-alist
4090 '((dvipng
4091 :programs ("latex" "dvipng")
4092 :description "dvi > png"
4093 :message "you need to install the programs: latex and dvipng."
4094 :image-input-type "dvi"
4095 :image-output-type "png"
4096 :image-size-adjust (1.0 . 1.0)
4097 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4098 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4099 (dvisvgm
4100 :programs ("latex" "dvisvgm")
4101 :description "dvi > svg"
4102 :message "you need to install the programs: latex and dvisvgm."
4103 :use-xcolor t
4104 :image-input-type "dvi"
4105 :image-output-type "svg"
4106 :image-size-adjust (1.7 . 1.5)
4107 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4108 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4109 (imagemagick
4110 :programs ("latex" "convert")
4111 :description "pdf > png"
4112 :message "you need to install the programs: latex and imagemagick."
4113 :use-xcolor t
4114 :image-input-type "pdf"
4115 :image-output-type "png"
4116 :image-size-adjust (1.0 . 1.0)
4117 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4118 :image-converter
4119 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4120 "Definitions of external processes for LaTeX previewing.
4121 Org mode can use some external commands to generate TeX snippet's images for
4122 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4123 `org-create-formula-image' how to call them.
4125 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4126 PROPERTIES accepts the following attributes:
4128 :programs list of strings, required programs.
4129 :description string, describe the process.
4130 :message string, message it when required programs cannot be found.
4131 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4132 :image-output-type string, output file type of image converter (e.g., \"png\").
4133 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4134 deal with background and foreground color of image.
4135 Otherwise, dvipng style background and foregroud color
4136 format are generated. You may then refer to them in
4137 command options with \"%F\" and \"%B\".
4138 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4139 image size showed in buffer and the cdr element is for
4140 HTML file. This option is only useful for process
4141 developers, users should use variable
4142 `org-format-latex-options' instead.
4143 :post-clean list of strings, files matched are to be cleaned up once
4144 the image is generated. When nil, the files with \".dvi\",
4145 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4146 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4147 be cleaned up.
4148 :latex-header list of strings, the LaTeX header of the snippet file.
4149 When nil, the fallback value is used instead, which is
4150 controlled by `org-format-latex-header',
4151 `org-latex-default-packages-alist' and
4152 `org-latex-packages-alist', which see.
4153 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4154 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4155 replaced with values defined below.
4156 :image-converter list of image converter commands strings. Each of them is
4157 given to the shell and supports any of the following
4158 place-holders defined below.
4160 Place-holders used by `:image-converter' and `:latex-compiler':
4162 %f input file name
4163 %b base name of input file
4164 %o base directory of input file
4165 %O absolute output file name
4167 Place-holders only used by `:image-converter':
4169 %F foreground of image
4170 %B background of image
4171 %D dpi, which is used to adjust image size by some processing commands.
4172 %S the image size scale ratio, which is used to adjust image size by some
4173 processing commands."
4174 :group 'org-latex
4175 :version "26.1"
4176 :package-version '(Org . "9.0")
4177 :type '(alist :tag "LaTeX to image backends"
4178 :value-type (plist)))
4180 (defcustom org-preview-latex-image-directory "ltximg/"
4181 "Path to store latex preview images.
4182 A relative path here creates many directories relative to the
4183 processed org files paths. An absolute path puts all preview
4184 images at the same place."
4185 :group 'org-latex
4186 :version "26.1"
4187 :package-version '(Org . "9.0")
4188 :type 'string)
4190 (defun org-format-latex-mathml-available-p ()
4191 "Return t if `org-latex-to-mathml-convert-command' is usable."
4192 (save-match-data
4193 (when (and (boundp 'org-latex-to-mathml-convert-command)
4194 org-latex-to-mathml-convert-command)
4195 (let ((executable (car (split-string
4196 org-latex-to-mathml-convert-command))))
4197 (when (executable-find executable)
4198 (if (string-match
4199 "%j" org-latex-to-mathml-convert-command)
4200 (file-readable-p org-latex-to-mathml-jar-file)
4201 t))))))
4203 (defcustom org-format-latex-header "\\documentclass{article}
4204 \\usepackage[usenames]{color}
4205 \[PACKAGES]
4206 \[DEFAULT-PACKAGES]
4207 \\pagestyle{empty} % do not remove
4208 % The settings below are copied from fullpage.sty
4209 \\setlength{\\textwidth}{\\paperwidth}
4210 \\addtolength{\\textwidth}{-3cm}
4211 \\setlength{\\oddsidemargin}{1.5cm}
4212 \\addtolength{\\oddsidemargin}{-2.54cm}
4213 \\setlength{\\evensidemargin}{\\oddsidemargin}
4214 \\setlength{\\textheight}{\\paperheight}
4215 \\addtolength{\\textheight}{-\\headheight}
4216 \\addtolength{\\textheight}{-\\headsep}
4217 \\addtolength{\\textheight}{-\\footskip}
4218 \\addtolength{\\textheight}{-3cm}
4219 \\setlength{\\topmargin}{1.5cm}
4220 \\addtolength{\\topmargin}{-2.54cm}"
4221 "The document header used for processing LaTeX fragments.
4222 It is imperative that this header make sure that no page number
4223 appears on the page. The package defined in the variables
4224 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4225 will either replace the placeholder \"[PACKAGES]\" in this
4226 header, or they will be appended."
4227 :group 'org-latex
4228 :type 'string)
4230 (defun org-set-packages-alist (var val)
4231 "Set the packages alist and make sure it has 3 elements per entry."
4232 (set var (mapcar (lambda (x)
4233 (if (and (consp x) (= (length x) 2))
4234 (list (car x) (nth 1 x) t)
4236 val)))
4238 (defun org-get-packages-alist (var)
4239 "Get the packages alist and make sure it has 3 elements per entry."
4240 (mapcar (lambda (x)
4241 (if (and (consp x) (= (length x) 2))
4242 (list (car x) (nth 1 x) t)
4244 (default-value var)))
4246 (defcustom org-latex-default-packages-alist
4247 '(("AUTO" "inputenc" t ("pdflatex"))
4248 ("T1" "fontenc" t ("pdflatex"))
4249 ("" "graphicx" t)
4250 ("" "grffile" t)
4251 ("" "longtable" nil)
4252 ("" "wrapfig" nil)
4253 ("" "rotating" nil)
4254 ("normalem" "ulem" t)
4255 ("" "amsmath" t)
4256 ("" "textcomp" t)
4257 ("" "amssymb" t)
4258 ("" "capt-of" nil)
4259 ("" "hyperref" nil))
4260 "Alist of default packages to be inserted in the header.
4262 Change this only if one of the packages here causes an
4263 incompatibility with another package you are using.
4265 The packages in this list are needed by one part or another of
4266 Org mode to function properly:
4268 - inputenc, fontenc: for basic font and character selection
4269 - graphicx: for including images
4270 - grffile: allow periods and spaces in graphics file names
4271 - longtable: For multipage tables
4272 - wrapfig: for figure placement
4273 - rotating: for sideways figures and tables
4274 - ulem: for underline and strike-through
4275 - amsmath: for subscript and superscript and math environments
4276 - textcomp, amssymb: for various symbols used
4277 for interpreting the entities in `org-entities'. You can skip
4278 some of these packages if you don't use any of their symbols.
4279 - capt-of: for captions outside of floats
4280 - hyperref: for cross references
4282 Therefore you should not modify this variable unless you know
4283 what you are doing. The one reason to change it anyway is that
4284 you might be loading some other package that conflicts with one
4285 of the default packages. Each element is either a cell or
4286 a string.
4288 A cell is of the format
4290 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4292 If SNIPPET-FLAG is non-nil, the package also needs to be included
4293 when compiling LaTeX snippets into images for inclusion into
4294 non-LaTeX output. COMPILERS is a list of compilers that should
4295 include the package, see `org-latex-compiler'. If the document
4296 compiler is not in the list, and the list is non-nil, the package
4297 will not be inserted in the final document.
4299 A string will be inserted as-is in the header of the document."
4300 :group 'org-latex
4301 :group 'org-export-latex
4302 :set 'org-set-packages-alist
4303 :get 'org-get-packages-alist
4304 :version "26.1"
4305 :package-version '(Org . "8.3")
4306 :type '(repeat
4307 (choice
4308 (list :tag "options/package pair"
4309 (string :tag "options")
4310 (string :tag "package")
4311 (boolean :tag "Snippet"))
4312 (string :tag "A line of LaTeX"))))
4314 (defcustom org-latex-packages-alist nil
4315 "Alist of packages to be inserted in every LaTeX header.
4317 These will be inserted after `org-latex-default-packages-alist'.
4318 Each element is either a cell or a string.
4320 A cell is of the format:
4322 (\"options\" \"package\" SNIPPET-FLAG)
4324 SNIPPET-FLAG, when non-nil, indicates that this package is also
4325 needed when turning LaTeX snippets into images for inclusion into
4326 non-LaTeX output.
4328 A string will be inserted as-is in the header of the document.
4330 Make sure that you only list packages here which:
4332 - you want in every file;
4333 - do not conflict with the setup in `org-format-latex-header';
4334 - do not conflict with the default packages in
4335 `org-latex-default-packages-alist'."
4336 :group 'org-latex
4337 :group 'org-export-latex
4338 :set 'org-set-packages-alist
4339 :get 'org-get-packages-alist
4340 :type '(repeat
4341 (choice
4342 (list :tag "options/package pair"
4343 (string :tag "options")
4344 (string :tag "package")
4345 (boolean :tag "Snippet"))
4346 (string :tag "A line of LaTeX"))))
4348 (defgroup org-appearance nil
4349 "Settings for Org mode appearance."
4350 :tag "Org Appearance"
4351 :group 'org)
4353 (defcustom org-level-color-stars-only nil
4354 "Non-nil means fontify only the stars in each headline.
4355 When nil, the entire headline is fontified.
4356 Changing it requires restart of `font-lock-mode' to become effective
4357 also in regions already fontified."
4358 :group 'org-appearance
4359 :type 'boolean)
4361 (defcustom org-hide-leading-stars nil
4362 "Non-nil means hide the first N-1 stars in a headline.
4363 This works by using the face `org-hide' for these stars. This
4364 face is white for a light background, and black for a dark
4365 background. You may have to customize the face `org-hide' to
4366 make this work.
4367 Changing it requires restart of `font-lock-mode' to become effective
4368 also in regions already fontified.
4369 You may also set this on a per-file basis by adding one of the following
4370 lines to the buffer:
4372 #+STARTUP: hidestars
4373 #+STARTUP: showstars"
4374 :group 'org-appearance
4375 :type 'boolean)
4377 (defcustom org-hidden-keywords nil
4378 "List of symbols corresponding to keywords to be hidden the org buffer.
4379 For example, a value \\='(title) for this list will make the document's title
4380 appear in the buffer without the initial #+TITLE: keyword."
4381 :group 'org-appearance
4382 :version "24.1"
4383 :type '(set (const :tag "#+AUTHOR" author)
4384 (const :tag "#+DATE" date)
4385 (const :tag "#+EMAIL" email)
4386 (const :tag "#+TITLE" title)))
4388 (defcustom org-custom-properties nil
4389 "List of properties (as strings) with a special meaning.
4390 The default use of these custom properties is to let the user
4391 hide them with `org-toggle-custom-properties-visibility'."
4392 :group 'org-properties
4393 :group 'org-appearance
4394 :version "24.3"
4395 :type '(repeat (string :tag "Property Name")))
4397 (defcustom org-fontify-done-headline nil
4398 "Non-nil means change the face of a headline if it is marked DONE.
4399 Normally, only the TODO/DONE keyword indicates the state of a headline.
4400 When this is non-nil, the headline after the keyword is set to the
4401 `org-headline-done' as an additional indication."
4402 :group 'org-appearance
4403 :type 'boolean)
4405 (defcustom org-fontify-emphasized-text t
4406 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4407 Changing this variable requires a restart of Emacs to take effect."
4408 :group 'org-appearance
4409 :type 'boolean)
4411 (defcustom org-fontify-whole-heading-line nil
4412 "Non-nil means fontify the whole line for headings.
4413 This is useful when setting a background color for the
4414 org-level-* faces."
4415 :group 'org-appearance
4416 :type 'boolean)
4418 (defcustom org-highlight-latex-and-related nil
4419 "Non-nil means highlight LaTeX related syntax in the buffer.
4420 When non nil, the value should be a list containing any of the
4421 following symbols:
4422 `latex' Highlight LaTeX snippets and environments.
4423 `script' Highlight subscript and superscript.
4424 `entities' Highlight entities."
4425 :group 'org-appearance
4426 :version "24.4"
4427 :package-version '(Org . "8.0")
4428 :type '(choice
4429 (const :tag "No highlighting" nil)
4430 (set :greedy t :tag "Highlight"
4431 (const :tag "LaTeX snippets and environments" latex)
4432 (const :tag "Subscript and superscript" script)
4433 (const :tag "Entities" entities))))
4435 (defcustom org-hide-emphasis-markers nil
4436 "Non-nil mean font-lock should hide the emphasis marker characters."
4437 :group 'org-appearance
4438 :type 'boolean)
4440 (defcustom org-hide-macro-markers nil
4441 "Non-nil mean font-lock should hide the brackets marking macro calls."
4442 :group 'org-appearance
4443 :type 'boolean)
4445 (defcustom org-pretty-entities nil
4446 "Non-nil means show entities as UTF8 characters.
4447 When nil, the \\name form remains in the buffer."
4448 :group 'org-appearance
4449 :version "24.1"
4450 :type 'boolean)
4452 (defcustom org-pretty-entities-include-sub-superscripts t
4453 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4454 :group 'org-appearance
4455 :version "24.1"
4456 :type 'boolean)
4458 (defvar org-emph-re nil
4459 "Regular expression for matching emphasis.
4460 After a match, the match groups contain these elements:
4461 0 The match of the full regular expression, including the characters
4462 before and after the proper match
4463 1 The character before the proper match, or empty at beginning of line
4464 2 The proper match, including the leading and trailing markers
4465 3 The leading marker like * or /, indicating the type of highlighting
4466 4 The text between the emphasis markers, not including the markers
4467 5 The character after the match, empty at the end of a line")
4468 (defvar org-verbatim-re nil
4469 "Regular expression for matching verbatim text.")
4470 (defvar org-emphasis-regexp-components) ; defined just below
4471 (defvar org-emphasis-alist) ; defined just below
4472 (defun org-set-emph-re (var val)
4473 "Set variable and compute the emphasis regular expression."
4474 (set var val)
4475 (when (and (boundp 'org-emphasis-alist)
4476 (boundp 'org-emphasis-regexp-components)
4477 org-emphasis-alist org-emphasis-regexp-components)
4478 (let* ((e org-emphasis-regexp-components)
4479 (pre (car e))
4480 (post (nth 1 e))
4481 (border (nth 2 e))
4482 (body (nth 3 e))
4483 (nl (nth 4 e))
4484 (body1 (concat body "*?"))
4485 (markers (mapconcat 'car org-emphasis-alist ""))
4486 (vmarkers (mapconcat
4487 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4488 org-emphasis-alist "")))
4489 ;; make sure special characters appear at the right position in the class
4490 (if (string-match "\\^" markers)
4491 (setq markers (concat (replace-match "" t t markers) "^")))
4492 (if (string-match "-" markers)
4493 (setq markers (concat (replace-match "" t t markers) "-")))
4494 (if (string-match "\\^" vmarkers)
4495 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4496 (if (string-match "-" vmarkers)
4497 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4498 (if (> nl 0)
4499 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4500 (int-to-string nl) "\\}")))
4501 ;; Make the regexp
4502 (setq org-emph-re
4503 (concat "\\([" pre "]\\|^\\)"
4504 "\\("
4505 "\\([" markers "]\\)"
4506 "\\("
4507 "[^" border "]\\|"
4508 "[^" border "]"
4509 body1
4510 "[^" border "]"
4511 "\\)"
4512 "\\3\\)"
4513 "\\([" post "]\\|$\\)"))
4514 (setq org-verbatim-re
4515 (concat "\\([" pre "]\\|^\\)"
4516 "\\("
4517 "\\([" vmarkers "]\\)"
4518 "\\("
4519 "[^" border "]\\|"
4520 "[^" border "]"
4521 body1
4522 "[^" border "]"
4523 "\\)"
4524 "\\3\\)"
4525 "\\([" post "]\\|$\\)")))))
4527 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4528 ;; set this option proved cumbersome. See this message/thread:
4529 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4530 (defvar org-emphasis-regexp-components
4531 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4532 "Components used to build the regular expression for emphasis.
4533 This is a list with five entries. Terminology: In an emphasis string
4534 like \" *strong word* \", we call the initial space PREMATCH, the final
4535 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4536 and \"trong wor\" is the body. The different components in this variable
4537 specify what is allowed/forbidden in each part:
4539 pre Chars allowed as prematch. Beginning of line will be allowed too.
4540 post Chars allowed as postmatch. End of line will be allowed too.
4541 border The chars *forbidden* as border characters.
4542 body-regexp A regexp like \".\" to match a body character. Don't use
4543 non-shy groups here, and don't allow newline here.
4544 newline The maximum number of newlines allowed in an emphasis exp.
4546 You need to reload Org or to restart Emacs after customizing this.")
4548 (defcustom org-emphasis-alist
4549 '(("*" bold)
4550 ("/" italic)
4551 ("_" underline)
4552 ("=" org-verbatim verbatim)
4553 ("~" org-code verbatim)
4554 ("+" (:strike-through t)))
4555 "Alist of characters and faces to emphasize text.
4556 Text starting and ending with a special character will be emphasized,
4557 for example *bold*, _underlined_ and /italic/. This variable sets the
4558 marker characters and the face to be used by font-lock for highlighting
4559 in Org buffers.
4561 You need to reload Org or to restart Emacs after customizing this."
4562 :group 'org-appearance
4563 :set 'org-set-emph-re
4564 :version "24.4"
4565 :package-version '(Org . "8.0")
4566 :type '(repeat
4567 (list
4568 (string :tag "Marker character")
4569 (choice
4570 (face :tag "Font-lock-face")
4571 (plist :tag "Face property list"))
4572 (option (const verbatim)))))
4574 (defvar org-protecting-blocks '("src" "example" "export")
4575 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4576 This is needed for font-lock setup.")
4578 ;;; Functions and variables from their packages
4579 ;; Declared here to avoid compiler warnings
4580 (defvar mark-active)
4582 ;; Various packages
4583 (declare-function calc-eval "calc" (str &optional separator &rest args))
4584 (declare-function calendar-forward-day "cal-move" (arg))
4585 (declare-function calendar-goto-date "cal-move" (date))
4586 (declare-function calendar-goto-today "cal-move" ())
4587 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4588 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4589 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4590 (declare-function cdlatex-tab "ext:cdlatex" ())
4591 (declare-function dired-get-filename
4592 "dired"
4593 (&optional localp no-error-if-not-filep))
4594 (declare-function iswitchb-read-buffer
4595 "iswitchb"
4596 (prompt &optional
4597 default require-match _predicate start matches-set))
4598 (declare-function org-agenda-change-all-lines
4599 "org-agenda"
4600 (newhead hdmarker &optional fixface just-this))
4601 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4602 "org-agenda"
4603 (&optional end))
4604 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4605 (declare-function org-agenda-format-item
4606 "org-agenda"
4607 (extra txt &optional level category tags dotime
4608 remove-re habitp))
4609 (declare-function org-agenda-maybe-redo "org-agenda" ())
4610 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4611 (declare-function org-agenda-save-markers-for-cut-and-paste
4612 "org-agenda"
4613 (beg end))
4614 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4615 (declare-function org-agenda-skip "org-agenda" ())
4616 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4617 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4618 (declare-function org-indent-mode "org-indent" (&optional arg))
4619 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4620 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4621 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4622 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4623 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4624 (declare-function parse-time-string "parse-time" (string))
4625 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4627 (defvar align-mode-rules-list)
4628 (defvar calc-embedded-close-formula)
4629 (defvar calc-embedded-open-formula)
4630 (defvar calc-embedded-open-mode)
4631 (defvar font-lock-unfontify-region-function)
4632 (defvar iswitchb-temp-buflist)
4633 (defvar org-agenda-tags-todo-honor-ignore-options)
4634 (defvar remember-data-file)
4635 (defvar texmathp-why)
4637 ;;;###autoload
4638 (defun turn-on-orgtbl ()
4639 "Unconditionally turn on `orgtbl-mode'."
4640 (require 'org-table)
4641 (orgtbl-mode 1))
4643 (defun org-at-table-p (&optional table-type)
4644 "Non-nil if the cursor is inside an Org table.
4645 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4646 If `org-enable-table-editor' is nil, return nil unconditionally."
4647 (and
4648 org-enable-table-editor
4649 (save-excursion
4650 (beginning-of-line)
4651 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4652 (or (not (derived-mode-p 'org-mode))
4653 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4654 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4656 (defun org-at-table.el-p ()
4657 "Non-nil when point is at a table.el table."
4658 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4659 (let ((element (org-element-at-point)))
4660 (and (eq (org-element-type element) 'table)
4661 (eq (org-element-property :type element) 'table.el)))))
4663 (defun org-at-table-hline-p ()
4664 "Non-nil when point is inside a hline in a table.
4665 Assume point is already in a table. If `org-enable-table-editor'
4666 is nil, return nil unconditionally."
4667 (and org-enable-table-editor
4668 (save-excursion
4669 (beginning-of-line)
4670 (looking-at org-table-hline-regexp))))
4672 (defun org-table-map-tables (function &optional quietly)
4673 "Apply FUNCTION to the start of all tables in the buffer."
4674 (org-with-wide-buffer
4675 (goto-char (point-min))
4676 (while (re-search-forward org-table-any-line-regexp nil t)
4677 (unless quietly
4678 (message "Mapping tables: %d%%"
4679 (floor (* 100.0 (point)) (buffer-size))))
4680 (beginning-of-line 1)
4681 (when (and (looking-at org-table-line-regexp)
4682 ;; Exclude tables in src/example/verbatim/clocktable blocks
4683 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4684 (save-excursion (funcall function))
4685 (or (looking-at org-table-line-regexp)
4686 (forward-char 1)))
4687 (re-search-forward org-table-any-border-regexp nil 1)))
4688 (unless quietly (message "Mapping tables: done")))
4690 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4691 (declare-function org-clock-update-mode-line "org-clock" ())
4692 (declare-function org-resolve-clocks "org-clock"
4693 (&optional also-non-dangling-p prompt last-valid))
4695 (defun org-at-TBLFM-p (&optional pos)
4696 "Non-nil when point (or POS) is in #+TBLFM line."
4697 (save-excursion
4698 (goto-char (or pos (point)))
4699 (beginning-of-line)
4700 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4701 (eq (org-element-type (org-element-at-point)) 'table))))
4703 (defvar org-clock-start-time)
4704 (defvar org-clock-marker (make-marker)
4705 "Marker recording the last clock-in.")
4706 (defvar org-clock-hd-marker (make-marker)
4707 "Marker recording the last clock-in, but the headline position.")
4708 (defvar org-clock-heading ""
4709 "The heading of the current clock entry.")
4710 (defun org-clock-is-active ()
4711 "Return the buffer where the clock is currently running.
4712 Return nil if no clock is running."
4713 (marker-buffer org-clock-marker))
4715 (defun org-check-running-clock ()
4716 "Check if the current buffer contains the running clock.
4717 If yes, offer to stop it and to save the buffer with the changes."
4718 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4719 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4720 (buffer-name))))
4721 (org-clock-out)
4722 (when (y-or-n-p "Save changed buffer?")
4723 (save-buffer))))
4725 (defun org-clocktable-try-shift (dir n)
4726 "Check if this line starts a clock table, if yes, shift the time block."
4727 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4728 (org-clocktable-shift dir n)))
4730 ;;;###autoload
4731 (defun org-clock-persistence-insinuate ()
4732 "Set up hooks for clock persistence."
4733 (require 'org-clock)
4734 (add-hook 'org-mode-hook 'org-clock-load)
4735 (add-hook 'kill-emacs-hook 'org-clock-save))
4737 (defgroup org-archive nil
4738 "Options concerning archiving in Org mode."
4739 :tag "Org Archive"
4740 :group 'org-structure)
4742 (defcustom org-archive-location "%s_archive::"
4743 "The location where subtrees should be archived.
4745 The value of this variable is a string, consisting of two parts,
4746 separated by a double-colon. The first part is a filename and
4747 the second part is a headline.
4749 When the filename is omitted, archiving happens in the same file.
4750 %s in the filename will be replaced by the current file
4751 name (without the directory part). Archiving to a different file
4752 is useful to keep archived entries from contributing to the
4753 Org Agenda.
4755 The archived entries will be filed as subtrees of the specified
4756 headline. When the headline is omitted, the subtrees are simply
4757 filed away at the end of the file, as top-level entries. Also in
4758 the heading you can use %s to represent the file name, this can be
4759 useful when using the same archive for a number of different files.
4761 Here are a few examples:
4762 \"%s_archive::\"
4763 If the current file is Projects.org, archive in file
4764 Projects.org_archive, as top-level trees. This is the default.
4766 \"::* Archived Tasks\"
4767 Archive in the current file, under the top-level headline
4768 \"* Archived Tasks\".
4770 \"~/org/archive.org::\"
4771 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4773 \"~/org/archive.org::* From %s\"
4774 Archive in file ~/org/archive.org (absolute path), under headlines
4775 \"From FILENAME\" where file name is the current file name.
4777 \"~/org/datetree.org::datetree/* Finished Tasks\"
4778 The \"datetree/\" string is special, signifying to archive
4779 items to the datetree. Items are placed in either the CLOSED
4780 date of the item, or the current date if there is no CLOSED date.
4781 The heading will be a subentry to the current date. There doesn't
4782 need to be a heading, but there always needs to be a slash after
4783 datetree. For example, to store archived items directly in the
4784 datetree, use \"~/org/datetree.org::datetree/\".
4786 \"basement::** Finished Tasks\"
4787 Archive in file ./basement (relative path), as level 3 trees
4788 below the level 2 heading \"** Finished Tasks\".
4790 You may set this option on a per-file basis by adding to the buffer a
4791 line like
4793 #+ARCHIVE: basement::** Finished Tasks
4795 You may also define it locally for a subtree by setting an ARCHIVE property
4796 in the entry. If such a property is found in an entry, or anywhere up
4797 the hierarchy, it will be used."
4798 :group 'org-archive
4799 :type 'string)
4801 (defcustom org-agenda-skip-archived-trees t
4802 "Non-nil means the agenda will skip any items located in archived trees.
4803 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4804 variable is no longer recommended, you should leave it at the value t.
4805 Instead, use the key `v' to cycle the archives-mode in the agenda."
4806 :group 'org-archive
4807 :group 'org-agenda-skip
4808 :type 'boolean)
4810 (defcustom org-columns-skip-archived-trees t
4811 "Non-nil means ignore archived trees when creating column view."
4812 :group 'org-archive
4813 :group 'org-properties
4814 :type 'boolean)
4816 (defcustom org-cycle-open-archived-trees nil
4817 "Non-nil means `org-cycle' will open archived trees.
4818 An archived tree is a tree marked with the tag ARCHIVE.
4819 When nil, archived trees will stay folded. You can still open them with
4820 normal outline commands like `show-all', but not with the cycling commands."
4821 :group 'org-archive
4822 :group 'org-cycle
4823 :type 'boolean)
4825 (defcustom org-sparse-tree-open-archived-trees nil
4826 "Non-nil means sparse tree construction shows matches in archived trees.
4827 When nil, matches in these trees are highlighted, but the trees are kept in
4828 collapsed state."
4829 :group 'org-archive
4830 :group 'org-sparse-trees
4831 :type 'boolean)
4833 (defcustom org-sparse-tree-default-date-type nil
4834 "The default date type when building a sparse tree.
4835 When this is nil, a date is a scheduled or a deadline timestamp.
4836 Otherwise, these types are allowed:
4838 all: all timestamps
4839 active: only active timestamps (<...>)
4840 inactive: only inactive timestamps ([...])
4841 scheduled: only scheduled timestamps
4842 deadline: only deadline timestamps"
4843 :type '(choice (const :tag "Scheduled or deadline" nil)
4844 (const :tag "All timestamps" all)
4845 (const :tag "Only active timestamps" active)
4846 (const :tag "Only inactive timestamps" inactive)
4847 (const :tag "Only scheduled timestamps" scheduled)
4848 (const :tag "Only deadline timestamps" deadline)
4849 (const :tag "Only closed timestamps" closed))
4850 :version "26.1"
4851 :package-version '(Org . "8.3")
4852 :group 'org-sparse-trees)
4854 (defun org-cycle-hide-archived-subtrees (state)
4855 "Re-hide all archived subtrees after a visibility state change."
4856 (when (and (not org-cycle-open-archived-trees)
4857 (not (memq state '(overview folded))))
4858 (save-excursion
4859 (let* ((globalp (memq state '(contents all)))
4860 (beg (if globalp (point-min) (point)))
4861 (end (if globalp (point-max) (org-end-of-subtree t))))
4862 (org-hide-archived-subtrees beg end)
4863 (goto-char beg)
4864 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4865 (message "%s" (substitute-command-keys
4866 "Subtree is archived and stays closed. Use \
4867 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4869 (defun org-force-cycle-archived ()
4870 "Cycle subtree even if it is archived."
4871 (interactive)
4872 (setq this-command 'org-cycle)
4873 (let ((org-cycle-open-archived-trees t))
4874 (call-interactively 'org-cycle)))
4876 (defun org-hide-archived-subtrees (beg end)
4877 "Re-hide all archived subtrees after a visibility state change."
4878 (org-with-wide-buffer
4879 (let ((case-fold-search nil)
4880 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4881 (goto-char beg)
4882 ;; Include headline point is currently on.
4883 (beginning-of-line)
4884 (while (and (< (point) end) (re-search-forward re end t))
4885 (when (member org-archive-tag (org-get-tags))
4886 (org-flag-subtree t)
4887 (org-end-of-subtree t))))))
4889 (declare-function outline-end-of-heading "outline" ())
4890 (declare-function outline-flag-region "outline" (from to flag))
4891 (defun org-flag-subtree (flag)
4892 (save-excursion
4893 (org-back-to-heading t)
4894 (outline-end-of-heading)
4895 (outline-flag-region (point)
4896 (progn (org-end-of-subtree t) (point))
4897 flag)))
4899 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4901 ;; Declare Column View Code
4903 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4904 (declare-function org-columns-compute "org-colview" (property))
4906 ;; Declare ID code
4908 (declare-function org-id-store-link "org-id")
4909 (declare-function org-id-locations-load "org-id")
4910 (declare-function org-id-locations-save "org-id")
4911 (defvar org-id-track-globally)
4913 ;;; Variables for pre-computed regular expressions, all buffer local
4915 (defvar-local org-todo-regexp nil
4916 "Matches any of the TODO state keywords.
4917 Since TODO keywords are case-sensitive, `case-fold-search' is
4918 expected to be bound to nil when matching against this regexp.")
4920 (defvar-local org-not-done-regexp nil
4921 "Matches any of the TODO state keywords except the last one.
4922 Since TODO keywords are case-sensitive, `case-fold-search' is
4923 expected to be bound to nil when matching against this regexp.")
4925 (defvar-local org-not-done-heading-regexp nil
4926 "Matches a TODO headline that is not done.
4927 Since TODO keywords are case-sensitive, `case-fold-search' is
4928 expected to be bound to nil when matching against this regexp.")
4930 (defvar-local org-todo-line-regexp nil
4931 "Matches a headline and puts TODO state into group 2 if present.
4932 Since TODO keywords are case-sensitive, `case-fold-search' is
4933 expected to be bound to nil when matching against this regexp.")
4935 (defvar-local org-complex-heading-regexp nil
4936 "Matches a headline and puts everything into groups:
4938 group 1: Stars
4939 group 2: The TODO keyword, maybe
4940 group 3: Priority cookie
4941 group 4: True headline
4942 group 5: Tags
4944 Since TODO keywords are case-sensitive, `case-fold-search' is
4945 expected to be bound to nil when matching against this regexp.")
4947 (defvar-local org-complex-heading-regexp-format nil
4948 "Printf format to make regexp to match an exact headline.
4949 This regexp will match the headline of any node which has the
4950 exact headline text that is put into the format, but may have any
4951 TODO state, priority and tags.")
4953 (defvar-local org-todo-line-tags-regexp nil
4954 "Matches a headline and puts TODO state into group 2 if present.
4955 Also put tags into group 4 if tags are present.")
4957 (defconst org-plain-time-of-day-regexp
4958 (concat
4959 "\\(\\<[012]?[0-9]"
4960 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4961 "\\(--?"
4962 "\\(\\<[012]?[0-9]"
4963 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4964 "\\)?")
4965 "Regular expression to match a plain time or time range.
4966 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4967 groups carry important information:
4968 0 the full match
4969 1 the first time, range or not
4970 8 the second time, if it is a range.")
4972 (defconst org-plain-time-extension-regexp
4973 (concat
4974 "\\(\\<[012]?[0-9]"
4975 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4976 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4977 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4978 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4979 groups carry important information:
4980 0 the full match
4981 7 hours of duration
4982 9 minutes of duration")
4984 (defconst org-stamp-time-of-day-regexp
4985 (concat
4986 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4987 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4988 "\\(--?"
4989 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4990 "Regular expression to match a timestamp time or time range.
4991 After a match, the following groups carry important information:
4992 0 the full match
4993 1 date plus weekday, for back referencing to make sure both times are on the same day
4994 2 the first time, range or not
4995 4 the second time, if it is a range.")
4997 (defconst org-startup-options
4998 '(("fold" org-startup-folded t)
4999 ("overview" org-startup-folded t)
5000 ("nofold" org-startup-folded nil)
5001 ("showall" org-startup-folded nil)
5002 ("showeverything" org-startup-folded showeverything)
5003 ("content" org-startup-folded content)
5004 ("indent" org-startup-indented t)
5005 ("noindent" org-startup-indented nil)
5006 ("hidestars" org-hide-leading-stars t)
5007 ("showstars" org-hide-leading-stars nil)
5008 ("odd" org-odd-levels-only t)
5009 ("oddeven" org-odd-levels-only nil)
5010 ("align" org-startup-align-all-tables t)
5011 ("noalign" org-startup-align-all-tables nil)
5012 ("inlineimages" org-startup-with-inline-images t)
5013 ("noinlineimages" org-startup-with-inline-images nil)
5014 ("latexpreview" org-startup-with-latex-preview t)
5015 ("nolatexpreview" org-startup-with-latex-preview nil)
5016 ("customtime" org-display-custom-times t)
5017 ("logdone" org-log-done time)
5018 ("lognotedone" org-log-done note)
5019 ("nologdone" org-log-done nil)
5020 ("lognoteclock-out" org-log-note-clock-out t)
5021 ("nolognoteclock-out" org-log-note-clock-out nil)
5022 ("logrepeat" org-log-repeat state)
5023 ("lognoterepeat" org-log-repeat note)
5024 ("logdrawer" org-log-into-drawer t)
5025 ("nologdrawer" org-log-into-drawer nil)
5026 ("logstatesreversed" org-log-states-order-reversed t)
5027 ("nologstatesreversed" org-log-states-order-reversed nil)
5028 ("nologrepeat" org-log-repeat nil)
5029 ("logreschedule" org-log-reschedule time)
5030 ("lognotereschedule" org-log-reschedule note)
5031 ("nologreschedule" org-log-reschedule nil)
5032 ("logredeadline" org-log-redeadline time)
5033 ("lognoteredeadline" org-log-redeadline note)
5034 ("nologredeadline" org-log-redeadline nil)
5035 ("logrefile" org-log-refile time)
5036 ("lognoterefile" org-log-refile note)
5037 ("nologrefile" org-log-refile nil)
5038 ("fninline" org-footnote-define-inline t)
5039 ("nofninline" org-footnote-define-inline nil)
5040 ("fnlocal" org-footnote-section nil)
5041 ("fnauto" org-footnote-auto-label t)
5042 ("fnprompt" org-footnote-auto-label nil)
5043 ("fnconfirm" org-footnote-auto-label confirm)
5044 ("fnplain" org-footnote-auto-label plain)
5045 ("fnadjust" org-footnote-auto-adjust t)
5046 ("nofnadjust" org-footnote-auto-adjust nil)
5047 ("constcgs" constants-unit-system cgs)
5048 ("constSI" constants-unit-system SI)
5049 ("noptag" org-tag-persistent-alist nil)
5050 ("hideblocks" org-hide-block-startup t)
5051 ("nohideblocks" org-hide-block-startup nil)
5052 ("beamer" org-startup-with-beamer-mode t)
5053 ("entitiespretty" org-pretty-entities t)
5054 ("entitiesplain" org-pretty-entities nil))
5055 "Variable associated with STARTUP options for org-mode.
5056 Each element is a list of three items: the startup options (as written
5057 in the #+STARTUP line), the corresponding variable, and the value to set
5058 this variable to if the option is found. An optional forth element PUSH
5059 means to push this value onto the list in the variable.")
5061 (defcustom org-group-tags t
5062 "When non-nil (the default), use group tags.
5063 This can be turned on/off through `org-toggle-tags-groups'."
5064 :group 'org-tags
5065 :group 'org-startup
5066 :type 'boolean)
5068 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5070 (defun org-toggle-tags-groups ()
5071 "Toggle support for group tags.
5072 Support for group tags is controlled by the option
5073 `org-group-tags', which is non-nil by default."
5074 (interactive)
5075 (setq org-group-tags (not org-group-tags))
5076 (cond ((and (derived-mode-p 'org-agenda-mode)
5077 org-group-tags)
5078 (org-agenda-redo))
5079 ((derived-mode-p 'org-mode)
5080 (let ((org-inhibit-startup t)) (org-mode))))
5081 (message "Groups tags support has been turned %s"
5082 (if org-group-tags "on" "off")))
5084 (defun org-set-regexps-and-options (&optional tags-only)
5085 "Precompute regular expressions used in the current buffer.
5086 When optional argument TAGS-ONLY is non-nil, only compute tags
5087 related expressions."
5088 (when (derived-mode-p 'org-mode)
5089 (let ((alist (org--setup-collect-keywords
5090 (org-make-options-regexp
5091 (append '("FILETAGS" "TAGS" "SETUPFILE")
5092 (and (not tags-only)
5093 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5094 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5095 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5096 ;; Startup options. Get this early since it does change
5097 ;; behavior for other options (e.g., tags).
5098 (let ((startup (cdr (assq 'startup alist))))
5099 (dolist (option startup)
5100 (let ((entry (assoc-string option org-startup-options t)))
5101 (when entry
5102 (let ((var (nth 1 entry))
5103 (val (nth 2 entry)))
5104 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5105 (unless (listp (symbol-value var))
5106 (set (make-local-variable var) nil))
5107 (add-to-list var val)))))))
5108 (setq-local org-file-tags
5109 (mapcar #'org-add-prop-inherited
5110 (cdr (assq 'filetags alist))))
5111 (setq org-current-tag-alist
5112 (append org-tag-persistent-alist
5113 (let ((tags (cdr (assq 'tags alist))))
5114 (if tags (org-tag-string-to-alist tags)
5115 org-tag-alist))))
5116 (setq org-tag-groups-alist
5117 (org-tag-alist-to-groups org-current-tag-alist))
5118 (unless tags-only
5119 ;; File properties.
5120 (setq-local org-file-properties (cdr (assq 'property alist)))
5121 ;; Archive location.
5122 (let ((archive (cdr (assq 'archive alist))))
5123 (when archive (setq-local org-archive-location archive)))
5124 ;; Category.
5125 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5126 (when cat
5127 (setq-local org-category (intern cat))
5128 (setq-local org-file-properties
5129 (org--update-property-plist
5130 "CATEGORY" cat org-file-properties))))
5131 ;; Columns.
5132 (let ((column (cdr (assq 'columns alist))))
5133 (when column (setq-local org-columns-default-format column)))
5134 ;; Constants.
5135 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5136 ;; Link abbreviations.
5137 (let ((links (cdr (assq 'link alist))))
5138 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5139 ;; Priorities.
5140 (let ((priorities (cdr (assq 'priorities alist))))
5141 (when priorities
5142 (setq-local org-highest-priority (nth 0 priorities))
5143 (setq-local org-lowest-priority (nth 1 priorities))
5144 (setq-local org-default-priority (nth 2 priorities))))
5145 ;; Scripts.
5146 (let ((scripts (assq 'scripts alist)))
5147 (when scripts
5148 (setq-local org-use-sub-superscripts (cdr scripts))))
5149 ;; TODO keywords.
5150 (setq-local org-todo-kwd-alist nil)
5151 (setq-local org-todo-key-alist nil)
5152 (setq-local org-todo-key-trigger nil)
5153 (setq-local org-todo-keywords-1 nil)
5154 (setq-local org-done-keywords nil)
5155 (setq-local org-todo-heads nil)
5156 (setq-local org-todo-sets nil)
5157 (setq-local org-todo-log-states nil)
5158 (let ((todo-sequences
5159 (or (nreverse (cdr (assq 'todo alist)))
5160 (let ((d (default-value 'org-todo-keywords)))
5161 (if (not (stringp (car d))) d
5162 ;; XXX: Backward compatibility code.
5163 (list (cons org-todo-interpretation d)))))))
5164 (dolist (sequence todo-sequences)
5165 (let* ((sequence (or (run-hook-with-args-until-success
5166 'org-todo-setup-filter-hook sequence)
5167 sequence))
5168 (sequence-type (car sequence))
5169 (keywords (cdr sequence))
5170 (sep (member "|" keywords))
5171 names alist)
5172 (dolist (k (remove "|" keywords))
5173 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5175 (error "Invalid TODO keyword %s" k))
5176 (let ((name (match-string 1 k))
5177 (key (match-string 2 k))
5178 (log (org-extract-log-state-settings k)))
5179 (push name names)
5180 (push (cons name (and key (string-to-char key))) alist)
5181 (when log (push log org-todo-log-states))))
5182 (let* ((names (nreverse names))
5183 (done (if sep (org-remove-keyword-keys (cdr sep))
5184 (last names)))
5185 (head (car names))
5186 (tail (list sequence-type head (car done) (org-last done))))
5187 (add-to-list 'org-todo-heads head 'append)
5188 (push names org-todo-sets)
5189 (setq org-done-keywords (append org-done-keywords done nil))
5190 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5191 (setq org-todo-key-alist
5192 (append org-todo-key-alist
5193 (and alist
5194 (append '((:startgroup))
5195 (nreverse alist)
5196 '((:endgroup))))))
5197 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5198 (setq org-todo-sets (nreverse org-todo-sets)
5199 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5200 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5201 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5202 ;; Compute the regular expressions and other local variables.
5203 ;; Using `org-outline-regexp-bol' would complicate them much,
5204 ;; because of the fixed white space at the end of that string.
5205 (unless org-done-keywords
5206 (setq org-done-keywords
5207 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5208 (setq org-not-done-keywords
5209 (org-delete-all org-done-keywords
5210 (copy-sequence org-todo-keywords-1))
5211 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5212 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5213 org-not-done-heading-regexp
5214 (format org-heading-keyword-regexp-format org-not-done-regexp)
5215 org-todo-line-regexp
5216 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5217 org-complex-heading-regexp
5218 (concat "^\\(\\*+\\)"
5219 "\\(?: +" org-todo-regexp "\\)?"
5220 "\\(?: +\\(\\[#.\\]\\)\\)?"
5221 "\\(?: +\\(.*?\\)\\)??"
5222 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5223 "[ \t]*$")
5224 org-complex-heading-regexp-format
5225 (concat "^\\(\\*+\\)"
5226 "\\(?: +" org-todo-regexp "\\)?"
5227 "\\(?: +\\(\\[#.\\]\\)\\)?"
5228 "\\(?: +"
5229 ;; Stats cookies can be stuck to body.
5230 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5231 "\\(%s\\)"
5232 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5233 "\\)"
5234 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5235 "[ \t]*$")
5236 org-todo-line-tags-regexp
5237 (concat "^\\(\\*+\\)"
5238 "\\(?: +" org-todo-regexp "\\)?"
5239 "\\(?: +\\(.*?\\)\\)??"
5240 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5241 "[ \t]*$"))
5242 (org-compute-latex-and-related-regexp)))))
5244 (defun org--setup-collect-keywords (regexp &optional files alist)
5245 "Return setup keywords values as an alist.
5247 REGEXP matches a subset of setup keywords. FILES is a list of
5248 file names already visited. It is used to avoid circular setup
5249 files. ALIST, when non-nil, is the alist computed so far.
5251 Return value contains the following keys: `archive', `category',
5252 `columns', `constants', `filetags', `link', `priorities',
5253 `property', `scripts', `startup', `tags' and `todo'."
5254 (org-with-wide-buffer
5255 (goto-char (point-min))
5256 (let ((case-fold-search t))
5257 (while (re-search-forward regexp nil t)
5258 (let ((element (org-element-at-point)))
5259 (when (eq (org-element-type element) 'keyword)
5260 (let ((key (org-element-property :key element))
5261 (value (org-element-property :value element)))
5262 (cond
5263 ((equal key "ARCHIVE")
5264 (when (org-string-nw-p value)
5265 (push (cons 'archive value) alist)))
5266 ((equal key "CATEGORY") (push (cons 'category value) alist))
5267 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5268 ((equal key "CONSTANTS")
5269 (let* ((constants (assq 'constants alist))
5270 (store (cdr constants)))
5271 (dolist (pair (org-split-string value))
5272 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5273 pair)
5274 (let* ((name (match-string 1 pair))
5275 (value (match-string 2 pair))
5276 (old (assoc name store)))
5277 (if old (setcdr old value)
5278 (push (cons name value) store)))))
5279 (if constants (setcdr constants store)
5280 (push (cons 'constants store) alist))))
5281 ((equal key "FILETAGS")
5282 (when (org-string-nw-p value)
5283 (let ((old (assq 'filetags alist))
5284 (new (apply #'nconc
5285 (mapcar (lambda (x) (org-split-string x ":"))
5286 (org-split-string value)))))
5287 (if old (setcdr old (append new (cdr old)))
5288 (push (cons 'filetags new) alist)))))
5289 ((equal key "LINK")
5290 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5291 (let ((links (assq 'link alist))
5292 (pair (cons (match-string-no-properties 1 value)
5293 (match-string-no-properties 2 value))))
5294 (if links (push pair (cdr links))
5295 (push (list 'link pair) alist)))))
5296 ((equal key "OPTIONS")
5297 (when (and (org-string-nw-p value)
5298 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5299 (push (cons 'scripts (read (match-string 1 value))) alist)))
5300 ((equal key "PRIORITIES")
5301 (push (cons 'priorities
5302 (let ((prio (org-split-string value)))
5303 (if (< (length prio) 3) '(?A ?C ?B)
5304 (mapcar #'string-to-char prio))))
5305 alist))
5306 ((equal key "PROPERTY")
5307 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5308 (let* ((property (assq 'property alist))
5309 (value (org--update-property-plist
5310 (match-string-no-properties 1 value)
5311 (match-string-no-properties 2 value)
5312 (cdr property))))
5313 (if property (setcdr property value)
5314 (push (cons 'property value) alist)))))
5315 ((equal key "STARTUP")
5316 (let ((startup (assq 'startup alist)))
5317 (if startup
5318 (setcdr startup
5319 (append (cdr startup) (org-split-string value)))
5320 (push (cons 'startup (org-split-string value)) alist))))
5321 ((equal key "TAGS")
5322 (let ((tag-cell (assq 'tags alist)))
5323 (if tag-cell
5324 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5325 (push (cons 'tags value) alist))))
5326 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5327 (let ((todo (assq 'todo alist))
5328 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5329 (org-split-string value))))
5330 (if todo (push value (cdr todo))
5331 (push (list 'todo value) alist))))
5332 ((equal key "SETUPFILE")
5333 (unless buffer-read-only ; Do not check in Gnus messages.
5334 (let ((f (and (org-string-nw-p value)
5335 (expand-file-name
5336 (org-unbracket-string "\"" "\"" value)))))
5337 (when (and f (file-readable-p f) (not (member f files)))
5338 (with-temp-buffer
5339 (setq default-directory (file-name-directory f))
5340 (insert-file-contents f)
5341 (setq alist
5342 ;; Fake Org mode to benefit from cache
5343 ;; without recurring needlessly.
5344 (let ((major-mode 'org-mode))
5345 (org--setup-collect-keywords
5346 regexp (cons f files) alist)))))))))))))))
5347 alist)
5349 (defun org-tag-string-to-alist (s)
5350 "Return tag alist associated to string S.
5351 S is a value for TAGS keyword or produced with
5352 `org-tag-alist-to-string'. Return value is an alist suitable for
5353 `org-tag-alist' or `org-tag-persistent-alist'."
5354 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5355 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5356 "\\|{.+?}\\)" ; regular expression
5357 "\\(?:(\\(.\\))\\)?\\'"))
5358 alist group-flag)
5359 (dolist (tokens lines (cdr (nreverse alist)))
5360 (push '(:newline) alist)
5361 (while tokens
5362 (let ((token (pop tokens)))
5363 (pcase token
5364 ("{"
5365 (push '(:startgroup) alist)
5366 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5367 ("}"
5368 (push '(:endgroup) alist)
5369 (setq group-flag nil))
5370 ("["
5371 (push '(:startgrouptag) alist)
5372 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5373 ("]"
5374 (push '(:endgrouptag) alist)
5375 (setq group-flag nil))
5376 (":"
5377 (push '(:grouptags) alist))
5378 ((guard (string-match tag-re token))
5379 (let ((tag (match-string 1 token))
5380 (key (and (match-beginning 2)
5381 (string-to-char (match-string 2 token)))))
5382 ;; Push all tags in groups, no matter if they already
5383 ;; appear somewhere else in the list.
5384 (when (or group-flag (not (assoc tag alist)))
5385 (push (cons tag key) alist))))))))))
5387 (defun org-tag-alist-to-string (alist &optional skip-key)
5388 "Return tag string associated to ALIST.
5390 ALIST is an alist, as defined in `org-tag-alist' or
5391 `org-tag-persistent-alist', or produced with
5392 `org-tag-string-to-alist'.
5394 Return value is a string suitable as a value for \"TAGS\"
5395 keyword.
5397 When optional argument SKIP-KEY is non-nil, skip selection keys
5398 next to tags."
5399 (mapconcat (lambda (token)
5400 (pcase token
5401 (`(:startgroup) "{")
5402 (`(:endgroup) "}")
5403 (`(:startgrouptag) "[")
5404 (`(:endgrouptag) "]")
5405 (`(:grouptags) ":")
5406 (`(:newline) "\\n")
5407 ((and
5408 (guard (not skip-key))
5409 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5410 (format "%s(%c)" tag key))
5411 (`(,(and tag (pred stringp)) . ,_) tag)
5412 (_ (user-error "Invalid tag token: %S" token))))
5413 alist
5414 " "))
5416 (defun org-tag-alist-to-groups (alist)
5417 "Return group alist from tag ALIST.
5418 ALIST is an alist, as defined in `org-tag-alist' or
5419 `org-tag-persistent-alist', or produced with
5420 `org-tag-string-to-alist'. Return value is an alist following
5421 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5422 a string, summarizing TAGS, as a list of strings."
5423 (let (groups group-status current-group)
5424 (dolist (token alist (nreverse groups))
5425 (pcase token
5426 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5427 (`(,(or :endgroup :endgrouptag))
5428 (when (eq group-status 'append)
5429 (push (nreverse current-group) groups))
5430 (setq group-status nil))
5431 (`(:grouptags) (setq group-status 'append))
5432 ((and `(,tag . ,_) (guard group-status))
5433 (if (eq group-status 'append) (push tag current-group)
5434 (setq current-group (list tag))))
5435 (_ nil)))))
5437 (defun org-file-contents (file &optional noerror)
5438 "Return the contents of FILE, as a string."
5439 (if (and file (file-readable-p file))
5440 (with-temp-buffer
5441 (insert-file-contents file)
5442 (buffer-string))
5443 (funcall (if noerror 'message 'error)
5444 "Cannot read file \"%s\"%s"
5445 file
5446 (let ((from (buffer-file-name (buffer-base-buffer))))
5447 (if from (concat " (referenced in file \"" from "\")") "")))))
5449 (defun org-extract-log-state-settings (x)
5450 "Extract the log state setting from a TODO keyword string.
5451 This will extract info from a string like \"WAIT(w@/!)\"."
5452 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5453 (let ((kw (match-string 1 x))
5454 (log1 (and (match-end 3) (match-string 3 x)))
5455 (log2 (and (match-end 4) (match-string 4 x))))
5456 (and (or log1 log2)
5457 (list kw
5458 (and log1 (if (equal log1 "!") 'time 'note))
5459 (and log2 (if (equal log2 "!") 'time 'note)))))))
5461 (defun org-remove-keyword-keys (list)
5462 "Remove a pair of parenthesis at the end of each string in LIST."
5463 (mapcar (lambda (x)
5464 (if (string-match "(.*)$" x)
5465 (substring x 0 (match-beginning 0))
5467 list))
5469 (defun org-assign-fast-keys (alist)
5470 "Assign fast keys to a keyword-key alist.
5471 Respect keys that are already there."
5472 (let (new e (alt ?0))
5473 (while (setq e (pop alist))
5474 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5475 (cdr e)) ;; Key already assigned.
5476 (push e new)
5477 (let ((clist (string-to-list (downcase (car e))))
5478 (used (append new alist)))
5479 (when (= (car clist) ?@)
5480 (pop clist))
5481 (while (and clist (rassoc (car clist) used))
5482 (pop clist))
5483 (unless clist
5484 (while (rassoc alt used)
5485 (cl-incf alt)))
5486 (push (cons (car e) (or (car clist) alt)) new))))
5487 (nreverse new)))
5489 ;;; Some variables used in various places
5491 (defvar org-window-configuration nil
5492 "Used in various places to store a window configuration.")
5493 (defvar org-selected-window nil
5494 "Used in various places to store a window configuration.")
5495 (defvar org-finish-function nil
5496 "Function to be called when `C-c C-c' is used.
5497 This is for getting out of special buffers like capture.")
5498 (defvar org-last-state)
5500 ;; Defined somewhere in this file, but used before definition.
5501 (defvar org-entities) ;; defined in org-entities.el
5502 (defvar org-struct-menu)
5503 (defvar org-org-menu)
5504 (defvar org-tbl-menu)
5506 ;;;; Define the Org mode
5508 ;; We use a before-change function to check if a table might need
5509 ;; an update.
5510 (defvar org-table-may-need-update t
5511 "Indicates that a table might need an update.
5512 This variable is set by `org-before-change-function'.
5513 `org-table-align' sets it back to nil.")
5514 (defun org-before-change-function (_beg _end)
5515 "Every change indicates that a table might need an update."
5516 (setq org-table-may-need-update t))
5517 (defvar org-mode-map)
5518 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5519 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5520 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5521 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5522 (defvar org-table-buffer-is-an nil)
5524 (defvar bidi-paragraph-direction)
5525 (defvar buffer-face-mode-face)
5527 (require 'outline)
5529 ;; Other stuff we need.
5530 (require 'time-date)
5531 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5532 (require 'easymenu)
5533 (autoload 'easy-menu-add "easymenu")
5534 (require 'overlay)
5536 ;; (require 'org-macs) moved higher up in the file before it is first used
5537 (require 'org-entities)
5538 ;; (require 'org-compat) moved higher up in the file before it is first used
5539 (require 'org-faces)
5540 (require 'org-list)
5541 (require 'org-pcomplete)
5542 (require 'org-src)
5543 (require 'org-footnote)
5544 (require 'org-macro)
5546 ;; babel
5547 (require 'ob)
5549 ;;;###autoload
5550 (define-derived-mode org-mode outline-mode "Org"
5551 "Outline-based notes management and organizer, alias
5552 \"Carsten's outline-mode for keeping track of everything.\"
5554 Org mode develops organizational tasks around a NOTES file which
5555 contains information about projects as plain text. Org mode is
5556 implemented on top of Outline mode, which is ideal to keep the content
5557 of large files well structured. It supports ToDo items, deadlines and
5558 time stamps, which magically appear in the diary listing of the Emacs
5559 calendar. Tables are easily created with a built-in table editor.
5560 Plain text URL-like links connect to websites, emails (VM), Usenet
5561 messages (Gnus), BBDB entries, and any files related to the project.
5562 For printing and sharing of notes, an Org file (or a part of it)
5563 can be exported as a structured ASCII or HTML file.
5565 The following commands are available:
5567 \\{org-mode-map}"
5569 ;; Get rid of Outline menus, they are not needed
5570 ;; Need to do this here because define-derived-mode sets up
5571 ;; the keymap so late. Still, it is a waste to call this each time
5572 ;; we switch another buffer into Org mode.
5573 (define-key org-mode-map [menu-bar headings] 'undefined)
5574 (define-key org-mode-map [menu-bar hide] 'undefined)
5575 (define-key org-mode-map [menu-bar show] 'undefined)
5577 (org-load-modules-maybe)
5578 (org-install-agenda-files-menu)
5579 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5580 (add-to-invisibility-spec '(org-cwidth))
5581 (add-to-invisibility-spec '(org-hide-block . t))
5582 (setq-local outline-regexp org-outline-regexp)
5583 (setq-local outline-level 'org-outline-level)
5584 (setq bidi-paragraph-direction 'left-to-right)
5585 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5586 (unless org-display-table
5587 (setq org-display-table (make-display-table)))
5588 (set-display-table-slot
5589 org-display-table 4
5590 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5591 org-ellipsis)))
5592 (setq buffer-display-table org-display-table))
5593 (org-set-regexps-and-options)
5594 (org-set-font-lock-defaults)
5595 (when (and org-tag-faces (not org-tags-special-faces-re))
5596 ;; tag faces set outside customize.... force initialization.
5597 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5598 ;; Calc embedded
5599 (setq-local calc-embedded-open-mode "# ")
5600 ;; Modify a few syntax entries
5601 (modify-syntax-entry ?@ "w")
5602 (modify-syntax-entry ?\" "\"")
5603 (modify-syntax-entry ?\\ "_")
5604 (modify-syntax-entry ?~ "_")
5605 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5606 ;; Activate before-change-function
5607 (setq-local org-table-may-need-update t)
5608 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5609 ;; Check for running clock before killing a buffer
5610 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5611 ;; Initialize macros templates.
5612 (org-macro-initialize-templates)
5613 ;; Initialize radio targets.
5614 (org-update-radio-target-regexp)
5615 ;; Indentation.
5616 (setq-local indent-line-function 'org-indent-line)
5617 (setq-local indent-region-function 'org-indent-region)
5618 ;; Filling and auto-filling.
5619 (org-setup-filling)
5620 ;; Comments.
5621 (org-setup-comments-handling)
5622 ;; Initialize cache.
5623 (org-element-cache-reset)
5624 ;; Beginning/end of defun
5625 (setq-local beginning-of-defun-function 'org-backward-element)
5626 (setq-local end-of-defun-function
5627 (lambda ()
5628 (if (not (org-at-heading-p))
5629 (org-forward-element)
5630 (org-forward-element)
5631 (forward-char -1))))
5632 ;; Next error for sparse trees
5633 (setq-local next-error-function 'org-occur-next-match)
5634 ;; Make sure dependence stuff works reliably, even for users who set it
5635 ;; too late :-(
5636 (if org-enforce-todo-dependencies
5637 (add-hook 'org-blocker-hook
5638 'org-block-todo-from-children-or-siblings-or-parent)
5639 (remove-hook 'org-blocker-hook
5640 'org-block-todo-from-children-or-siblings-or-parent))
5641 (if org-enforce-todo-checkbox-dependencies
5642 (add-hook 'org-blocker-hook
5643 'org-block-todo-from-checkboxes)
5644 (remove-hook 'org-blocker-hook
5645 'org-block-todo-from-checkboxes))
5647 ;; Align options lines
5648 (setq-local
5649 align-mode-rules-list
5650 '((org-in-buffer-settings
5651 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5652 (modes . '(org-mode)))))
5654 ;; Imenu
5655 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5657 ;; Make isearch reveal context
5658 (setq-local outline-isearch-open-invisible-function
5659 (lambda (&rest _) (org-show-context 'isearch)))
5661 ;; Setup the pcomplete hooks
5662 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5663 (setq-local pcomplete-command-name-function 'org-command-at-point)
5664 (setq-local pcomplete-default-completion-function 'ignore)
5665 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5666 (setq-local pcomplete-termination-string "")
5667 (setq-local buffer-face-mode-face 'org-default)
5669 ;; If empty file that did not turn on Org mode automatically, make
5670 ;; it to.
5671 (when (and org-insert-mode-line-in-empty-file
5672 (called-interactively-p 'any)
5673 (= (point-min) (point-max)))
5674 (insert "# -*- mode: org -*-\n\n"))
5675 (unless org-inhibit-startup
5676 (org-unmodified
5677 (when org-startup-with-beamer-mode (org-beamer-mode))
5678 (when org-startup-align-all-tables
5679 (org-table-map-tables #'org-table-align t))
5680 (when org-startup-with-inline-images (org-display-inline-images))
5681 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5682 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5683 (when org-startup-truncated (setq truncate-lines t))
5684 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5685 (org-refresh-effort-properties)))
5686 ;; Try to set `org-hide' face correctly.
5687 (let ((foreground (org-find-invisible-foreground)))
5688 (when foreground
5689 (set-face-foreground 'org-hide foreground))))
5691 ;; Update `customize-package-emacs-version-alist'
5692 (add-to-list 'customize-package-emacs-version-alist
5693 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5694 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5695 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5696 ("9.0" . "26.1")))
5698 (defvar org-mode-transpose-word-syntax-table
5699 (let ((st (make-syntax-table text-mode-syntax-table)))
5700 (dolist (c org-emphasis-alist st)
5701 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5703 (when (fboundp 'abbrev-table-put)
5704 (abbrev-table-put org-mode-abbrev-table
5705 :parents (list text-mode-abbrev-table)))
5707 (defun org-find-invisible-foreground ()
5708 (let ((candidates (remove
5709 "unspecified-bg"
5710 (nconc
5711 (list (face-background 'default)
5712 (face-background 'org-default))
5713 (mapcar
5714 (lambda (alist)
5715 (when (boundp alist)
5716 (cdr (assq 'background-color (symbol-value alist)))))
5717 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5718 (list (face-foreground 'org-hide))))))
5719 (car (remove nil candidates))))
5721 (defun org-current-time (&optional rounding-minutes past)
5722 "Current time, possibly rounded to ROUNDING-MINUTES.
5723 When ROUNDING-MINUTES is not an integer, fall back on the car of
5724 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5725 the rounding returns a past time."
5726 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5727 (car org-time-stamp-rounding-minutes)))
5728 (time (decode-time)) res)
5729 (if (< r 1)
5730 (current-time)
5731 (setq res
5732 (apply 'encode-time
5733 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5734 (nthcdr 2 time))))
5735 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5736 (seconds-to-time (- (float-time res) (* r 60)))
5737 res))))
5739 (defun org-today ()
5740 "Return today date, considering `org-extend-today-until'."
5741 (time-to-days
5742 (time-subtract (current-time)
5743 (list 0 (* 3600 org-extend-today-until) 0))))
5745 ;;;; Font-Lock stuff, including the activators
5747 (defvar org-mouse-map (make-sparse-keymap))
5748 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5749 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5750 (when org-mouse-1-follows-link
5751 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5752 (when org-tab-follows-link
5753 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5754 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5756 (require 'font-lock)
5758 (defconst org-non-link-chars "]\t\n\r<>")
5759 (defvar org-link-types-re nil
5760 "Matches a link that has a url-like prefix like \"http:\"")
5761 (defvar org-link-re-with-space nil
5762 "Matches a link with spaces, optional angular brackets around it.")
5763 (defvar org-link-re-with-space2 nil
5764 "Matches a link with spaces, optional angular brackets around it.")
5765 (defvar org-link-re-with-space3 nil
5766 "Matches a link with spaces, only for internal part in bracket links.")
5767 (defvar org-angle-link-re nil
5768 "Matches link with angular brackets, spaces are allowed.")
5769 (defvar org-plain-link-re nil
5770 "Matches plain link, without spaces.")
5771 (defvar org-bracket-link-regexp nil
5772 "Matches a link in double brackets.")
5773 (defvar org-bracket-link-analytic-regexp nil
5774 "Regular expression used to analyze links.
5775 Here is what the match groups contain after a match:
5776 1: http:
5777 2: http
5778 3: path
5779 4: [desc]
5780 5: desc")
5781 (defvar org-bracket-link-analytic-regexp++ nil
5782 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5783 (defvar org-any-link-re nil
5784 "Regular expression matching any link.")
5786 (defconst org-match-sexp-depth 3
5787 "Number of stacked braces for sub/superscript matching.")
5789 (defun org-create-multibrace-regexp (left right n)
5790 "Create a regular expression which will match a balanced sexp.
5791 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5792 as single character strings.
5793 The regexp returned will match the entire expression including the
5794 delimiters. It will also define a single group which contains the
5795 match except for the outermost delimiters. The maximum depth of
5796 stacked delimiters is N. Escaping delimiters is not possible."
5797 (let* ((nothing (concat "[^" left right "]*?"))
5798 (or "\\|")
5799 (re nothing)
5800 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5801 (while (> n 1)
5802 (setq n (1- n)
5803 re (concat re or next)
5804 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5805 (concat left "\\(" re "\\)" right)))
5807 (defconst org-match-substring-regexp
5808 (concat
5809 "\\(\\S-\\)\\([_^]\\)\\("
5810 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5811 "\\|"
5812 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5813 "\\|"
5814 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5815 "The regular expression matching a sub- or superscript.")
5817 (defconst org-match-substring-with-braces-regexp
5818 (concat
5819 "\\(\\S-\\)\\([_^]\\)"
5820 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5821 "The regular expression matching a sub- or superscript, forcing braces.")
5823 (defun org-make-link-regexps ()
5824 "Update the link regular expressions.
5825 This should be called after the variable `org-link-parameters' has changed."
5826 (let ((types-re (regexp-opt (org-link-types) t)))
5827 (setq org-link-types-re
5828 (concat "\\`" types-re ":")
5829 org-link-re-with-space
5830 (concat "<?" types-re ":"
5831 "\\([^" org-non-link-chars " ]"
5832 "[^" org-non-link-chars "]*"
5833 "[^" org-non-link-chars " ]\\)>?")
5834 org-link-re-with-space2
5835 (concat "<?" types-re ":"
5836 "\\([^" org-non-link-chars " ]"
5837 "[^\t\n\r]*"
5838 "[^" org-non-link-chars " ]\\)>?")
5839 org-link-re-with-space3
5840 (concat "<?" types-re ":"
5841 "\\([^" org-non-link-chars " ]"
5842 "[^\t\n\r]*\\)")
5843 org-angle-link-re
5844 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5845 types-re)
5846 org-plain-link-re
5847 (concat
5848 "\\<" types-re ":"
5849 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5850 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5851 org-bracket-link-regexp
5852 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5853 org-bracket-link-analytic-regexp
5854 (concat
5855 "\\[\\["
5856 "\\(" types-re ":\\)?"
5857 "\\([^]]+\\)"
5858 "\\]"
5859 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5860 "\\]")
5861 org-bracket-link-analytic-regexp++
5862 (concat
5863 "\\[\\["
5864 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5865 "\\([^]]+\\)"
5866 "\\]"
5867 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5868 "\\]")
5869 org-any-link-re
5870 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5871 org-angle-link-re "\\)\\|\\("
5872 org-plain-link-re "\\)"))))
5874 (org-make-link-regexps)
5876 (defvar org-emph-face nil)
5878 (defun org-do-emphasis-faces (limit)
5879 "Run through the buffer and emphasize strings."
5880 (let (rtn a)
5881 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5882 (let* ((border (char-after (match-beginning 3)))
5883 (bre (regexp-quote (char-to-string border))))
5884 (when (and (not (= border (char-after (match-beginning 4))))
5885 (not (string-match-p (concat bre ".*" bre)
5886 (replace-regexp-in-string
5887 "\n" " "
5888 (substring (match-string 2) 1 -1)))))
5889 (setq rtn t)
5890 (setq a (assoc (match-string 3) org-emphasis-alist))
5891 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5892 'face
5893 (nth 1 a))
5894 (and (nth 2 a)
5895 (org-remove-flyspell-overlays-in
5896 (match-beginning 0) (match-end 0)))
5897 (add-text-properties (match-beginning 2) (match-end 2)
5898 '(font-lock-multiline t org-emphasis t))
5899 (when org-hide-emphasis-markers
5900 (add-text-properties (match-end 4) (match-beginning 5)
5901 '(invisible org-link))
5902 (add-text-properties (match-beginning 3) (match-end 3)
5903 '(invisible org-link)))))
5904 (goto-char (1+ (match-beginning 0))))
5905 rtn))
5907 (defun org-emphasize (&optional char)
5908 "Insert or change an emphasis, i.e. a font like bold or italic.
5909 If there is an active region, change that region to a new emphasis.
5910 If there is no region, just insert the marker characters and position
5911 the cursor between them.
5912 CHAR should be the marker character. If it is a space, it means to
5913 remove the emphasis of the selected region.
5914 If CHAR is not given (for example in an interactive call) it will be
5915 prompted for."
5916 (interactive)
5917 (let ((erc org-emphasis-regexp-components)
5918 (string "") beg end move s)
5919 (if (org-region-active-p)
5920 (setq beg (region-beginning)
5921 end (region-end)
5922 string (buffer-substring beg end))
5923 (setq move t))
5925 (unless char
5926 (message "Emphasis marker or tag: [%s]"
5927 (mapconcat #'car org-emphasis-alist ""))
5928 (setq char (read-char-exclusive)))
5929 (if (equal char ?\s)
5930 (setq s ""
5931 move nil)
5932 (unless (assoc (char-to-string char) org-emphasis-alist)
5933 (user-error "No such emphasis marker: \"%c\"" char))
5934 (setq s (char-to-string char)))
5935 (while (and (> (length string) 1)
5936 (equal (substring string 0 1) (substring string -1))
5937 (assoc (substring string 0 1) org-emphasis-alist))
5938 (setq string (substring string 1 -1)))
5939 (setq string (concat s string s))
5940 (when beg (delete-region beg end))
5941 (unless (or (bolp)
5942 (string-match (concat "[" (nth 0 erc) "\n]")
5943 (char-to-string (char-before (point)))))
5944 (insert " "))
5945 (unless (or (eobp)
5946 (string-match (concat "[" (nth 1 erc) "\n]")
5947 (char-to-string (char-after (point)))))
5948 (insert " ") (backward-char 1))
5949 (insert string)
5950 (and move (backward-char 1))))
5952 (defconst org-nonsticky-props
5953 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5955 (defsubst org-rear-nonsticky-at (pos)
5956 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5958 (defun org-activate-links (limit)
5959 "Add link properties to links.
5960 This includes angle, plain, and bracket links."
5961 (catch :exit
5962 (while (re-search-forward org-any-link-re limit t)
5963 (let* ((start (match-beginning 0))
5964 (end (match-end 0))
5965 (style (cond ((eq ?< (char-after start)) 'angle)
5966 ((eq ?\[ (char-after (1+ start))) 'bracket)
5967 (t 'plain))))
5968 (when (and (memq style org-highlight-links)
5969 ;; Do not confuse plain links with tags.
5970 (not (and (eq style 'plain)
5971 (let ((face (get-text-property
5972 (max (1- start) (point-min)) 'face)))
5973 (if (consp face) (memq 'org-tag face)
5974 (eq 'org-tag face))))))
5975 (let* ((link-object (save-excursion
5976 (goto-char start)
5977 (save-match-data (org-element-link-parser))))
5978 (link (org-element-property :raw-link link-object))
5979 (type (org-element-property :type link-object))
5980 (path (org-element-property :path link-object))
5981 (properties ;for link's visible part
5982 (list
5983 'face (pcase (org-link-get-parameter type :face)
5984 ((and (pred functionp) face) (funcall face path))
5985 ((and (pred facep) face) face)
5986 ((and (pred consp) face) face) ;anonymous
5987 (_ 'org-link))
5988 'mouse-face (or (org-link-get-parameter type :mouse-face)
5989 'highlight)
5990 'keymap (or (org-link-get-parameter type :keymap)
5991 org-mouse-map)
5992 'help-echo (pcase (org-link-get-parameter type :help-echo)
5993 ((and (pred stringp) echo) echo)
5994 ((and (pred functionp) echo) echo)
5995 (_ (concat "LINK: " link)))
5996 'htmlize-link (pcase (org-link-get-parameter type
5997 :htmlize-link)
5998 ((and (pred functionp) f) (funcall f))
5999 (_ `(:uri ,link)))
6000 'font-lock-multiline t)))
6001 (org-remove-flyspell-overlays-in start end)
6002 (org-rear-nonsticky-at end)
6003 (if (not (eq 'bracket style))
6004 (add-text-properties start end properties)
6005 ;; Handle invisible parts in bracket links.
6006 (remove-text-properties start end '(invisible nil))
6007 (let ((hidden
6008 (append `(invisible
6009 ,(or (org-link-get-parameter type :display)
6010 'org-link))
6011 properties))
6012 (visible-start (or (match-beginning 4) (match-beginning 2)))
6013 (visible-end (or (match-end 4) (match-end 2))))
6014 (add-text-properties start visible-start hidden)
6015 (add-text-properties visible-start visible-end properties)
6016 (add-text-properties visible-end end hidden)
6017 (org-rear-nonsticky-at visible-start)
6018 (org-rear-nonsticky-at visible-end)))
6019 (let ((f (org-link-get-parameter type :activate-func)))
6020 (when (functionp f)
6021 (funcall f start end path (eq style 'bracket))))
6022 (throw :exit t))))) ;signal success
6023 nil))
6025 (defun org-activate-code (limit)
6026 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6027 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6028 (remove-text-properties (match-beginning 0) (match-end 0)
6029 '(display t invisible t intangible t))
6032 (defcustom org-src-fontify-natively t
6033 "When non-nil, fontify code in code blocks.
6034 See also the `org-block' face."
6035 :type 'boolean
6036 :version "24.4"
6037 :package-version '(Org . "8.3")
6038 :group 'org-appearance
6039 :group 'org-babel)
6041 (defcustom org-allow-promoting-top-level-subtree nil
6042 "When non-nil, allow promoting a top level subtree.
6043 The leading star of the top level headline will be replaced
6044 by a #."
6045 :type 'boolean
6046 :version "24.1"
6047 :group 'org-appearance)
6049 (defun org-fontify-meta-lines-and-blocks (limit)
6050 (condition-case nil
6051 (org-fontify-meta-lines-and-blocks-1 limit)
6052 (error (message "org-mode fontification error in %S at %d"
6053 (current-buffer)
6054 (line-number-at-pos)))))
6056 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6057 "Fontify #+ lines and blocks."
6058 (let ((case-fold-search t))
6059 (when (re-search-forward
6060 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6061 limit t)
6062 (let ((beg (match-beginning 0))
6063 (block-start (match-end 0))
6064 (block-end nil)
6065 (lang (match-string 7))
6066 (beg1 (line-beginning-position 2))
6067 (dc1 (downcase (match-string 2)))
6068 (dc3 (downcase (match-string 3)))
6069 end end1 quoting block-type)
6070 (cond
6071 ((and (match-end 4) (equal dc3 "+begin"))
6072 ;; Truly a block
6073 (setq block-type (downcase (match-string 5))
6074 quoting (member block-type org-protecting-blocks))
6075 (when (re-search-forward
6076 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6077 nil t) ;; on purpose, we look further than LIMIT
6078 (setq end (min (point-max) (match-end 0))
6079 end1 (min (point-max) (1- (match-beginning 0))))
6080 (setq block-end (match-beginning 0))
6081 (when quoting
6082 (org-remove-flyspell-overlays-in beg1 end1)
6083 (remove-text-properties beg end
6084 '(display t invisible t intangible t)))
6085 (add-text-properties
6086 beg end '(font-lock-fontified t font-lock-multiline t))
6087 (add-text-properties beg beg1 '(face org-meta-line))
6088 (org-remove-flyspell-overlays-in beg beg1)
6089 (add-text-properties ; For end_src
6090 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6091 (org-remove-flyspell-overlays-in end1 end)
6092 (cond
6093 ((and lang (not (string= lang "")) org-src-fontify-natively)
6094 (org-src-font-lock-fontify-block lang block-start block-end)
6095 (add-text-properties beg1 block-end '(src-block t)))
6096 (quoting
6097 (add-text-properties beg1 (min (point-max) (1+ end1))
6098 (list 'face
6099 (list :inherit
6100 (let ((face-name
6101 (intern (format "org-block-%s" lang))))
6102 (append (and (facep face-name) (list face-name))
6103 '(org-block))))))) ; end of source block
6104 ((not org-fontify-quote-and-verse-blocks))
6105 ((string= block-type "quote")
6106 (add-face-text-property
6107 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6108 ((string= block-type "verse")
6109 (add-face-text-property
6110 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6111 (add-text-properties beg beg1 '(face org-block-begin-line))
6112 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6113 '(face org-block-end-line))
6115 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6116 (org-remove-flyspell-overlays-in
6117 (match-beginning 0)
6118 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6119 (add-text-properties
6120 beg (match-end 3)
6121 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6122 '(font-lock-fontified t invisible t)
6123 '(font-lock-fontified t face org-document-info-keyword)))
6124 (add-text-properties
6125 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6126 (if (string-equal dc1 "+title:")
6127 '(font-lock-fontified t face org-document-title)
6128 '(font-lock-fontified t face org-document-info))))
6129 ((string-prefix-p "+caption" dc1)
6130 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6131 (remove-text-properties (match-beginning 0) (match-end 0)
6132 '(display t invisible t intangible t))
6133 ;; Handle short captions.
6134 (save-excursion
6135 (beginning-of-line)
6136 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6137 (add-text-properties (line-beginning-position) (match-end 1)
6138 '(font-lock-fontified t face org-meta-line))
6139 (add-text-properties (match-end 0) (line-end-position)
6140 '(font-lock-fontified t face org-block))
6142 ((member dc3 '(" " ""))
6143 (org-remove-flyspell-overlays-in beg (match-end 0))
6144 (add-text-properties
6145 beg (match-end 0)
6146 '(font-lock-fontified t face font-lock-comment-face)))
6147 (t ;; just any other in-buffer setting, but not indented
6148 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6149 (remove-text-properties (match-beginning 0) (match-end 0)
6150 '(display t invisible t intangible t))
6151 (add-text-properties beg (match-end 0)
6152 '(font-lock-fontified t face org-meta-line))
6153 t))))))
6155 (defun org-fontify-drawers (limit)
6156 "Fontify drawers."
6157 (when (re-search-forward org-drawer-regexp limit t)
6158 (add-text-properties
6159 (match-beginning 0) (match-end 0)
6160 '(font-lock-fontified t face org-special-keyword))
6161 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6164 (defun org-fontify-macros (limit)
6165 "Fontify macros."
6166 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6167 (add-text-properties
6168 (match-beginning 0) (match-end 0)
6169 '(font-lock-fontified t face org-macro))
6170 (when org-hide-macro-markers
6171 (add-text-properties (match-end 2) (match-beginning 2)
6172 '(invisible t))
6173 (add-text-properties (match-beginning 1) (match-end 1)
6174 '(invisible t)))
6175 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6178 (defun org-activate-footnote-links (limit)
6179 "Add text properties for footnotes."
6180 (let ((fn (org-footnote-next-reference-or-definition limit)))
6181 (when fn
6182 (let* ((beg (nth 1 fn))
6183 (end (nth 2 fn))
6184 (label (car fn))
6185 (referencep (/= (line-beginning-position) beg)))
6186 (when (and referencep (nth 3 fn))
6187 (save-excursion
6188 (goto-char beg)
6189 (search-forward (or label "fn:"))
6190 (org-remove-flyspell-overlays-in beg (match-end 0))))
6191 (add-text-properties beg end
6192 (list 'mouse-face 'highlight
6193 'keymap org-mouse-map
6194 'help-echo
6195 (if referencep "Footnote reference"
6196 "Footnote definition")
6197 'font-lock-fontified t
6198 'font-lock-multiline t
6199 'face 'org-footnote))))))
6201 (defun org-activate-dates (limit)
6202 "Add text properties for dates."
6203 (when (and (re-search-forward org-tsr-regexp-both limit t)
6204 (not (equal (char-before (match-beginning 0)) 91)))
6205 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6206 (add-text-properties (match-beginning 0) (match-end 0)
6207 (list 'mouse-face 'highlight
6208 'keymap org-mouse-map))
6209 (org-rear-nonsticky-at (match-end 0))
6210 (when org-display-custom-times
6211 ;; If it's a date range, activate custom time for second date.
6212 (when (match-end 3)
6213 (org-display-custom-time (match-beginning 3) (match-end 3)))
6214 (org-display-custom-time (match-beginning 1) (match-end 1)))
6217 (defvar-local org-target-link-regexp nil
6218 "Regular expression matching radio targets in plain text.")
6220 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6221 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6222 border border border))
6223 "Regular expression matching a link target.")
6225 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6226 "Regular expression matching a radio target.")
6228 (defconst org-any-target-regexp
6229 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6230 "Regular expression matching any target.")
6232 (defun org-activate-target-links (limit)
6233 "Add text properties for target matches."
6234 (when org-target-link-regexp
6235 (let ((case-fold-search t))
6236 (when (re-search-forward org-target-link-regexp limit t)
6237 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6238 (add-text-properties (match-beginning 1) (match-end 1)
6239 (list 'mouse-face 'highlight
6240 'keymap org-mouse-map
6241 'help-echo "Radio target link"
6242 'org-linked-text t))
6243 (org-rear-nonsticky-at (match-end 1))
6244 t))))
6246 (defun org-update-radio-target-regexp ()
6247 "Find all radio targets in this file and update the regular expression.
6248 Also refresh fontification if needed."
6249 (interactive)
6250 (let ((old-regexp org-target-link-regexp)
6251 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6252 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6253 (targets
6254 (org-with-wide-buffer
6255 (goto-char (point-min))
6256 (let (rtn)
6257 (while (re-search-forward org-radio-target-regexp nil t)
6258 ;; Make sure point is really within the object.
6259 (backward-char)
6260 (let ((obj (org-element-context)))
6261 (when (eq (org-element-type obj) 'radio-target)
6262 (cl-pushnew (org-element-property :value obj) rtn
6263 :test #'equal))))
6264 rtn))))
6265 (setq org-target-link-regexp
6266 (and targets
6267 (concat before-re
6268 (mapconcat
6269 (lambda (x)
6270 (replace-regexp-in-string
6271 " +" "\\s-+" (regexp-quote x) t t))
6272 targets
6273 "\\|")
6274 after-re)))
6275 (unless (equal old-regexp org-target-link-regexp)
6276 ;; Clean-up cache.
6277 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6278 ((not org-target-link-regexp) old-regexp)
6280 (concat before-re
6281 (mapconcat
6282 (lambda (re)
6283 (substring re (length before-re)
6284 (- (length after-re))))
6285 (list old-regexp org-target-link-regexp)
6286 "\\|")
6287 after-re)))))
6288 (org-with-wide-buffer
6289 (goto-char (point-min))
6290 (while (re-search-forward regexp nil t)
6291 (org-element-cache-refresh (match-beginning 1)))))
6292 ;; Re fontify buffer.
6293 (when (memq 'radio org-highlight-links)
6294 (org-restart-font-lock)))))
6296 (defun org-hide-wide-columns (limit)
6297 (let (s e)
6298 (setq s (text-property-any (point) (or limit (point-max))
6299 'org-cwidth t))
6300 (when s
6301 (setq e (next-single-property-change s 'org-cwidth))
6302 (add-text-properties s e '(invisible org-cwidth))
6303 (goto-char e)
6304 t)))
6306 (defvar org-latex-and-related-regexp nil
6307 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6309 (defun org-compute-latex-and-related-regexp ()
6310 "Compute regular expression for LaTeX, entities and sub/superscript.
6311 Result depends on variable `org-highlight-latex-and-related'."
6312 (setq-local
6313 org-latex-and-related-regexp
6314 (let* ((re-sub
6315 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6316 ((eq org-use-sub-superscripts '{})
6317 (list org-match-substring-with-braces-regexp))
6318 (org-use-sub-superscripts (list org-match-substring-regexp))))
6319 (re-latex
6320 (when (memq 'latex org-highlight-latex-and-related)
6321 (let ((matchers (plist-get org-format-latex-options :matchers)))
6322 (delq nil
6323 (mapcar (lambda (x)
6324 (and (member (car x) matchers) (nth 1 x)))
6325 org-latex-regexps)))))
6326 (re-entities
6327 (when (memq 'entities org-highlight-latex-and-related)
6328 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6329 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6331 (defun org-do-latex-and-related (limit)
6332 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6333 LIMIT bounds the search for syntax to highlight. Stop at first
6334 highlighted object, if any. Return t if some highlighting was
6335 done, nil otherwise."
6336 (when (org-string-nw-p org-latex-and-related-regexp)
6337 (catch 'found
6338 (while (re-search-forward org-latex-and-related-regexp limit t)
6339 (unless
6340 (cl-some
6341 (lambda (f)
6342 (memq f '(org-code org-verbatim underline org-special-keyword)))
6343 (save-excursion
6344 (goto-char (1+ (match-beginning 0)))
6345 (face-at-point nil t)))
6346 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6347 '(?_ ?^))
6349 0)))
6350 (font-lock-prepend-text-property
6351 (+ offset (match-beginning 0)) (match-end 0)
6352 'face 'org-latex-and-related)
6353 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6354 '(font-lock-multiline t)))
6355 (throw 'found t)))
6356 nil)))
6358 (defun org-restart-font-lock ()
6359 "Restart `font-lock-mode', to force refontification."
6360 (when (and (boundp 'font-lock-mode) font-lock-mode)
6361 (font-lock-mode -1)
6362 (font-lock-mode 1)))
6364 (defun org-activate-tags (limit)
6365 (when (re-search-forward
6366 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6367 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6368 (add-text-properties (match-beginning 1) (match-end 1)
6369 (list 'mouse-face 'highlight
6370 'keymap org-mouse-map))
6371 (org-rear-nonsticky-at (match-end 1))
6374 (defun org-outline-level ()
6375 "Compute the outline level of the heading at point.
6377 If this is called at a normal headline, the level is the number
6378 of stars. Use `org-reduced-level' to remove the effect of
6379 `org-odd-levels'. Unlike to `org-current-level', this function
6380 takes into consideration inlinetasks."
6381 (org-with-wide-buffer
6382 (end-of-line)
6383 (if (re-search-backward org-outline-regexp-bol nil t)
6384 (1- (- (match-end 0) (match-beginning 0)))
6385 0)))
6387 (defvar org-font-lock-keywords nil)
6389 (defsubst org-re-property (property &optional literal allow-null value)
6390 "Return a regexp matching a PROPERTY line.
6392 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6393 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6394 non-nil, match properties even without a value.
6396 Match group 3 is set to the value when it exists. If there is no
6397 value and ALLOW-NULL is non-nil, it is set to the empty string.
6399 With optional argument VALUE, match only property lines with
6400 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6401 unless LITERAL is non-nil."
6402 (concat
6403 "^\\(?4:[ \t]*\\)"
6404 (format "\\(?1::\\(?2:%s\\):\\)"
6405 (if literal property (regexp-quote property)))
6406 (cond (value
6407 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6408 (if literal value (regexp-quote value))))
6409 (allow-null
6410 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6412 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6414 (defconst org-property-re
6415 (org-re-property "\\S-+" 'literal t)
6416 "Regular expression matching a property line.
6417 There are four matching groups:
6418 1: :PROPKEY: including the leading and trailing colon,
6419 2: PROPKEY without the leading and trailing colon,
6420 3: PROPVAL without leading or trailing spaces,
6421 4: the indentation of the current line,
6422 5: trailing whitespace.")
6424 (defvar org-font-lock-hook nil
6425 "Functions to be called for special font lock stuff.")
6427 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6429 (defvar org-font-lock-set-keywords-hook nil
6430 "Functions that can manipulate `org-font-lock-extra-keywords'.
6431 This is called after `org-font-lock-extra-keywords' is defined, but before
6432 it is installed to be used by font lock. This can be useful if something
6433 needs to be inserted at a specific position in the font-lock sequence.")
6435 (defun org-font-lock-hook (limit)
6436 "Run `org-font-lock-hook' within LIMIT."
6437 (run-hook-with-args 'org-font-lock-hook limit))
6439 (defun org-set-font-lock-defaults ()
6440 "Set font lock defaults for the current buffer."
6441 (let* ((em org-fontify-emphasized-text)
6442 (lk org-highlight-links)
6443 (org-font-lock-extra-keywords
6444 (list
6445 ;; Call the hook
6446 '(org-font-lock-hook)
6447 ;; Headlines
6448 `(,(if org-fontify-whole-heading-line
6449 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6450 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6451 (1 (org-get-level-face 1))
6452 (2 (org-get-level-face 2))
6453 (3 (org-get-level-face 3)))
6454 ;; Table lines
6455 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6456 (1 'org-table t))
6457 ;; Table internals
6458 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6459 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6460 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6461 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6462 ;; Drawers
6463 '(org-fontify-drawers)
6464 ;; Properties
6465 (list org-property-re
6466 '(1 'org-special-keyword t)
6467 '(3 'org-property-value t))
6468 ;; Link related fontification.
6469 '(org-activate-links)
6470 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6471 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6472 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6473 (when (memq 'footnote lk) '(org-activate-footnote-links))
6474 ;; Targets.
6475 (list org-any-target-regexp '(0 'org-target t))
6476 ;; Diary sexps.
6477 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6478 ;; Macro
6479 '(org-fontify-macros)
6480 '(org-hide-wide-columns (0 nil append))
6481 ;; TODO keyword
6482 (list (format org-heading-keyword-regexp-format
6483 org-todo-regexp)
6484 '(2 (org-get-todo-face 2) t))
6485 ;; DONE
6486 (if org-fontify-done-headline
6487 (list (format org-heading-keyword-regexp-format
6488 (concat
6489 "\\(?:"
6490 (mapconcat 'regexp-quote org-done-keywords "\\|")
6491 "\\)"))
6492 '(2 'org-headline-done t))
6493 nil)
6494 ;; Priorities
6495 '(org-font-lock-add-priority-faces)
6496 ;; Tags
6497 '(org-font-lock-add-tag-faces)
6498 ;; Tags groups
6499 (when (and org-group-tags org-tag-groups-alist)
6500 (list (concat org-outline-regexp-bol ".+\\(:"
6501 (regexp-opt (mapcar 'car org-tag-groups-alist))
6502 ":\\).*$")
6503 '(1 'org-tag-group prepend)))
6504 ;; Special keywords
6505 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6506 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6507 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6508 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6509 ;; Emphasis
6510 (when em '(org-do-emphasis-faces))
6511 ;; Checkboxes
6512 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6513 1 'org-checkbox prepend)
6514 (when (cdr (assq 'checkbox org-list-automatic-rules))
6515 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6516 (0 (org-get-checkbox-statistics-face) t)))
6517 ;; Description list items
6518 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6519 1 'org-list-dt prepend)
6520 ;; ARCHIVEd headings
6521 (list (concat
6522 org-outline-regexp-bol
6523 "\\(.*:" org-archive-tag ":.*\\)")
6524 '(1 'org-archived prepend))
6525 ;; Specials
6526 '(org-do-latex-and-related)
6527 '(org-fontify-entities)
6528 '(org-raise-scripts)
6529 ;; Code
6530 '(org-activate-code (1 'org-code t))
6531 ;; COMMENT
6532 (list (format
6533 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6534 org-todo-regexp
6535 org-comment-string)
6536 '(9 'org-special-keyword t))
6537 ;; Blocks and meta lines
6538 '(org-fontify-meta-lines-and-blocks))))
6539 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6540 (run-hooks 'org-font-lock-set-keywords-hook)
6541 ;; Now set the full font-lock-keywords
6542 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6543 (setq-local font-lock-defaults
6544 '(org-font-lock-keywords t nil nil backward-paragraph))
6545 (kill-local-variable 'font-lock-keywords)
6546 nil))
6548 (defun org-toggle-pretty-entities ()
6549 "Toggle the composition display of entities as UTF8 characters."
6550 (interactive)
6551 (setq-local org-pretty-entities (not org-pretty-entities))
6552 (org-restart-font-lock)
6553 (if org-pretty-entities
6554 (message "Entities are now displayed as UTF8 characters")
6555 (save-restriction
6556 (widen)
6557 (decompose-region (point-min) (point-max))
6558 (message "Entities are now displayed as plain text"))))
6560 (defvar-local org-custom-properties-overlays nil
6561 "List of overlays used for custom properties.")
6563 (defun org-toggle-custom-properties-visibility ()
6564 "Display or hide properties in `org-custom-properties'."
6565 (interactive)
6566 (if org-custom-properties-overlays
6567 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6568 (setq org-custom-properties-overlays nil))
6569 (when org-custom-properties
6570 (org-with-wide-buffer
6571 (goto-char (point-min))
6572 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6573 (while (re-search-forward regexp nil t)
6574 (let ((end (cdr (save-match-data (org-get-property-block)))))
6575 (when (and end (< (point) end))
6576 ;; Hide first custom property in current drawer.
6577 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6578 (overlay-put o 'invisible t)
6579 (overlay-put o 'org-custom-property t)
6580 (push o org-custom-properties-overlays))
6581 ;; Hide additional custom properties in the same drawer.
6582 (while (re-search-forward regexp end t)
6583 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6584 (overlay-put o 'invisible t)
6585 (overlay-put o 'org-custom-property t)
6586 (push o org-custom-properties-overlays)))))
6587 ;; Each entry is limited to a single property drawer.
6588 (outline-next-heading)))))))
6590 (defun org-fontify-entities (limit)
6591 "Find an entity to fontify."
6592 (let (ee)
6593 (when org-pretty-entities
6594 (catch 'match
6595 ;; "\_ "-family is left out on purpose. Only the first one,
6596 ;; i.e., "\_ ", could be fontified anyway, and it would be
6597 ;; confusing when adding a second white space character.
6598 (while (re-search-forward
6599 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6600 limit t)
6601 (when (and (not (org-at-comment-p))
6602 (setq ee (org-entity-get (match-string 1)))
6603 (= (length (nth 6 ee)) 1))
6604 (let* ((end (if (equal (match-string 2) "{}")
6605 (match-end 2)
6606 (match-end 1))))
6607 (add-text-properties
6608 (match-beginning 0) end
6609 (list 'font-lock-fontified t))
6610 (compose-region (match-beginning 0) end
6611 (nth 6 ee) nil)
6612 (backward-char 1)
6613 (throw 'match t))))
6614 nil))))
6616 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6617 "Fontify string S like in Org mode."
6618 (with-temp-buffer
6619 (insert s)
6620 (let ((org-odd-levels-only odd-levels))
6621 (org-mode)
6622 (org-font-lock-ensure)
6623 (buffer-string))))
6625 (defvar org-m nil)
6626 (defvar org-l nil)
6627 (defvar org-f nil)
6628 (defun org-get-level-face (n)
6629 "Get the right face for match N in font-lock matching of headlines."
6630 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6631 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6632 (if org-cycle-level-faces
6633 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6634 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6635 (cond
6636 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6637 ((eq n 2) org-f)
6638 (t (unless org-level-color-stars-only org-f))))
6640 (defun org-face-from-face-or-color (context inherit face-or-color)
6641 "Create a face list that inherits INHERIT, but sets the foreground color.
6642 When FACE-OR-COLOR is not a string, just return it."
6643 (if (stringp face-or-color)
6644 (list :inherit inherit
6645 (cdr (assoc context org-faces-easy-properties))
6646 face-or-color)
6647 face-or-color))
6649 (defun org-get-todo-face (kwd)
6650 "Get the right face for a TODO keyword KWD.
6651 If KWD is a number, get the corresponding match group."
6652 (when (numberp kwd) (setq kwd (match-string kwd)))
6653 (or (org-face-from-face-or-color
6654 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6655 (and (member kwd org-done-keywords) 'org-done)
6656 'org-todo))
6658 (defun org-get-priority-face (priority)
6659 "Get the right face for PRIORITY.
6660 PRIORITY is a character."
6661 (or (org-face-from-face-or-color
6662 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6663 'org-priority))
6665 (defun org-get-tag-face (tag)
6666 "Get the right face for TAG.
6667 If TAG is a number, get the corresponding match group."
6668 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6669 (or (org-face-from-face-or-color
6670 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6671 'org-tag)))
6673 (defun org-font-lock-add-priority-faces (limit)
6674 "Add the special priority faces."
6675 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6676 (add-text-properties
6677 (match-beginning 1) (match-end 1)
6678 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6679 'font-lock-fontified t))))
6681 (defun org-font-lock-add-tag-faces (limit)
6682 "Add the special tag faces."
6683 (when (and org-tag-faces org-tags-special-faces-re)
6684 (while (re-search-forward org-tags-special-faces-re limit t)
6685 (add-text-properties (match-beginning 1) (match-end 1)
6686 (list 'face (org-get-tag-face 1)
6687 'font-lock-fontified t))
6688 (backward-char 1))))
6690 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6691 "Remove fontification and activation overlays from links."
6692 (font-lock-default-unfontify-region beg end)
6693 (let* ((buffer-undo-list t)
6694 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6695 (inhibit-modification-hooks t)
6696 deactivate-mark buffer-file-name buffer-file-truename)
6697 (decompose-region beg end)
6698 (remove-text-properties beg end
6699 '(mouse-face t keymap t org-linked-text t
6700 invisible t intangible t
6701 org-emphasis t))
6702 (org-remove-font-lock-display-properties beg end)))
6704 (defconst org-script-display '(((raise -0.3) (height 0.7))
6705 ((raise 0.3) (height 0.7))
6706 ((raise -0.5))
6707 ((raise 0.5)))
6708 "Display properties for showing superscripts and subscripts.")
6710 (defun org-remove-font-lock-display-properties (beg end)
6711 "Remove specific display properties that have been added by font lock.
6712 The will remove the raise properties that are used to show superscripts
6713 and subscripts."
6714 (let (next prop)
6715 (while (< beg end)
6716 (setq next (next-single-property-change beg 'display nil end)
6717 prop (get-text-property beg 'display))
6718 (when (member prop org-script-display)
6719 (put-text-property beg next 'display nil))
6720 (setq beg next))))
6722 (defun org-raise-scripts (limit)
6723 "Add raise properties to sub/superscripts."
6724 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6725 (re-search-forward
6726 (if (eq org-use-sub-superscripts t)
6727 org-match-substring-regexp
6728 org-match-substring-with-braces-regexp)
6729 limit t))
6730 (let* ((pos (point)) table-p comment-p
6731 (mpos (match-beginning 3))
6732 (emph-p (get-text-property mpos 'org-emphasis))
6733 (link-p (get-text-property mpos 'mouse-face))
6734 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6735 (goto-char (point-at-bol))
6736 (setq table-p (looking-at-p org-table-dataline-regexp)
6737 comment-p (looking-at-p "^[ \t]*#[ +]"))
6738 (goto-char pos)
6739 ;; Handle a_b^c
6740 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6741 (unless (or comment-p emph-p link-p keyw-p)
6742 (put-text-property (match-beginning 3) (match-end 0)
6743 'display
6744 (if (equal (char-after (match-beginning 2)) ?^)
6745 (nth (if table-p 3 1) org-script-display)
6746 (nth (if table-p 2 0) org-script-display)))
6747 (add-text-properties (match-beginning 2) (match-end 2)
6748 (list 'invisible t
6749 'org-dwidth t 'org-dwidth-n 1))
6750 (if (and (eq (char-after (match-beginning 3)) ?{)
6751 (eq (char-before (match-end 3)) ?}))
6752 (progn
6753 (add-text-properties
6754 (match-beginning 3) (1+ (match-beginning 3))
6755 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6756 (add-text-properties
6757 (1- (match-end 3)) (match-end 3)
6758 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6759 t)))
6761 ;;;; Visibility cycling, including org-goto and indirect buffer
6763 ;;; Cycling
6765 (defvar-local org-cycle-global-status nil)
6766 (put 'org-cycle-global-status 'org-state t)
6767 (defvar-local org-cycle-subtree-status nil)
6768 (put 'org-cycle-subtree-status 'org-state t)
6770 (defvar org-inlinetask-min-level)
6772 (defun org-unlogged-message (&rest args)
6773 "Display a message, but avoid logging it in the *Messages* buffer."
6774 (let ((message-log-max nil))
6775 (apply 'message args)))
6777 ;;;###autoload
6778 (defun org-cycle (&optional arg)
6779 "TAB-action and visibility cycling for Org mode.
6781 This is the command invoked in Org mode by the `TAB' key. Its main
6782 purpose is outline visibility cycling, but it also invokes other actions
6783 in special contexts.
6785 When this function is called with a `\\[universal-argument]' prefix, rotate \
6786 the entire
6787 buffer through 3 states (global cycling)
6788 1. OVERVIEW: Show only top-level headlines.
6789 2. CONTENTS: Show all headlines of all levels, but no body text.
6790 3. SHOW ALL: Show everything.
6792 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6793 switch to the startup visibility,
6794 determined by the variable `org-startup-folded', and by any VISIBILITY
6795 properties in the buffer.
6797 With a `\\[universal-argument] \\[universal-argument] \
6798 \\[universal-argument]' prefix argument, show the entire buffer, including
6799 any drawers.
6801 When inside a table, re-align the table and move to the next field.
6803 When point is at the beginning of a headline, rotate the subtree started
6804 by this line through 3 different states (local cycling)
6805 1. FOLDED: Only the main headline is shown.
6806 2. CHILDREN: The main headline and the direct children are shown.
6807 From this state, you can move to one of the children
6808 and zoom in further.
6809 3. SUBTREE: Show the entire subtree, including body text.
6810 If there is no subtree, switch directly from CHILDREN to FOLDED.
6812 When point is at the beginning of an empty headline and the variable
6813 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6814 of the headline by demoting and promoting it to likely levels. This
6815 speeds up creation document structure by pressing `TAB' once or several
6816 times right after creating a new headline.
6818 When there is a numeric prefix, go up to a heading with level ARG, do
6819 a `show-subtree' and return to the previous cursor position. If ARG
6820 is negative, go up that many levels.
6822 When point is not at the beginning of a headline, execute the global
6823 binding for `TAB', which is re-indenting the line. See the option
6824 `org-cycle-emulate-tab' for details.
6826 As a special case, if point is at the beginning of the buffer and there is
6827 no headline in line 1, this function will act as if called with prefix arg
6828 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6829 prefix arg, but only
6830 if the variable `org-cycle-global-at-bob' is t."
6831 (interactive "P")
6832 (org-load-modules-maybe)
6833 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6834 (and org-cycle-level-after-item/entry-creation
6835 (or (org-cycle-level)
6836 (org-cycle-item-indentation))))
6837 (let* ((limit-level
6838 (or org-cycle-max-level
6839 (and (boundp 'org-inlinetask-min-level)
6840 org-inlinetask-min-level
6841 (1- org-inlinetask-min-level))))
6842 (nstars (and limit-level
6843 (if org-odd-levels-only
6844 (and limit-level (1- (* limit-level 2)))
6845 limit-level)))
6846 (org-outline-regexp
6847 (if (not (derived-mode-p 'org-mode))
6848 outline-regexp
6849 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6850 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6851 (not (looking-at org-outline-regexp))))
6852 (org-cycle-hook
6853 (if bob-special
6854 (delq 'org-optimize-window-after-visibility-change
6855 (copy-sequence org-cycle-hook))
6856 org-cycle-hook))
6857 (pos (point)))
6859 (cond
6861 ((equal arg '(16))
6862 (setq last-command 'dummy)
6863 (org-set-startup-visibility)
6864 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6866 ((equal arg '(64))
6867 (outline-show-all)
6868 (org-unlogged-message "Entire buffer visible, including drawers"))
6870 ((equal arg '(4)) (org-cycle-internal-global))
6872 ;; Try hiding block at point.
6873 ((org-hide-block-toggle-maybe))
6875 ;; Try cdlatex TAB completion
6876 ((org-try-cdlatex-tab))
6878 ;; Table: enter it or move to the next field.
6879 ((org-at-table-p 'any)
6880 (if (org-at-table.el-p)
6881 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6882 Use `\\[org-edit-special]' to edit table.el tables"))
6883 (if arg (org-table-edit-field t)
6884 (org-table-justify-field-maybe)
6885 (call-interactively 'org-table-next-field))))
6887 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6889 ;; Global cycling: delegate to `org-cycle-internal-global'.
6890 (bob-special (org-cycle-internal-global))
6892 ;; Drawers: delegate to `org-flag-drawer'.
6893 ((save-excursion
6894 (beginning-of-line 1)
6895 (looking-at org-drawer-regexp))
6896 (org-flag-drawer ; toggle block visibility
6897 (not (get-char-property (match-end 0) 'invisible))))
6899 ;; Show-subtree, ARG levels up from here.
6900 ((integerp arg)
6901 (save-excursion
6902 (org-back-to-heading)
6903 (outline-up-heading (if (< arg 0) (- arg)
6904 (- (funcall outline-level) arg)))
6905 (org-show-subtree)))
6907 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6908 ((and (featurep 'org-inlinetask)
6909 (org-inlinetask-at-task-p)
6910 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6911 (org-inlinetask-toggle-visibility))
6913 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6914 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6915 (save-excursion (move-beginning-of-line 1)
6916 (looking-at org-outline-regexp)))
6917 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6918 (org-cycle-internal-local))
6920 ;; From there: TAB emulation and template completion.
6921 (buffer-read-only (org-back-to-heading))
6923 ((run-hook-with-args-until-success
6924 'org-tab-after-check-for-cycling-hook))
6926 ((org-try-structure-completion))
6928 ((run-hook-with-args-until-success
6929 'org-tab-before-tab-emulation-hook))
6931 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6932 (or (not (bolp))
6933 (not (looking-at org-outline-regexp))))
6934 (call-interactively (global-key-binding "\t")))
6936 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6937 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6938 (or (and (eq org-cycle-emulate-tab 'white)
6939 (= (match-end 0) (point-at-eol)))
6940 (and (eq org-cycle-emulate-tab 'whitestart)
6941 (>= (match-end 0) pos))))
6943 (eq org-cycle-emulate-tab t))
6944 (call-interactively (global-key-binding "\t")))
6946 (t (save-excursion
6947 (org-back-to-heading)
6948 (org-cycle)))))))
6950 (defun org-cycle-internal-global ()
6951 "Do the global cycling action."
6952 ;; Hack to avoid display of messages for .org attachments in Gnus
6953 (let ((ga (string-match "\\*fontification" (buffer-name))))
6954 (cond
6955 ((and (eq last-command this-command)
6956 (eq org-cycle-global-status 'overview))
6957 ;; We just created the overview - now do table of contents
6958 ;; This can be slow in very large buffers, so indicate action
6959 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6960 (unless ga (org-unlogged-message "CONTENTS..."))
6961 (org-content)
6962 (unless ga (org-unlogged-message "CONTENTS...done"))
6963 (setq org-cycle-global-status 'contents)
6964 (run-hook-with-args 'org-cycle-hook 'contents))
6966 ((and (eq last-command this-command)
6967 (eq org-cycle-global-status 'contents))
6968 ;; We just showed the table of contents - now show everything
6969 (run-hook-with-args 'org-pre-cycle-hook 'all)
6970 (outline-show-all)
6971 (unless ga (org-unlogged-message "SHOW ALL"))
6972 (setq org-cycle-global-status 'all)
6973 (run-hook-with-args 'org-cycle-hook 'all))
6976 ;; Default action: go to overview
6977 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6978 (org-overview)
6979 (unless ga (org-unlogged-message "OVERVIEW"))
6980 (setq org-cycle-global-status 'overview)
6981 (run-hook-with-args 'org-cycle-hook 'overview)))))
6983 (defvar org-called-with-limited-levels nil
6984 "Non-nil when `org-with-limited-levels' is currently active.")
6986 (defun org-invisible-p (&optional pos)
6987 "Non-nil if the character after POS is invisible.
6988 If POS is nil, use `point' instead."
6989 (get-char-property (or pos (point)) 'invisible))
6991 (defun org-cycle-internal-local ()
6992 "Do the local cycling action."
6993 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6994 ;; First, determine end of headline (EOH), end of subtree or item
6995 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6996 (save-excursion
6997 (if (org-at-item-p)
6998 (progn
6999 (beginning-of-line)
7000 (setq struct (org-list-struct))
7001 (setq eoh (point-at-eol))
7002 (setq eos (org-list-get-item-end-before-blank (point) struct))
7003 (setq has-children (org-list-has-child-p (point) struct)))
7004 (org-back-to-heading)
7005 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7006 (setq eos (save-excursion (org-end-of-subtree t t)
7007 (when (bolp) (backward-char)) (point)))
7008 (setq has-children
7009 (or (save-excursion
7010 (let ((level (funcall outline-level)))
7011 (outline-next-heading)
7012 (and (org-at-heading-p t)
7013 (> (funcall outline-level) level))))
7014 (save-excursion
7015 (org-list-search-forward (org-item-beginning-re) eos t)))))
7016 ;; Determine end invisible part of buffer (EOL)
7017 (beginning-of-line 2)
7018 (while (and (not (eobp)) ;This is like `next-line'.
7019 (get-char-property (1- (point)) 'invisible))
7020 (goto-char (next-single-char-property-change (point) 'invisible))
7021 (and (eolp) (beginning-of-line 2)))
7022 (setq eol (point)))
7023 ;; Find out what to do next and set `this-command'
7024 (cond
7025 ((= eos eoh)
7026 ;; Nothing is hidden behind this heading
7027 (unless (org-before-first-heading-p)
7028 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7029 (org-unlogged-message "EMPTY ENTRY")
7030 (setq org-cycle-subtree-status nil)
7031 (save-excursion
7032 (goto-char eos)
7033 (outline-next-heading)
7034 (when (org-invisible-p) (org-flag-heading nil))))
7035 ((and (or (>= eol eos)
7036 (not (string-match "\\S-" (buffer-substring eol eos))))
7037 (or has-children
7038 (not (setq children-skipped
7039 org-cycle-skip-children-state-if-no-children))))
7040 ;; Entire subtree is hidden in one line: children view
7041 (unless (org-before-first-heading-p)
7042 (run-hook-with-args 'org-pre-cycle-hook 'children))
7043 (if (org-at-item-p)
7044 (org-list-set-item-visibility (point-at-bol) struct 'children)
7045 (org-show-entry)
7046 (org-with-limited-levels (org-show-children))
7047 ;; FIXME: This slows down the func way too much.
7048 ;; How keep drawers hidden in subtree anyway?
7049 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7050 ;; (org-cycle-hide-drawers 'subtree))
7052 ;; Fold every list in subtree to top-level items.
7053 (when (eq org-cycle-include-plain-lists 'integrate)
7054 (save-excursion
7055 (org-back-to-heading)
7056 (while (org-list-search-forward (org-item-beginning-re) eos t)
7057 (beginning-of-line 1)
7058 (let* ((struct (org-list-struct))
7059 (prevs (org-list-prevs-alist struct))
7060 (end (org-list-get-bottom-point struct)))
7061 (dolist (e (org-list-get-all-items (point) struct prevs))
7062 (org-list-set-item-visibility e struct 'folded))
7063 (goto-char (if (< end eos) end eos)))))))
7064 (org-unlogged-message "CHILDREN")
7065 (save-excursion
7066 (goto-char eos)
7067 (outline-next-heading)
7068 (when (org-invisible-p) (org-flag-heading nil)))
7069 (setq org-cycle-subtree-status 'children)
7070 (unless (org-before-first-heading-p)
7071 (run-hook-with-args 'org-cycle-hook 'children)))
7072 ((or children-skipped
7073 (and (eq last-command this-command)
7074 (eq org-cycle-subtree-status 'children)))
7075 ;; We just showed the children, or no children are there,
7076 ;; now show everything.
7077 (unless (org-before-first-heading-p)
7078 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7079 (outline-flag-region eoh eos nil)
7080 (org-unlogged-message
7081 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7082 (setq org-cycle-subtree-status 'subtree)
7083 (unless (org-before-first-heading-p)
7084 (run-hook-with-args 'org-cycle-hook 'subtree)))
7086 ;; Default action: hide the subtree.
7087 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7088 (outline-flag-region eoh eos t)
7089 (org-unlogged-message "FOLDED")
7090 (setq org-cycle-subtree-status 'folded)
7091 (unless (org-before-first-heading-p)
7092 (run-hook-with-args 'org-cycle-hook 'folded))))))
7094 ;;;###autoload
7095 (defun org-global-cycle (&optional arg)
7096 "Cycle the global visibility. For details see `org-cycle'.
7097 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7098 With a numeric prefix, show all headlines up to that level."
7099 (interactive "P")
7100 (let ((org-cycle-include-plain-lists
7101 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7102 (cond
7103 ((integerp arg)
7104 (outline-show-all)
7105 (outline-hide-sublevels arg)
7106 (setq org-cycle-global-status 'contents))
7107 ((equal arg '(4))
7108 (org-set-startup-visibility)
7109 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7111 (org-cycle '(4))))))
7113 (defun org-set-startup-visibility ()
7114 "Set the visibility required by startup options and properties."
7115 (cond
7116 ((eq org-startup-folded t)
7117 (org-overview))
7118 ((eq org-startup-folded 'content)
7119 (org-content))
7120 ((or (eq org-startup-folded 'showeverything)
7121 (eq org-startup-folded nil))
7122 (outline-show-all)))
7123 (unless (eq org-startup-folded 'showeverything)
7124 (when org-hide-block-startup (org-hide-block-all))
7125 (org-set-visibility-according-to-property 'no-cleanup)
7126 (org-cycle-hide-archived-subtrees 'all)
7127 (org-cycle-hide-drawers 'all)
7128 (org-cycle-show-empty-lines t)))
7130 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7131 "Switch subtree visibilities according to :VISIBILITY: property."
7132 (interactive)
7133 (org-with-wide-buffer
7134 (goto-char (point-min))
7135 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7136 (if (not (org-at-property-p)) (outline-next-heading)
7137 (let ((state (match-string 3)))
7138 (save-excursion
7139 (org-back-to-heading t)
7140 (outline-hide-subtree)
7141 (org-reveal)
7142 (cond
7143 ((equal state "folded")
7144 (outline-hide-subtree))
7145 ((equal state "children")
7146 (org-show-hidden-entry)
7147 (org-show-children))
7148 ((equal state "content")
7149 (save-excursion
7150 (save-restriction
7151 (org-narrow-to-subtree)
7152 (org-content))))
7153 ((member state '("all" "showall"))
7154 (outline-show-subtree)))))))
7155 (unless no-cleanup
7156 (org-cycle-hide-archived-subtrees 'all)
7157 (org-cycle-hide-drawers 'all)
7158 (org-cycle-show-empty-lines 'all))))
7160 ;; This function uses outline-regexp instead of the more fundamental
7161 ;; org-outline-regexp so that org-cycle-global works outside of Org
7162 ;; buffers, where outline-regexp is needed.
7163 (defun org-overview ()
7164 "Switch to overview mode, showing only top-level headlines.
7165 This shows all headlines with a level equal or greater than the level
7166 of the first headline in the buffer. This is important, because if the
7167 first headline is not level one, then (hide-sublevels 1) gives confusing
7168 results."
7169 (interactive)
7170 (save-excursion
7171 (let ((level
7172 (save-excursion
7173 (goto-char (point-min))
7174 (when (re-search-forward (concat "^" outline-regexp) nil t)
7175 (goto-char (match-beginning 0))
7176 (funcall outline-level)))))
7177 (and level (outline-hide-sublevels level)))))
7179 (defun org-content (&optional arg)
7180 "Show all headlines in the buffer, like a table of contents.
7181 With numerical argument N, show content up to level N."
7182 (interactive "P")
7183 (org-overview)
7184 (save-excursion
7185 ;; Visit all headings and show their offspring
7186 (and (integerp arg) (org-overview))
7187 (goto-char (point-max))
7188 (catch 'exit
7189 (while (and (progn (condition-case nil
7190 (outline-previous-visible-heading 1)
7191 (error (goto-char (point-min))))
7193 (looking-at org-outline-regexp))
7194 (if (integerp arg)
7195 (org-show-children (1- arg))
7196 (outline-show-branches))
7197 (when (bobp) (throw 'exit nil))))))
7199 (defun org-optimize-window-after-visibility-change (state)
7200 "Adjust the window after a change in outline visibility.
7201 This function is the default value of the hook `org-cycle-hook'."
7202 (when (get-buffer-window (current-buffer))
7203 (cond
7204 ((eq state 'content) nil)
7205 ((eq state 'all) nil)
7206 ((eq state 'folded) nil)
7207 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7208 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7210 (defun org-remove-empty-overlays-at (pos)
7211 "Remove outline overlays that do not contain non-white stuff."
7212 (dolist (o (overlays-at pos))
7213 (and (eq 'outline (overlay-get o 'invisible))
7214 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7215 (overlay-end o))))
7216 (delete-overlay o))))
7218 (defun org-clean-visibility-after-subtree-move ()
7219 "Fix visibility issues after moving a subtree."
7220 ;; First, find a reasonable region to look at:
7221 ;; Start two siblings above, end three below
7222 (let* ((beg (save-excursion
7223 (and (org-get-last-sibling)
7224 (org-get-last-sibling))
7225 (point)))
7226 (end (save-excursion
7227 (and (org-get-next-sibling)
7228 (org-get-next-sibling)
7229 (org-get-next-sibling))
7230 (if (org-at-heading-p)
7231 (point-at-eol)
7232 (point))))
7233 (level (looking-at "\\*+"))
7234 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7235 (save-excursion
7236 (save-restriction
7237 (narrow-to-region beg end)
7238 (when re
7239 ;; Properly fold already folded siblings
7240 (goto-char (point-min))
7241 (while (re-search-forward re nil t)
7242 (when (and (not (org-invisible-p))
7243 (save-excursion
7244 (goto-char (point-at-eol)) (org-invisible-p)))
7245 (outline-hide-entry))))
7246 (org-cycle-show-empty-lines 'overview)
7247 (org-cycle-hide-drawers 'overview)))))
7249 (defun org-cycle-show-empty-lines (state)
7250 "Show empty lines above all visible headlines.
7251 The region to be covered depends on STATE when called through
7252 `org-cycle-hook'. Lisp program can use t for STATE to get the
7253 entire buffer covered. Note that an empty line is only shown if there
7254 are at least `org-cycle-separator-lines' empty lines before the headline."
7255 (when (/= org-cycle-separator-lines 0)
7256 (save-excursion
7257 (let* ((n (abs org-cycle-separator-lines))
7258 (re (cond
7259 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7260 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7261 (t (let ((ns (number-to-string (- n 2))))
7262 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7263 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7264 beg end)
7265 (cond
7266 ((memq state '(overview contents t))
7267 (setq beg (point-min) end (point-max)))
7268 ((memq state '(children folded))
7269 (setq beg (point)
7270 end (progn (org-end-of-subtree t t)
7271 (line-beginning-position 2)))))
7272 (when beg
7273 (goto-char beg)
7274 (while (re-search-forward re end t)
7275 (unless (get-char-property (match-end 1) 'invisible)
7276 (let ((e (match-end 1))
7277 (b (if (>= org-cycle-separator-lines 0)
7278 (match-beginning 1)
7279 (save-excursion
7280 (goto-char (match-beginning 0))
7281 (skip-chars-backward " \t\n")
7282 (line-end-position)))))
7283 (outline-flag-region b e nil))))))))
7284 ;; Never hide empty lines at the end of the file.
7285 (save-excursion
7286 (goto-char (point-max))
7287 (outline-previous-heading)
7288 (outline-end-of-heading)
7289 (when (and (looking-at "[ \t\n]+")
7290 (= (match-end 0) (point-max)))
7291 (outline-flag-region (point) (match-end 0) nil))))
7293 (defun org-show-empty-lines-in-parent ()
7294 "Move to the parent and re-show empty lines before visible headlines."
7295 (save-excursion
7296 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7297 (org-cycle-show-empty-lines context))))
7299 (defun org-files-list ()
7300 "Return `org-agenda-files' list, plus all open Org files.
7301 This is useful for operations that need to scan all of a user's
7302 open and agenda-wise Org files."
7303 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7304 (dolist (buf (buffer-list))
7305 (with-current-buffer buf
7306 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7307 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7308 files))
7310 (defsubst org-entry-beginning-position ()
7311 "Return the beginning position of the current entry."
7312 (save-excursion (org-back-to-heading t) (point)))
7314 (defsubst org-entry-end-position ()
7315 "Return the end position of the current entry."
7316 (save-excursion (outline-next-heading) (point)))
7318 (defun org-cycle-hide-drawers (state &optional exceptions)
7319 "Re-hide all drawers after a visibility state change.
7320 When non-nil, optional argument EXCEPTIONS is a list of strings
7321 specifying which drawers should not be hidden."
7322 (when (and (derived-mode-p 'org-mode)
7323 (not (memq state '(overview folded contents))))
7324 (save-excursion
7325 (let* ((globalp (memq state '(contents all)))
7326 (beg (if globalp (point-min) (point)))
7327 (end (if globalp (point-max)
7328 (if (eq state 'children)
7329 (save-excursion (outline-next-heading) (point))
7330 (org-end-of-subtree t)))))
7331 (goto-char beg)
7332 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7333 (unless (member-ignore-case (match-string 1) exceptions)
7334 (let ((drawer (org-element-at-point)))
7335 (when (memq (org-element-type drawer) '(drawer property-drawer))
7336 (org-flag-drawer t drawer)
7337 ;; Make sure to skip drawer entirely or we might flag
7338 ;; it another time when matching its ending line with
7339 ;; `org-drawer-regexp'.
7340 (goto-char (org-element-property :end drawer))))))))))
7342 (defun org-flag-drawer (flag &optional element)
7343 "When FLAG is non-nil, hide the drawer we are at.
7344 Otherwise make it visible. When optional argument ELEMENT is
7345 a parsed drawer, as returned by `org-element-at-point', hide or
7346 show that drawer instead."
7347 (let ((drawer (or element
7348 (and (save-excursion
7349 (beginning-of-line)
7350 (looking-at-p org-drawer-regexp))
7351 (org-element-at-point)))))
7352 (when (memq (org-element-type drawer) '(drawer property-drawer))
7353 (let ((post (org-element-property :post-affiliated drawer)))
7354 (save-excursion
7355 (outline-flag-region
7356 (progn (goto-char post) (line-end-position))
7357 (progn (goto-char (org-element-property :end drawer))
7358 (skip-chars-backward " \r\t\n")
7359 (line-end-position))
7360 flag))
7361 ;; When the drawer is hidden away, make sure point lies in
7362 ;; a visible part of the buffer.
7363 (when (and flag (> (line-beginning-position) post))
7364 (goto-char post))))))
7366 (defun org-subtree-end-visible-p ()
7367 "Is the end of the current subtree visible?"
7368 (pos-visible-in-window-p
7369 (save-excursion (org-end-of-subtree t) (point))))
7371 (defun org-first-headline-recenter ()
7372 "Move cursor to the first headline and recenter the headline."
7373 (let ((window (get-buffer-window)))
7374 (when window
7375 (goto-char (point-min))
7376 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7377 (set-window-start window (line-beginning-position))))))
7379 ;;; Saving and restoring visibility
7381 (defun org-outline-overlay-data (&optional use-markers)
7382 "Return a list of the locations of all outline overlays.
7383 These are overlays with the `invisible' property value `outline'.
7384 The return value is a list of cons cells, with start and stop
7385 positions for each overlay.
7386 If USE-MARKERS is set, return the positions as markers."
7387 (let (beg end)
7388 (org-with-wide-buffer
7389 (delq nil
7390 (mapcar (lambda (o)
7391 (when (eq (overlay-get o 'invisible) 'outline)
7392 (setq beg (overlay-start o)
7393 end (overlay-end o))
7394 (and beg end (> end beg)
7395 (if use-markers
7396 (cons (copy-marker beg)
7397 (copy-marker end t))
7398 (cons beg end)))))
7399 (overlays-in (point-min) (point-max)))))))
7401 (defun org-set-outline-overlay-data (data)
7402 "Create visibility overlays for all positions in DATA.
7403 DATA should have been made by `org-outline-overlay-data'."
7404 (org-with-wide-buffer
7405 (outline-show-all)
7406 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7408 ;;; Folding of blocks
7410 (defvar-local org-hide-block-overlays nil
7411 "Overlays hiding blocks.")
7413 (defun org-block-map (function &optional start end)
7414 "Call FUNCTION at the head of all source blocks in the current buffer.
7415 Optional arguments START and END can be used to limit the range."
7416 (let ((start (or start (point-min)))
7417 (end (or end (point-max))))
7418 (save-excursion
7419 (goto-char start)
7420 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7421 (save-excursion
7422 (save-match-data
7423 (goto-char (match-beginning 0))
7424 (funcall function)))))))
7426 (defun org-hide-block-toggle-all ()
7427 "Toggle the visibility of all blocks in the current buffer."
7428 (org-block-map 'org-hide-block-toggle))
7430 (defun org-hide-block-all ()
7431 "Fold all blocks in the current buffer."
7432 (interactive)
7433 (org-show-block-all)
7434 (org-block-map 'org-hide-block-toggle-maybe))
7436 (defun org-show-block-all ()
7437 "Unfold all blocks in the current buffer."
7438 (interactive)
7439 (mapc #'delete-overlay org-hide-block-overlays)
7440 (setq org-hide-block-overlays nil))
7442 (defun org-hide-block-toggle-maybe ()
7443 "Toggle visibility of block at point.
7444 Unlike to `org-hide-block-toggle', this function does not throw
7445 an error. Return a non-nil value when toggling is successful."
7446 (interactive)
7447 (ignore-errors (org-hide-block-toggle)))
7449 (defun org-hide-block-toggle (&optional force)
7450 "Toggle the visibility of the current block.
7451 When optional argument FORCE is `off', make block visible. If it
7452 is non-nil, hide it unconditionally. Throw an error when not at
7453 a block. Return a non-nil value when toggling is successful."
7454 (interactive)
7455 (let ((element (org-element-at-point)))
7456 (unless (memq (org-element-type element)
7457 '(center-block comment-block dynamic-block example-block
7458 export-block quote-block special-block
7459 src-block verse-block))
7460 (user-error "Not at a block"))
7461 (let* ((start (save-excursion
7462 (goto-char (org-element-property :post-affiliated element))
7463 (line-end-position)))
7464 (end (save-excursion
7465 (goto-char (org-element-property :end element))
7466 (skip-chars-backward " \r\t\n")
7467 (line-end-position)))
7468 (overlays (overlays-at start)))
7469 (cond
7470 ;; Do nothing when not before or at the block opening line or
7471 ;; at the block closing line.
7472 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7473 ((and (not (eq force 'off))
7474 (not (memq t (mapcar
7475 (lambda (o)
7476 (eq (overlay-get o 'invisible) 'org-hide-block))
7477 overlays))))
7478 (let ((ov (make-overlay start end)))
7479 (overlay-put ov 'invisible 'org-hide-block)
7480 ;; Make the block accessible to `isearch'.
7481 (overlay-put
7482 ov 'isearch-open-invisible
7483 (lambda (ov)
7484 (when (memq ov org-hide-block-overlays)
7485 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7486 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7487 (delete-overlay ov))))
7488 (push ov org-hide-block-overlays)
7489 ;; When the block is hidden away, make sure point is left in
7490 ;; a visible part of the buffer.
7491 (when (> (line-beginning-position) start)
7492 (goto-char start)
7493 (beginning-of-line))
7494 ;; Signal successful toggling.
7496 ((or (not force) (eq force 'off))
7497 (dolist (ov overlays t)
7498 (when (memq ov org-hide-block-overlays)
7499 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7500 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7501 (delete-overlay ov))))))))
7503 ;; Remove overlays when changing major mode
7504 (add-hook 'org-mode-hook
7505 (lambda () (add-hook 'change-major-mode-hook
7506 'org-show-block-all 'append 'local)))
7508 ;;; Org-goto
7510 (defvar org-goto-window-configuration nil)
7511 (defvar org-goto-marker nil)
7512 (defvar org-goto-map)
7513 (defun org-goto-map ()
7514 "Set the keymap `org-goto'."
7515 (setq org-goto-map
7516 (let ((map (make-sparse-keymap)))
7517 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7518 mouse-drag-region universal-argument org-occur)))
7519 (dolist (cmd cmds)
7520 (substitute-key-definition cmd cmd map global-map)))
7521 (suppress-keymap map)
7522 (org-defkey map "\C-m" 'org-goto-ret)
7523 (org-defkey map [(return)] 'org-goto-ret)
7524 (org-defkey map [(left)] 'org-goto-left)
7525 (org-defkey map [(right)] 'org-goto-right)
7526 (org-defkey map [(control ?g)] 'org-goto-quit)
7527 (org-defkey map "\C-i" 'org-cycle)
7528 (org-defkey map [(tab)] 'org-cycle)
7529 (org-defkey map [(down)] 'outline-next-visible-heading)
7530 (org-defkey map [(up)] 'outline-previous-visible-heading)
7531 (if org-goto-auto-isearch
7532 (if (fboundp 'define-key-after)
7533 (define-key-after map [t] 'org-goto-local-auto-isearch)
7534 nil)
7535 (org-defkey map "q" 'org-goto-quit)
7536 (org-defkey map "n" 'outline-next-visible-heading)
7537 (org-defkey map "p" 'outline-previous-visible-heading)
7538 (org-defkey map "f" 'outline-forward-same-level)
7539 (org-defkey map "b" 'outline-backward-same-level)
7540 (org-defkey map "u" 'outline-up-heading))
7541 (org-defkey map "/" 'org-occur)
7542 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7543 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7544 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7545 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7546 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7547 map)))
7549 (defconst org-goto-help
7550 "Browse buffer copy, to find location or copy text.%s
7551 RET=jump to location C-g=quit and return to previous location
7552 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7554 (defvar org-goto-start-pos) ; dynamically scoped parameter
7556 (defun org-goto (&optional alternative-interface)
7557 "Look up a different location in the current file, keeping current visibility.
7559 When you want look-up or go to a different location in a
7560 document, the fastest way is often to fold the entire buffer and
7561 then dive into the tree. This method has the disadvantage, that
7562 the previous location will be folded, which may not be what you
7563 want.
7565 This command works around this by showing a copy of the current
7566 buffer in an indirect buffer, in overview mode. You can dive
7567 into the tree in that copy, use org-occur and incremental search
7568 to find a location. When pressing RET or `Q', the command
7569 returns to the original buffer in which the visibility is still
7570 unchanged. After RET it will also jump to the location selected
7571 in the indirect buffer and expose the headline hierarchy above.
7573 With a prefix argument, use the alternative interface: e.g., if
7574 `org-goto-interface' is `outline' use `outline-path-completion'."
7575 (interactive "P")
7576 (org-goto-map)
7577 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7578 (org-refile-use-outline-path t)
7579 (org-refile-target-verify-function nil)
7580 (interface
7581 (if (not alternative-interface)
7582 org-goto-interface
7583 (if (eq org-goto-interface 'outline)
7584 'outline-path-completion
7585 'outline)))
7586 (org-goto-start-pos (point))
7587 (selected-point
7588 (if (eq interface 'outline)
7589 (car (org-get-location (current-buffer) org-goto-help))
7590 (let ((pa (org-refile-get-location "Goto")))
7591 (org-refile-check-position pa)
7592 (nth 3 pa)))))
7593 (if selected-point
7594 (progn
7595 (org-mark-ring-push org-goto-start-pos)
7596 (goto-char selected-point)
7597 (when (or (org-invisible-p) (org-invisible-p2))
7598 (org-show-context 'org-goto)))
7599 (message "Quit"))))
7601 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7602 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7603 (defvar org-goto-local-auto-isearch-map) ; defined below
7605 (defun org-get-location (_buf help)
7606 "Let the user select a location in current buffer.
7607 This function uses a recursive edit. It returns the selected position
7608 or nil."
7609 (org-no-popups
7610 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7611 (isearch-hide-immediately nil)
7612 (isearch-search-fun-function
7613 (lambda () 'org-goto-local-search-headings))
7614 (org-goto-selected-point org-goto-exit-command))
7615 (save-excursion
7616 (save-window-excursion
7617 (delete-other-windows)
7618 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7619 (pop-to-buffer-same-window
7620 (condition-case nil
7621 (make-indirect-buffer (current-buffer) "*org-goto*")
7622 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7623 (with-output-to-temp-buffer "*Org Help*"
7624 (princ (format help (if org-goto-auto-isearch
7625 " Just type for auto-isearch."
7626 " n/p/f/b/u to navigate, q to quit."))))
7627 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7628 (setq buffer-read-only nil)
7629 (let ((org-startup-truncated t)
7630 (org-startup-folded nil)
7631 (org-startup-align-all-tables nil))
7632 (org-mode)
7633 (org-overview))
7634 (setq buffer-read-only t)
7635 (if (and (boundp 'org-goto-start-pos)
7636 (integer-or-marker-p org-goto-start-pos))
7637 (progn (goto-char org-goto-start-pos)
7638 (when (org-invisible-p)
7639 (org-show-set-visibility 'lineage)))
7640 (goto-char (point-min)))
7641 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7642 (message "Select location and press RET")
7643 (use-local-map org-goto-map)
7644 (recursive-edit)))
7645 (kill-buffer "*org-goto*")
7646 (cons org-goto-selected-point org-goto-exit-command))))
7648 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7649 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7650 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7651 (if (fboundp 'isearch-other-control-char)
7652 (progn
7653 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7654 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7655 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7656 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7657 (define-key org-goto-local-auto-isearch-map [return] nil))
7659 (defun org-goto-local-search-headings (string bound noerror)
7660 "Search and make sure that any matches are in headlines."
7661 (catch 'return
7662 (while (if isearch-forward
7663 (search-forward string bound noerror)
7664 (search-backward string bound noerror))
7665 (when (save-match-data
7666 (and (save-excursion
7667 (beginning-of-line)
7668 (looking-at org-complex-heading-regexp))
7669 (or (not (match-beginning 5))
7670 (< (point) (match-beginning 5)))))
7671 (throw 'return (point))))))
7673 (defun org-goto-local-auto-isearch ()
7674 "Start isearch."
7675 (interactive)
7676 (goto-char (point-min))
7677 (let ((keys (this-command-keys)))
7678 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7679 (isearch-mode t)
7680 (isearch-process-search-char (string-to-char keys)))))
7682 (defun org-goto-ret (&optional _arg)
7683 "Finish `org-goto' by going to the new location."
7684 (interactive "P")
7685 (setq org-goto-selected-point (point))
7686 (setq org-goto-exit-command 'return)
7687 (throw 'exit nil))
7689 (defun org-goto-left ()
7690 "Finish `org-goto' by going to the new location."
7691 (interactive)
7692 (if (org-at-heading-p)
7693 (progn
7694 (beginning-of-line 1)
7695 (setq org-goto-selected-point (point)
7696 org-goto-exit-command 'left)
7697 (throw 'exit nil))
7698 (user-error "Not on a heading")))
7700 (defun org-goto-right ()
7701 "Finish `org-goto' by going to the new location."
7702 (interactive)
7703 (if (org-at-heading-p)
7704 (progn
7705 (setq org-goto-selected-point (point)
7706 org-goto-exit-command 'right)
7707 (throw 'exit nil))
7708 (user-error "Not on a heading")))
7710 (defun org-goto-quit ()
7711 "Finish `org-goto' without cursor motion."
7712 (interactive)
7713 (setq org-goto-selected-point nil)
7714 (setq org-goto-exit-command 'quit)
7715 (throw 'exit nil))
7717 ;;; Indirect buffer display of subtrees
7719 (defvar org-indirect-dedicated-frame nil
7720 "This is the frame being used for indirect tree display.")
7721 (defvar org-last-indirect-buffer nil)
7723 (defun org-tree-to-indirect-buffer (&optional arg)
7724 "Create indirect buffer and narrow it to current subtree.
7726 With a numerical prefix ARG, go up to this level and then take that tree.
7727 If ARG is negative, go up that many levels.
7729 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7730 indirect buffer previously made with this command, to avoid proliferation of
7731 indirect buffers. However, when you call the command with a \
7732 `\\[universal-argument]' prefix, or
7733 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7734 so that you can work with several indirect buffers at the same time. If
7735 `org-indirect-buffer-display' is `dedicated-frame', the \
7736 `\\[universal-argument]' prefix also
7737 requests that a new frame be made for the new buffer, so that the dedicated
7738 frame is not changed."
7739 (interactive "P")
7740 (let ((cbuf (current-buffer))
7741 (cwin (selected-window))
7742 (pos (point))
7743 beg end level heading ibuf)
7744 (save-excursion
7745 (org-back-to-heading t)
7746 (when (numberp arg)
7747 (setq level (org-outline-level))
7748 (when (< arg 0) (setq arg (+ level arg)))
7749 (while (> (setq level (org-outline-level)) arg)
7750 (org-up-heading-safe)))
7751 (setq beg (point)
7752 heading (org-get-heading 'no-tags))
7753 (org-end-of-subtree t t)
7754 (when (org-at-heading-p) (backward-char 1))
7755 (setq end (point)))
7756 (when (and (buffer-live-p org-last-indirect-buffer)
7757 (not (eq org-indirect-buffer-display 'new-frame))
7758 (not arg))
7759 (kill-buffer org-last-indirect-buffer))
7760 (setq ibuf (org-get-indirect-buffer cbuf heading)
7761 org-last-indirect-buffer ibuf)
7762 (cond
7763 ((or (eq org-indirect-buffer-display 'new-frame)
7764 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7765 (select-frame (make-frame))
7766 (delete-other-windows)
7767 (pop-to-buffer-same-window ibuf)
7768 (org-set-frame-title heading))
7769 ((eq org-indirect-buffer-display 'dedicated-frame)
7770 (raise-frame
7771 (select-frame (or (and org-indirect-dedicated-frame
7772 (frame-live-p org-indirect-dedicated-frame)
7773 org-indirect-dedicated-frame)
7774 (setq org-indirect-dedicated-frame (make-frame)))))
7775 (delete-other-windows)
7776 (pop-to-buffer-same-window ibuf)
7777 (org-set-frame-title (concat "Indirect: " heading)))
7778 ((eq org-indirect-buffer-display 'current-window)
7779 (pop-to-buffer-same-window ibuf))
7780 ((eq org-indirect-buffer-display 'other-window)
7781 (pop-to-buffer ibuf))
7782 (t (error "Invalid value")))
7783 (narrow-to-region beg end)
7784 (outline-show-all)
7785 (goto-char pos)
7786 (run-hook-with-args 'org-cycle-hook 'all)
7787 (and (window-live-p cwin) (select-window cwin))))
7789 (defun org-get-indirect-buffer (&optional buffer heading)
7790 (setq buffer (or buffer (current-buffer)))
7791 (let ((n 1) (base (buffer-name buffer)) bname)
7792 (while (buffer-live-p
7793 (get-buffer
7794 (setq bname
7795 (concat base "-"
7796 (if heading (concat heading "-" (number-to-string n))
7797 (number-to-string n))))))
7798 (setq n (1+ n)))
7799 (condition-case nil
7800 (make-indirect-buffer buffer bname 'clone)
7801 (error (make-indirect-buffer buffer bname)))))
7803 (defun org-set-frame-title (title)
7804 "Set the title of the current frame to the string TITLE."
7805 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7807 ;;;; Structure editing
7809 ;;; Inserting headlines
7811 (defun org--line-empty-p (n)
7812 "Is the Nth next line empty?
7814 Counts the current line as N = 1 and the previous line as N = 0;
7815 see `beginning-of-line'."
7816 (save-excursion
7817 (and (not (bobp))
7818 (or (beginning-of-line n) t)
7819 (save-match-data
7820 (looking-at "[ \t]*$")))))
7822 (defun org-previous-line-empty-p ()
7823 "Is the previous line a blank line?
7824 When NEXT is non-nil, check the next line instead."
7825 (org--line-empty-p 0))
7827 (defun org-next-line-empty-p ()
7828 "Is the previous line a blank line?
7829 When NEXT is non-nil, check the next line instead."
7830 (org--line-empty-p 2))
7832 (defun org-insert-heading (&optional arg invisible-ok top)
7833 "Insert a new heading or an item with the same depth at point.
7835 If point is at the beginning of a heading or a list item, insert
7836 a new heading or a new item above the current one. When at the
7837 beginning of a regular line of text, turn it into a heading.
7839 If point is in the middle of a line, split it and create a new
7840 headline/item with the text in the current line after point (see
7841 `org-M-RET-may-split-line' on how to modify this behavior). As
7842 a special case, on a headline, splitting can only happen on the
7843 title itself. E.g., this excludes breaking stars or tags.
7845 With a `\\[universal-argument]' prefix, set \
7846 `org-insert-heading-respect-content' to
7847 a non-nil value for the duration of the command. This forces the
7848 insertion of a heading after the current subtree, independently
7849 on the location of point.
7851 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7852 insert the heading at the end of the tree
7853 above the current heading. For example, if point is within a
7854 2nd-level heading, then it will insert a 2nd-level heading at
7855 the end of the 1st-level parent subtree.
7857 When INVISIBLE-OK is set, stop at invisible headlines when going
7858 back. This is important for non-interactive uses of the
7859 command.
7861 When optional argument TOP is non-nil, insert a level 1 heading,
7862 unconditionally."
7863 (interactive "P")
7864 (let ((itemp (and (not top) (org-in-item-p)))
7865 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7866 (respect-content (or org-insert-heading-respect-content
7867 (equal arg '(4))))
7868 (initial-content ""))
7870 (cond
7872 ((or (= (buffer-size) 0)
7873 (and (not (save-excursion
7874 (and (ignore-errors (org-back-to-heading invisible-ok))
7875 (org-at-heading-p))))
7876 (or arg (not itemp))))
7877 ;; At beginning of buffer or so high up that only a heading
7878 ;; makes sense.
7879 (cond ((and (bolp) (not respect-content)) (insert "* "))
7880 ((not respect-content)
7881 (unless may-split (end-of-line))
7882 (insert "\n* "))
7883 ((re-search-forward org-outline-regexp-bol nil t)
7884 (beginning-of-line)
7885 (insert "* \n")
7886 (backward-char))
7887 (t (goto-char (point-max))
7888 (insert "\n* ")))
7889 (run-hooks 'org-insert-heading-hook))
7891 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7894 ;; Maybe move at the end of the subtree
7895 (when (equal arg '(16))
7896 (org-up-heading-safe)
7897 (org-end-of-subtree t))
7898 ;; Insert a heading
7899 (save-restriction
7900 (widen)
7901 (let* ((level nil)
7902 (on-heading (org-at-heading-p))
7903 (empty-line-p (if on-heading
7904 (org-previous-line-empty-p)
7905 ;; We will decide later
7906 nil))
7907 ;; Get a level string to fall back on.
7908 (fix-level
7909 (if (org-before-first-heading-p) "*"
7910 (save-excursion
7911 (org-back-to-heading t)
7912 (when (org-previous-line-empty-p) (setq empty-line-p t))
7913 (looking-at org-outline-regexp)
7914 (make-string (1- (length (match-string 0))) ?*))))
7915 (stars
7916 (save-excursion
7917 (condition-case nil
7918 (if top "* "
7919 (org-back-to-heading invisible-ok)
7920 (when (and (not on-heading)
7921 (featurep 'org-inlinetask)
7922 (integerp org-inlinetask-min-level)
7923 (>= (length (match-string 0))
7924 org-inlinetask-min-level))
7925 ;; Find a heading level before the inline
7926 ;; task.
7927 (while (and (setq level (org-up-heading-safe))
7928 (>= level org-inlinetask-min-level)))
7929 (if (org-at-heading-p)
7930 (org-back-to-heading invisible-ok)
7931 (error "This should not happen")))
7932 (unless (and (save-excursion
7933 (save-match-data
7934 (org-backward-heading-same-level
7935 1 invisible-ok))
7936 (= (point) (match-beginning 0)))
7937 (not (org-next-line-empty-p)))
7938 (setq empty-line-p (or empty-line-p
7939 (org-previous-line-empty-p))))
7940 (match-string 0))
7941 (error (or fix-level "* ")))))
7942 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7943 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7945 ;; If we insert after content, move there and clean up
7946 ;; whitespace.
7947 (when respect-content
7948 (if (not (org-before-first-heading-p))
7949 (org-end-of-subtree nil t)
7950 (re-search-forward org-outline-regexp-bol)
7951 (beginning-of-line 0))
7952 (skip-chars-backward " \r\t\n")
7953 (and (not (looking-back "^\\*+" (line-beginning-position)))
7954 (looking-at "[ \t]+") (replace-match ""))
7955 (unless (eobp) (forward-char 1))
7956 (when (looking-at "^\\*")
7957 (unless (bobp) (backward-char 1))
7958 (insert "\n")))
7960 ;; If we are splitting, grab the text that should be moved
7961 ;; to the new headline.
7962 (when may-split
7963 (if (org-at-heading-p)
7964 ;; This is a heading: split intelligently (keeping
7965 ;; tags).
7966 (let ((pos (point)))
7967 (beginning-of-line)
7968 (let ((case-fold-search nil))
7969 (unless (looking-at org-complex-heading-regexp)
7970 (error "This should not happen")))
7971 (when (and (match-beginning 4)
7972 (> pos (match-beginning 4))
7973 (< pos (match-end 4)))
7974 (setq initial-content (buffer-substring pos (match-end 4)))
7975 (goto-char pos)
7976 (delete-region (point) (match-end 4))
7977 (if (looking-at "[ \t]*$")
7978 (replace-match "")
7979 (insert (make-string (length initial-content) ?\s)))
7980 (setq initial-content (org-trim initial-content)))
7981 (goto-char pos))
7982 ;; A normal line.
7983 (setq initial-content
7984 (org-trim
7985 (delete-and-extract-region (point) (line-end-position))))))
7987 ;; If we are at the beginning of the line, insert before it.
7988 ;; Otherwise, after it.
7989 (cond
7990 ((and (bolp) (looking-at "[ \t]*$")))
7991 ((bolp) (save-excursion (insert "\n")))
7992 (t (end-of-line)
7993 (insert "\n")))
7995 ;; Insert the new heading
7996 (insert stars)
7997 (just-one-space)
7998 (insert initial-content)
7999 (unless (and blank (org-previous-line-empty-p))
8000 (org-N-empty-lines-before-current (if blank 1 0)))
8001 ;; Adjust visibility, which may be messed up if we removed
8002 ;; blank lines while previous entry was hidden.
8003 (let ((bol (line-beginning-position)))
8004 (dolist (o (overlays-at (1- bol)))
8005 (when (and (eq (overlay-get o 'invisible) 'outline)
8006 (eq (overlay-end o) bol))
8007 (move-overlay o (overlay-start o) (1- bol)))))
8008 (run-hooks 'org-insert-heading-hook)))))))
8010 (defun org-N-empty-lines-before-current (N)
8011 "Make the number of empty lines before current exactly N.
8012 So this will delete or add empty lines."
8013 (save-excursion
8014 (beginning-of-line)
8015 (let ((p (point)))
8016 (skip-chars-backward " \r\t\n")
8017 (unless (bolp) (forward-line))
8018 (delete-region (point) p))
8019 (when (> N 0) (insert (make-string N ?\n)))))
8021 (defun org-get-heading (&optional no-tags no-todo)
8022 "Return the heading of the current entry, without the stars.
8023 When NO-TAGS is non-nil, don't include tags.
8024 When NO-TODO is non-nil, don't include TODO keywords."
8025 (save-excursion
8026 (org-back-to-heading t)
8027 (let ((case-fold-search nil))
8028 (cond
8029 ((and no-tags no-todo)
8030 (looking-at org-complex-heading-regexp)
8031 ;; Return value has to be a string, but match group 4 is
8032 ;; optional.
8033 (or (match-string 4) ""))
8034 (no-tags
8035 (looking-at (concat org-outline-regexp
8036 "\\(.*?\\)"
8037 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8038 (match-string 1))
8039 (no-todo
8040 (looking-at org-todo-line-regexp)
8041 (match-string 3))
8042 (t (looking-at org-heading-regexp)
8043 (match-string 2))))))
8045 (defvar orgstruct-mode) ; defined below
8047 (defun org-heading-components ()
8048 "Return the components of the current heading.
8049 This is a list with the following elements:
8050 - the level as an integer
8051 - the reduced level, different if `org-odd-levels-only' is set.
8052 - the TODO keyword, or nil
8053 - the priority character, like ?A, or nil if no priority is given
8054 - the headline text itself, or the tags string if no headline text
8055 - the tags string, or nil."
8056 (save-excursion
8057 (org-back-to-heading t)
8058 (when (let (case-fold-search)
8059 (looking-at
8060 (if orgstruct-mode
8061 org-heading-regexp
8062 org-complex-heading-regexp)))
8063 (if orgstruct-mode
8064 (list (length (match-string 1))
8065 (org-reduced-level (length (match-string 1)))
8068 (match-string 2)
8069 nil)
8070 (list (length (match-string 1))
8071 (org-reduced-level (length (match-string 1)))
8072 (match-string-no-properties 2)
8073 (and (match-end 3) (aref (match-string 3) 2))
8074 (match-string-no-properties 4)
8075 (match-string-no-properties 5))))))
8077 (defun org-get-entry ()
8078 "Get the entry text, after heading, entire subtree."
8079 (save-excursion
8080 (org-back-to-heading t)
8081 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8083 (defun org-edit-headline (&optional heading)
8084 "Edit the current headline.
8085 Set it to HEADING when provided."
8086 (interactive)
8087 (org-with-wide-buffer
8088 (org-back-to-heading t)
8089 (let ((case-fold-search nil))
8090 (when (looking-at org-complex-heading-regexp)
8091 (let* ((old (match-string-no-properties 4))
8092 (new (save-match-data
8093 (org-trim (or heading (read-string "Edit: " old))))))
8094 (unless (equal old new)
8095 (if old (replace-match new t t nil 4)
8096 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8097 (insert " " new))
8098 (org-set-tags nil t)
8099 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8101 (defun org-insert-heading-after-current ()
8102 "Insert a new heading with same level as current, after current subtree."
8103 (interactive)
8104 (org-back-to-heading)
8105 (org-insert-heading)
8106 (org-move-subtree-down)
8107 (end-of-line 1))
8109 (defun org-insert-heading-respect-content (&optional invisible-ok)
8110 "Insert heading with `org-insert-heading-respect-content' set to t."
8111 (interactive)
8112 (org-insert-heading '(4) invisible-ok))
8114 (defun org-insert-todo-heading-respect-content (&optional force-state)
8115 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8116 (interactive)
8117 (org-insert-todo-heading force-state '(4)))
8119 (defun org-insert-todo-heading (arg &optional force-heading)
8120 "Insert a new heading with the same level and TODO state as current heading.
8122 If the heading has no TODO state, or if the state is DONE, use
8123 the first state (TODO by default). Also with one prefix arg,
8124 force first state. With two prefix args, force inserting at the
8125 end of the parent subtree.
8127 When called at a plain list item, insert a new item with an
8128 unchecked check box."
8129 (interactive "P")
8130 (when (or force-heading (not (org-insert-item 'checkbox)))
8131 (org-insert-heading (or (and (equal arg '(16)) '(16))
8132 force-heading))
8133 (save-excursion
8134 (org-back-to-heading)
8135 (outline-previous-heading)
8136 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8137 (let* ((new-mark-x
8138 (if (or (equal arg '(4))
8139 (not (match-beginning 2))
8140 (member (match-string 2) org-done-keywords))
8141 (car org-todo-keywords-1)
8142 (match-string 2)))
8143 (new-mark
8145 (run-hook-with-args-until-success
8146 'org-todo-get-default-hook new-mark-x nil)
8147 new-mark-x)))
8148 (beginning-of-line 1)
8149 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8150 (if org-treat-insert-todo-heading-as-state-change
8151 (org-todo new-mark)
8152 (insert new-mark " "))))
8153 (when org-provide-todo-statistics
8154 (org-update-parent-todo-statistics))))
8156 (defun org-insert-subheading (arg)
8157 "Insert a new subheading and demote it.
8158 Works for outline headings and for plain lists alike."
8159 (interactive "P")
8160 (org-insert-heading arg)
8161 (cond
8162 ((org-at-heading-p) (org-do-demote))
8163 ((org-at-item-p) (org-indent-item))))
8165 (defun org-insert-todo-subheading (arg)
8166 "Insert a new subheading with TODO keyword or checkbox and demote it.
8167 Works for outline headings and for plain lists alike."
8168 (interactive "P")
8169 (org-insert-todo-heading arg)
8170 (cond
8171 ((org-at-heading-p) (org-do-demote))
8172 ((org-at-item-p) (org-indent-item))))
8174 ;;; Promotion and Demotion
8176 (defvar org-after-demote-entry-hook nil
8177 "Hook run after an entry has been demoted.
8178 The cursor will be at the beginning of the entry.
8179 When a subtree is being demoted, the hook will be called for each node.")
8181 (defvar org-after-promote-entry-hook nil
8182 "Hook run after an entry has been promoted.
8183 The cursor will be at the beginning of the entry.
8184 When a subtree is being promoted, the hook will be called for each node.")
8186 (defun org-promote-subtree ()
8187 "Promote the entire subtree.
8188 See also `org-promote'."
8189 (interactive)
8190 (save-excursion
8191 (org-with-limited-levels (org-map-tree 'org-promote)))
8192 (org-fix-position-after-promote))
8194 (defun org-demote-subtree ()
8195 "Demote the entire subtree.
8196 See `org-demote' and `org-promote'."
8197 (interactive)
8198 (save-excursion
8199 (org-with-limited-levels (org-map-tree 'org-demote)))
8200 (org-fix-position-after-promote))
8202 (defun org-do-promote ()
8203 "Promote the current heading higher up the tree.
8204 If the region is active in `transient-mark-mode', promote all
8205 headings in the region."
8206 (interactive)
8207 (save-excursion
8208 (if (org-region-active-p)
8209 (org-map-region 'org-promote (region-beginning) (region-end))
8210 (org-promote)))
8211 (org-fix-position-after-promote))
8213 (defun org-do-demote ()
8214 "Demote the current heading lower down the tree.
8215 If the region is active in `transient-mark-mode', demote all
8216 headings in the region."
8217 (interactive)
8218 (save-excursion
8219 (if (org-region-active-p)
8220 (org-map-region 'org-demote (region-beginning) (region-end))
8221 (org-demote)))
8222 (org-fix-position-after-promote))
8224 (defun org-fix-position-after-promote ()
8225 "Fix cursor position and indentation after demoting/promoting."
8226 (let ((pos (point)))
8227 (when (save-excursion
8228 (beginning-of-line)
8229 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8230 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8231 (cond ((eobp) (insert " "))
8232 ((eolp) (insert " "))
8233 ((equal (char-after) ?\s) (forward-char 1))))))
8235 (defun org-current-level ()
8236 "Return the level of the current entry, or nil if before the first headline.
8237 The level is the number of stars at the beginning of the
8238 headline. Use `org-reduced-level' to remove the effect of
8239 `org-odd-levels'. Unlike to `org-outline-level', this function
8240 ignores inlinetasks."
8241 (let ((level (org-with-limited-levels (org-outline-level))))
8242 (and (> level 0) level)))
8244 (defun org-get-previous-line-level ()
8245 "Return the outline depth of the last headline before the current line.
8246 Returns 0 for the first headline in the buffer, and nil if before the
8247 first headline."
8248 (and (org-current-level)
8249 (or (and (/= (line-beginning-position) (point-min))
8250 (save-excursion (beginning-of-line 0) (org-current-level)))
8251 0)))
8253 (defun org-reduced-level (l)
8254 "Compute the effective level of a heading.
8255 This takes into account the setting of `org-odd-levels-only'."
8256 (cond
8257 ((zerop l) 0)
8258 (org-odd-levels-only (1+ (floor (/ l 2))))
8259 (t l)))
8261 (defun org-level-increment ()
8262 "Return the number of stars that will be added or removed at a
8263 time to headlines when structure editing, based on the value of
8264 `org-odd-levels-only'."
8265 (if org-odd-levels-only 2 1))
8267 (defun org-get-valid-level (level &optional change)
8268 "Rectify a level change under the influence of `org-odd-levels-only'
8269 LEVEL is a current level, CHANGE is by how much the level should be
8270 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8271 even level numbers will become the next higher odd number."
8272 (if org-odd-levels-only
8273 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8274 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8275 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8276 (max 1 (+ level (or change 0)))))
8278 (defun org-promote ()
8279 "Promote the current heading higher up the tree."
8280 (org-with-wide-buffer
8281 (org-back-to-heading t)
8282 (let* ((after-change-functions (remq 'flyspell-after-change-function
8283 after-change-functions))
8284 (level (save-match-data (funcall outline-level)))
8285 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8286 (diff (abs (- level (length up-head) -1))))
8287 (cond
8288 ((and (= level 1) org-allow-promoting-top-level-subtree)
8289 (replace-match "# " nil t))
8290 ((= level 1)
8291 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8292 (t (replace-match up-head nil t)))
8293 (unless (= level 1)
8294 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8295 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8296 (run-hooks 'org-after-promote-entry-hook))))
8298 (defun org-demote ()
8299 "Demote the current heading lower down the tree."
8300 (org-with-wide-buffer
8301 (org-back-to-heading t)
8302 (let* ((after-change-functions (remq 'flyspell-after-change-function
8303 after-change-functions))
8304 (level (save-match-data (funcall outline-level)))
8305 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8306 (diff (abs (- level (length down-head) -1))))
8307 (replace-match down-head nil t)
8308 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8309 (when org-adapt-indentation (org-fixup-indentation diff))
8310 (run-hooks 'org-after-demote-entry-hook))))
8312 (defun org-cycle-level ()
8313 "Cycle the level of an empty headline through possible states.
8314 This goes first to child, then to parent, level, then up the hierarchy.
8315 After top level, it switches back to sibling level."
8316 (interactive)
8317 (let ((org-adapt-indentation nil))
8318 (when (org-point-at-end-of-empty-headline)
8319 (setq this-command 'org-cycle-level) ; Only needed for caching
8320 (let ((cur-level (org-current-level))
8321 (prev-level (org-get-previous-line-level)))
8322 (cond
8323 ;; If first headline in file, promote to top-level.
8324 ((= prev-level 0)
8325 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8326 do (org-do-promote)))
8327 ;; If same level as prev, demote one.
8328 ((= prev-level cur-level)
8329 (org-do-demote))
8330 ;; If parent is top-level, promote to top level if not already.
8331 ((= prev-level 1)
8332 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8333 do (org-do-promote)))
8334 ;; If top-level, return to prev-level.
8335 ((= cur-level 1)
8336 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8337 do (org-do-demote)))
8338 ;; If less than prev-level, promote one.
8339 ((< cur-level prev-level)
8340 (org-do-promote))
8341 ;; If deeper than prev-level, promote until higher than
8342 ;; prev-level.
8343 ((> cur-level prev-level)
8344 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8345 do (org-do-promote))))
8346 t))))
8348 (defun org-map-tree (fun)
8349 "Call FUN for every heading underneath the current one."
8350 (org-back-to-heading t)
8351 (let ((level (funcall outline-level)))
8352 (save-excursion
8353 (funcall fun)
8354 (while (and (progn
8355 (outline-next-heading)
8356 (> (funcall outline-level) level))
8357 (not (eobp)))
8358 (funcall fun)))))
8360 (defun org-map-region (fun beg end)
8361 "Call FUN for every heading between BEG and END."
8362 (let ((org-ignore-region t))
8363 (save-excursion
8364 (setq end (copy-marker end))
8365 (goto-char beg)
8366 (when (and (re-search-forward org-outline-regexp-bol nil t)
8367 (< (point) end))
8368 (funcall fun))
8369 (while (and (progn
8370 (outline-next-heading)
8371 (< (point) end))
8372 (not (eobp)))
8373 (funcall fun)))))
8375 (defun org-fixup-indentation (diff)
8376 "Change the indentation in the current entry by DIFF.
8378 DIFF is an integer. Indentation is done according to the
8379 following rules:
8381 - Planning information and property drawers are always indented
8382 according to the new level of the headline;
8384 - Footnote definitions and their contents are ignored;
8386 - Inlinetasks' boundaries are not shifted;
8388 - Empty lines are ignored;
8390 - Other lines' indentation are shifted by DIFF columns, unless
8391 it would introduce a structural change in the document, in
8392 which case no shifting is done at all.
8394 Assume point is at a heading or an inlinetask beginning."
8395 (org-with-wide-buffer
8396 (narrow-to-region (line-beginning-position)
8397 (save-excursion
8398 (if (org-with-limited-levels (org-at-heading-p))
8399 (org-with-limited-levels (outline-next-heading))
8400 (org-inlinetask-goto-end))
8401 (point)))
8402 (forward-line)
8403 ;; Indent properly planning info and property drawer.
8404 (when (looking-at-p org-planning-line-re)
8405 (org-indent-line)
8406 (forward-line))
8407 (when (looking-at org-property-drawer-re)
8408 (goto-char (match-end 0))
8409 (forward-line)
8410 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8411 (catch 'no-shift
8412 (when (zerop diff) (throw 'no-shift nil))
8413 ;; If DIFF is negative, first check if a shift is possible at all
8414 ;; (e.g., it doesn't break structure). This can only happen if
8415 ;; some contents are not properly indented.
8416 (let ((case-fold-search t))
8417 (when (< diff 0)
8418 (let ((diff (- diff))
8419 (forbidden-re (concat org-outline-regexp
8420 "\\|"
8421 (substring org-footnote-definition-re 1))))
8422 (save-excursion
8423 (while (not (eobp))
8424 (cond
8425 ((looking-at-p "[ \t]*$") (forward-line))
8426 ((and (looking-at-p org-footnote-definition-re)
8427 (let ((e (org-element-at-point)))
8428 (and (eq (org-element-type e) 'footnote-definition)
8429 (goto-char (org-element-property :end e))))))
8430 ((looking-at-p org-outline-regexp) (forward-line))
8431 ;; Give up if shifting would move before column 0 or
8432 ;; if it would introduce a headline or a footnote
8433 ;; definition.
8435 (skip-chars-forward " \t")
8436 (let ((ind (current-column)))
8437 (when (or (< ind diff)
8438 (and (= ind diff) (looking-at-p forbidden-re)))
8439 (throw 'no-shift nil)))
8440 ;; Ignore contents of example blocks and source
8441 ;; blocks if their indentation is meant to be
8442 ;; preserved. Jump to block's closing line.
8443 (beginning-of-line)
8444 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8445 (let ((e (org-element-at-point)))
8446 (and (memq (org-element-type e)
8447 '(example-block src-block))
8448 (or org-src-preserve-indentation
8449 (org-element-property :preserve-indent e))
8450 (goto-char (org-element-property :end e))
8451 (progn (skip-chars-backward " \r\t\n")
8452 (beginning-of-line)
8453 t))))
8454 (forward-line))))))))
8455 ;; Shift lines but footnote definitions, inlinetasks boundaries
8456 ;; by DIFF. Also skip contents of source or example blocks
8457 ;; when indentation is meant to be preserved.
8458 (while (not (eobp))
8459 (cond
8460 ((and (looking-at-p org-footnote-definition-re)
8461 (let ((e (org-element-at-point)))
8462 (and (eq (org-element-type e) 'footnote-definition)
8463 (goto-char (org-element-property :end e))))))
8464 ((looking-at-p org-outline-regexp) (forward-line))
8465 ((looking-at-p "[ \t]*$") (forward-line))
8467 (indent-line-to (+ (org-get-indentation) diff))
8468 (beginning-of-line)
8469 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8470 (let ((e (org-element-at-point)))
8471 (and (memq (org-element-type e)
8472 '(example-block src-block))
8473 (or org-src-preserve-indentation
8474 (org-element-property :preserve-indent e))
8475 (goto-char (org-element-property :end e))
8476 (progn (skip-chars-backward " \r\t\n")
8477 (beginning-of-line)
8478 t))))
8479 (forward-line)))))))))
8481 (defun org-convert-to-odd-levels ()
8482 "Convert an Org file with all levels allowed to one with odd levels.
8483 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8484 level 5 etc."
8485 (interactive)
8486 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8487 (let ((outline-level 'org-outline-level)
8488 (org-odd-levels-only nil) n)
8489 (save-excursion
8490 (goto-char (point-min))
8491 (while (re-search-forward "^\\*\\*+ " nil t)
8492 (setq n (- (length (match-string 0)) 2))
8493 (while (>= (setq n (1- n)) 0)
8494 (org-demote))
8495 (end-of-line 1))))))
8497 (defun org-convert-to-oddeven-levels ()
8498 "Convert an Org file with only odd levels to one with odd/even levels.
8499 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8500 file contains a section with an even level, conversion would
8501 destroy the structure of the file. An error is signaled in this
8502 case."
8503 (interactive)
8504 (goto-char (point-min))
8505 ;; First check if there are no even levels
8506 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8507 (org-show-set-visibility 'canonical)
8508 (error "Not all levels are odd in this file. Conversion not possible"))
8509 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8510 (let ((outline-regexp org-outline-regexp)
8511 (outline-level 'org-outline-level)
8512 (org-odd-levels-only nil) n)
8513 (save-excursion
8514 (goto-char (point-min))
8515 (while (re-search-forward "^\\*\\*+ " nil t)
8516 (setq n (/ (1- (length (match-string 0))) 2))
8517 (while (>= (setq n (1- n)) 0)
8518 (org-promote))
8519 (end-of-line 1))))))
8521 (defun org-tr-level (n)
8522 "Make N odd if required."
8523 (if org-odd-levels-only (1+ (/ n 2)) n))
8525 ;;; Vertical tree motion, cutting and pasting of subtrees
8527 (defun org-move-subtree-up (&optional arg)
8528 "Move the current subtree up past ARG headlines of the same level."
8529 (interactive "p")
8530 (org-move-subtree-down (- (prefix-numeric-value arg))))
8532 (defun org-move-subtree-down (&optional arg)
8533 "Move the current subtree down past ARG headlines of the same level."
8534 (interactive "p")
8535 (setq arg (prefix-numeric-value arg))
8536 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8537 'org-get-last-sibling))
8538 (ins-point (make-marker))
8539 (cnt (abs arg))
8540 (col (current-column))
8541 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8542 ;; Select the tree
8543 (org-back-to-heading)
8544 (setq beg0 (point))
8545 (save-excursion
8546 (setq ne-beg (org-back-over-empty-lines))
8547 (setq beg (point)))
8548 (save-match-data
8549 (save-excursion (outline-end-of-heading)
8550 (setq folded (org-invisible-p)))
8551 (progn (org-end-of-subtree nil t)
8552 (unless (eobp) (backward-char))))
8553 (outline-next-heading)
8554 (setq ne-end (org-back-over-empty-lines))
8555 (setq end (point))
8556 (goto-char beg0)
8557 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8558 ;; include less whitespace
8559 (save-excursion
8560 (goto-char beg)
8561 (forward-line (- ne-beg ne-end))
8562 (setq beg (point))))
8563 ;; Find insertion point, with error handling
8564 (while (> cnt 0)
8565 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8566 (progn (goto-char beg0)
8567 (user-error "Cannot move past superior level or buffer limit")))
8568 (setq cnt (1- cnt)))
8569 (when (> arg 0)
8570 ;; Moving forward - still need to move over subtree
8571 (org-end-of-subtree t t)
8572 (save-excursion
8573 (org-back-over-empty-lines)
8574 (or (bolp) (newline))))
8575 (setq ne-ins (org-back-over-empty-lines))
8576 (move-marker ins-point (point))
8577 (setq txt (buffer-substring beg end))
8578 (org-save-markers-in-region beg end)
8579 (delete-region beg end)
8580 (org-remove-empty-overlays-at beg)
8581 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8582 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8583 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8584 (let ((bbb (point)))
8585 (insert-before-markers txt)
8586 (org-reinstall-markers-in-region bbb)
8587 (move-marker ins-point bbb))
8588 (or (bolp) (insert "\n"))
8589 (setq ins-end (point))
8590 (goto-char ins-point)
8591 (org-skip-whitespace)
8592 (when (and (< arg 0)
8593 (org-first-sibling-p)
8594 (> ne-ins ne-beg))
8595 ;; Move whitespace back to beginning
8596 (save-excursion
8597 (goto-char ins-end)
8598 (let ((kill-whole-line t))
8599 (kill-line (- ne-ins ne-beg)) (point)))
8600 (insert (make-string (- ne-ins ne-beg) ?\n)))
8601 (move-marker ins-point nil)
8602 (if folded
8603 (outline-hide-subtree)
8604 (org-show-entry)
8605 (org-show-children)
8606 (org-cycle-hide-drawers 'children))
8607 (org-clean-visibility-after-subtree-move)
8608 ;; move back to the initial column we were at
8609 (move-to-column col)))
8611 (defvar org-subtree-clip ""
8612 "Clipboard for cut and paste of subtrees.
8613 This is actually only a copy of the kill, because we use the normal kill
8614 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8616 (defvar org-subtree-clip-folded nil
8617 "Was the last copied subtree folded?
8618 This is used to fold the tree back after pasting.")
8620 (defun org-cut-subtree (&optional n)
8621 "Cut the current subtree into the clipboard.
8622 With prefix arg N, cut this many sequential subtrees.
8623 This is a short-hand for marking the subtree and then cutting it."
8624 (interactive "p")
8625 (org-copy-subtree n 'cut))
8627 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8628 "Copy the current subtree it in the clipboard.
8629 With prefix arg N, copy this many sequential subtrees.
8630 This is a short-hand for marking the subtree and then copying it.
8631 If CUT is non-nil, actually cut the subtree.
8632 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8633 of some markers in the region, even if CUT is non-nil. This is
8634 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8635 (interactive "p")
8636 (let (beg end folded (beg0 (point)))
8637 (if (called-interactively-p 'any)
8638 (org-back-to-heading nil) ; take what looks like a subtree
8639 (org-back-to-heading t)) ; take what is really there
8640 (setq beg (point))
8641 (skip-chars-forward " \t\r\n")
8642 (save-match-data
8643 (if nosubtrees
8644 (outline-next-heading)
8645 (save-excursion (outline-end-of-heading)
8646 (setq folded (org-invisible-p)))
8647 (ignore-errors (org-forward-heading-same-level (1- n) t))
8648 (org-end-of-subtree t t)))
8649 ;; Include the end of an inlinetask
8650 (when (and (featurep 'org-inlinetask)
8651 (looking-at-p (concat (org-inlinetask-outline-regexp)
8652 "END[ \t]*$")))
8653 (end-of-line))
8654 (setq end (point))
8655 (goto-char beg0)
8656 (when (> end beg)
8657 (setq org-subtree-clip-folded folded)
8658 (when (or cut force-store-markers)
8659 (org-save-markers-in-region beg end))
8660 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8661 (setq org-subtree-clip (current-kill 0))
8662 (message "%s: Subtree(s) with %d characters"
8663 (if cut "Cut" "Copied")
8664 (length org-subtree-clip)))))
8666 (defun org-paste-subtree (&optional level tree for-yank remove)
8667 "Paste the clipboard as a subtree, with modification of headline level.
8668 The entire subtree is promoted or demoted in order to match a new headline
8669 level.
8671 If the cursor is at the beginning of a headline, the same level as
8672 that headline is used to paste the tree.
8674 If not, the new level is derived from the *visible* headings
8675 before and after the insertion point, and taken to be the inferior headline
8676 level of the two. So if the previous visible heading is level 3 and the
8677 next is level 4 (or vice versa), level 4 will be used for insertion.
8678 This makes sure that the subtree remains an independent subtree and does
8679 not swallow low level entries.
8681 You can also force a different level, either by using a numeric prefix
8682 argument, or by inserting the heading marker by hand. For example, if the
8683 cursor is after \"*****\", then the tree will be shifted to level 5.
8685 If optional TREE is given, use this text instead of the kill ring.
8687 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8688 move back over whitespace before inserting, and move point to the end of
8689 the inserted text when done.
8691 When REMOVE is non-nil, remove the subtree from the clipboard."
8692 (interactive "P")
8693 (setq tree (or tree (and kill-ring (current-kill 0))))
8694 (unless (org-kill-is-subtree-p tree)
8695 (user-error "%s"
8696 (substitute-command-keys
8697 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8698 (org-with-limited-levels
8699 (let* ((visp (not (org-invisible-p)))
8700 (txt tree)
8701 (^re_ "\\(\\*+\\)[ \t]*")
8702 (old-level (if (string-match org-outline-regexp-bol txt)
8703 (- (match-end 0) (match-beginning 0) 1)
8704 -1))
8705 (force-level (cond (level (prefix-numeric-value level))
8706 ((and (looking-at "[ \t]*$")
8707 (string-match
8708 "^\\*+$" (buffer-substring
8709 (point-at-bol) (point))))
8710 (- (match-end 0) (match-beginning 0)))
8711 ((and (bolp)
8712 (looking-at org-outline-regexp))
8713 (- (match-end 0) (point) 1))))
8714 (previous-level (save-excursion
8715 (condition-case nil
8716 (progn
8717 (outline-previous-visible-heading 1)
8718 (if (looking-at ^re_)
8719 (- (match-end 0) (match-beginning 0) 1)
8721 (error 1))))
8722 (next-level (save-excursion
8723 (condition-case nil
8724 (progn
8725 (or (looking-at org-outline-regexp)
8726 (outline-next-visible-heading 1))
8727 (if (looking-at ^re_)
8728 (- (match-end 0) (match-beginning 0) 1)
8730 (error 1))))
8731 (new-level (or force-level (max previous-level next-level)))
8732 (shift (if (or (= old-level -1)
8733 (= new-level -1)
8734 (= old-level new-level))
8736 (- new-level old-level)))
8737 (delta (if (> shift 0) -1 1))
8738 (func (if (> shift 0) 'org-demote 'org-promote))
8739 (org-odd-levels-only nil)
8740 beg end newend)
8741 ;; Remove the forced level indicator
8742 (when force-level
8743 (delete-region (point-at-bol) (point)))
8744 ;; Paste
8745 (beginning-of-line (if (bolp) 1 2))
8746 (setq beg (point))
8747 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8748 (insert-before-markers txt)
8749 (unless (string-suffix-p "\n" txt) (insert "\n"))
8750 (setq newend (point))
8751 (org-reinstall-markers-in-region beg)
8752 (setq end (point))
8753 (goto-char beg)
8754 (skip-chars-forward " \t\n\r")
8755 (setq beg (point))
8756 (when (and (org-invisible-p) visp)
8757 (save-excursion (outline-show-heading)))
8758 ;; Shift if necessary
8759 (unless (= shift 0)
8760 (save-restriction
8761 (narrow-to-region beg end)
8762 (while (not (= shift 0))
8763 (org-map-region func (point-min) (point-max))
8764 (setq shift (+ delta shift)))
8765 (goto-char (point-min))
8766 (setq newend (point-max))))
8767 (when (or (called-interactively-p 'interactive) for-yank)
8768 (message "Clipboard pasted as level %d subtree" new-level))
8769 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8770 kill-ring
8771 (eq org-subtree-clip (current-kill 0))
8772 org-subtree-clip-folded)
8773 ;; The tree was folded before it was killed/copied
8774 (outline-hide-subtree))
8775 (and for-yank (goto-char newend))
8776 (and remove (setq kill-ring (cdr kill-ring))))))
8778 (defun org-kill-is-subtree-p (&optional txt)
8779 "Check if the current kill is an outline subtree, or a set of trees.
8780 Returns nil if kill does not start with a headline, or if the first
8781 headline level is not the largest headline level in the tree.
8782 So this will actually accept several entries of equal levels as well,
8783 which is OK for `org-paste-subtree'.
8784 If optional TXT is given, check this string instead of the current kill."
8785 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8786 (re (org-get-limited-outline-regexp))
8787 (^re (concat "^" re))
8788 (start-level (and kill
8789 (string-match
8790 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8791 kill)
8792 (- (match-end 2) (match-beginning 2) 1)))
8793 (start (1+ (or (match-beginning 2) -1))))
8794 (if (not start-level)
8795 (progn
8796 nil) ;; does not even start with a heading
8797 (catch 'exit
8798 (while (setq start (string-match ^re kill (1+ start)))
8799 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8800 (throw 'exit nil)))
8801 t))))
8803 (defvar org-markers-to-move nil
8804 "Markers that should be moved with a cut-and-paste operation.
8805 Those markers are stored together with their positions relative to
8806 the start of the region.")
8808 (defun org-save-markers-in-region (beg end)
8809 "Check markers in region.
8810 If these markers are between BEG and END, record their position relative
8811 to BEG, so that after moving the block of text, we can put the markers back
8812 into place.
8813 This function gets called just before an entry or tree gets cut from the
8814 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8815 called immediately, to move the markers with the entries."
8816 (setq org-markers-to-move nil)
8817 (when (featurep 'org-clock)
8818 (org-clock-save-markers-for-cut-and-paste beg end))
8819 (when (featurep 'org-agenda)
8820 (org-agenda-save-markers-for-cut-and-paste beg end)))
8822 (defun org-check-and-save-marker (marker beg end)
8823 "Check if MARKER is between BEG and END.
8824 If yes, remember the marker and the distance to BEG."
8825 (when (and (marker-buffer marker)
8826 (equal (marker-buffer marker) (current-buffer))
8827 (>= marker beg) (< marker end))
8828 (push (cons marker (- marker beg)) org-markers-to-move)))
8830 (defun org-reinstall-markers-in-region (beg)
8831 "Move all remembered markers to their position relative to BEG."
8832 (dolist (x org-markers-to-move)
8833 (move-marker (car x) (+ beg (cdr x))))
8834 (setq org-markers-to-move nil))
8836 (defun org-narrow-to-subtree ()
8837 "Narrow buffer to the current subtree."
8838 (interactive)
8839 (save-excursion
8840 (save-match-data
8841 (org-with-limited-levels
8842 (narrow-to-region
8843 (progn (org-back-to-heading t) (point))
8844 (progn (org-end-of-subtree t t)
8845 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8846 (point)))))))
8848 (defun org-narrow-to-block ()
8849 "Narrow buffer to the current block."
8850 (interactive)
8851 (let* ((case-fold-search t)
8852 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8853 "^[ \t]*#\\+end_.*")))
8854 (if blockp
8855 (narrow-to-region (car blockp) (cdr blockp))
8856 (user-error "Not in a block"))))
8858 (defun org-clone-subtree-with-time-shift (n &optional shift)
8859 "Clone the task (subtree) at point N times.
8860 The clones will be inserted as siblings.
8862 In interactive use, the user will be prompted for the number of
8863 clones to be produced. If the entry has a timestamp, the user
8864 will also be prompted for a time shift, which may be a repeater
8865 as used in time stamps, for example `+3d'. To disable this,
8866 you can call the function with a universal prefix argument.
8868 When a valid repeater is given and the entry contains any time
8869 stamps, the clones will become a sequence in time, with time
8870 stamps in the subtree shifted for each clone produced. If SHIFT
8871 is nil or the empty string, time stamps will be left alone. The
8872 ID property of the original subtree is removed.
8874 In each clone, all the CLOCK entries will be removed. This
8875 prevents Org from considering that the clocked times overlap.
8877 If the original subtree did contain time stamps with a repeater,
8878 the following will happen:
8879 - the repeater will be removed in each clone
8880 - an additional clone will be produced, with the current, unshifted
8881 date(s) in the entry.
8882 - the original entry will be placed *after* all the clones, with
8883 repeater intact.
8884 - the start days in the repeater in the original entry will be shifted
8885 to past the last clone.
8886 In this way you can spell out a number of instances of a repeating task,
8887 and still retain the repeater to cover future instances of the task.
8889 As described above, N+1 clones are produced when the original
8890 subtree has a repeater. Setting N to 0, then, can be used to
8891 remove the repeater from a subtree and create a shifted clone
8892 with the original repeater."
8893 (interactive "nNumber of clones to produce: ")
8894 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8895 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8896 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8897 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8898 (shift
8899 (or shift
8900 (if (and (not (equal current-prefix-arg '(4)))
8901 (save-excursion
8902 (goto-char beg)
8903 (re-search-forward org-ts-regexp-both end-of-tree t)))
8904 (read-from-minibuffer
8905 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8906 ""))) ;No time shift
8907 (doshift
8908 (and (org-string-nw-p shift)
8909 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8910 shift)
8911 (user-error "Invalid shift specification %s" shift)))))
8912 (goto-char end-of-tree)
8913 (unless (bolp) (insert "\n"))
8914 (let* ((end (point))
8915 (template (buffer-substring beg end))
8916 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8917 (shift-what (pcase (and doshift (match-string 2 shift))
8918 (`nil nil)
8919 ("d" 'day)
8920 ("w" (setq shift-n (* 7 shift-n)) 'day)
8921 ("m" 'month)
8922 ("y" 'year)
8923 (_ (error "Unsupported time unit"))))
8924 (nmin 1)
8925 (nmax n)
8926 (n-no-remove -1)
8927 (idprop (org-entry-get nil "ID")))
8928 (when (and doshift
8929 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8930 template))
8931 (delete-region beg end)
8932 (setq end beg)
8933 (setq nmin 0)
8934 (setq nmax (1+ nmax))
8935 (setq n-no-remove nmax))
8936 (goto-char end)
8937 (cl-loop for n from nmin to nmax do
8938 (insert
8939 ;; Prepare clone.
8940 (with-temp-buffer
8941 (insert template)
8942 (org-mode)
8943 (goto-char (point-min))
8944 (org-show-subtree)
8945 (and idprop (if org-clone-delete-id
8946 (org-entry-delete nil "ID")
8947 (org-id-get-create t)))
8948 (unless (= n 0)
8949 (while (re-search-forward org-clock-line-re nil t)
8950 (delete-region (line-beginning-position)
8951 (line-beginning-position 2)))
8952 (goto-char (point-min))
8953 (while (re-search-forward org-drawer-regexp nil t)
8954 (org-remove-empty-drawer-at (point))))
8955 (goto-char (point-min))
8956 (when doshift
8957 (while (re-search-forward org-ts-regexp-both nil t)
8958 (org-timestamp-change (* n shift-n) shift-what))
8959 (unless (= n n-no-remove)
8960 (goto-char (point-min))
8961 (while (re-search-forward org-ts-regexp nil t)
8962 (save-excursion
8963 (goto-char (match-beginning 0))
8964 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8965 (delete-region (match-beginning 1) (match-end 1)))))))
8966 (buffer-string)))))
8967 (goto-char beg)))
8969 ;;; Outline Sorting
8971 (defun org-sort (with-case)
8972 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8973 Optional argument WITH-CASE means sort case-sensitively."
8974 (interactive "P")
8975 (cond
8976 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8977 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8979 (org-call-with-arg 'org-sort-entries with-case))))
8981 (defun org-sort-remove-invisible (s)
8982 "Remove invisible links from string S."
8983 (remove-text-properties 0 (length s) org-rm-props s)
8984 (while (string-match org-bracket-link-regexp s)
8985 (setq s (replace-match (if (match-end 2)
8986 (match-string 3 s)
8987 (match-string 1 s))
8988 t t s)))
8989 (let ((st (format " %s " s)))
8990 (while (string-match org-emph-re st)
8991 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8992 (setq s (substring st 1 -1)))
8995 (defvar org-priority-regexp) ; defined later in the file
8997 (defvar org-after-sorting-entries-or-items-hook nil
8998 "Hook that is run after a bunch of entries or items have been sorted.
8999 When children are sorted, the cursor is in the parent line when this
9000 hook gets called. When a region or a plain list is sorted, the cursor
9001 will be in the first entry of the sorted region/list.")
9003 (defun org-sort-entries
9004 (&optional with-case sorting-type getkey-func compare-func property
9005 interactive?)
9006 "Sort entries on a certain level of an outline tree.
9007 If there is an active region, the entries in the region are sorted.
9008 Else, if the cursor is before the first entry, sort the top-level items.
9009 Else, the children of the entry at point are sorted.
9011 Sorting can be alphabetically, numerically, by date/time as given by
9012 a time stamp, by a property, by priority order, or by a custom function.
9014 The command prompts for the sorting type unless it has been given to the
9015 function through the SORTING-TYPE argument, which needs to be a character,
9016 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9017 the precise meaning of each character:
9019 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9020 c By creation time, which is assumed to be the first inactive time stamp
9021 at the beginning of a line.
9022 d By deadline date/time.
9023 k By clocking time.
9024 n Numerically, by converting the beginning of the entry/item to a number.
9025 o By order of TODO keywords.
9026 p By priority according to the cookie.
9027 r By the value of a property.
9028 s By scheduled date/time.
9029 t By date/time, either the first active time stamp in the entry, or, if
9030 none exist, by the first inactive one.
9032 Capital letters will reverse the sort order.
9034 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9035 called with point at the beginning of the record. It must return a
9036 value that is compatible with COMPARE-FUNC, the function used to
9037 compare entries.
9039 Comparing entries ignores case by default. However, with an optional argument
9040 WITH-CASE, the sorting considers case as well.
9042 Sorting is done against the visible part of the headlines, it ignores hidden
9043 links.
9045 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
9047 A non-nil value for INTERACTIVE? is used to signal that this
9048 function is being called interactively."
9049 (interactive (list current-prefix-arg nil nil nil nil t))
9050 (let ((case-func (if with-case 'identity 'downcase))
9051 (cmstr
9052 ;; The clock marker is lost when using `sort-subr', let's
9053 ;; store the clocking string.
9054 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9055 (save-excursion
9056 (goto-char org-clock-marker)
9057 (buffer-substring-no-properties (line-beginning-position)
9058 (point)))))
9059 start beg end stars re re2
9060 txt what tmp)
9061 ;; Find beginning and end of region to sort
9062 (cond
9063 ((org-region-active-p)
9064 ;; we will sort the region
9065 (setq end (region-end)
9066 what "region")
9067 (goto-char (region-beginning))
9068 (unless (org-at-heading-p) (outline-next-heading))
9069 (setq start (point)))
9070 ((or (org-at-heading-p)
9071 (ignore-errors (progn (org-back-to-heading) t)))
9072 ;; we will sort the children of the current headline
9073 (org-back-to-heading)
9074 (setq start (point)
9075 end (progn (org-end-of-subtree t t)
9076 (or (bolp) (insert "\n"))
9077 (when (>= (org-back-over-empty-lines) 1)
9078 (forward-line 1))
9079 (point))
9080 what "children")
9081 (goto-char start)
9082 (outline-show-subtree)
9083 (outline-next-heading))
9085 ;; we will sort the top-level entries in this file
9086 (goto-char (point-min))
9087 (or (org-at-heading-p) (outline-next-heading))
9088 (setq start (point))
9089 (goto-char (point-max))
9090 (beginning-of-line 1)
9091 (when (looking-at ".*?\\S-")
9092 ;; File ends in a non-white line
9093 (end-of-line 1)
9094 (insert "\n"))
9095 (setq end (point-max))
9096 (setq what "top-level")
9097 (goto-char start)
9098 (outline-show-all)))
9100 (setq beg (point))
9101 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9103 (looking-at "\\(\\*+\\)")
9104 (setq stars (match-string 1)
9105 re (concat "^" (regexp-quote stars) " +")
9106 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9107 txt (buffer-substring beg end))
9108 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9109 (when (and (not (equal stars "*")) (string-match re2 txt))
9110 (user-error "Region to sort contains a level above the first entry"))
9112 (unless sorting-type
9113 (message
9114 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9115 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9116 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9117 what)
9118 (setq sorting-type (read-char-exclusive)))
9120 (unless getkey-func
9121 (and (= (downcase sorting-type) ?f)
9122 (setq getkey-func
9123 (or (and interactive?
9124 (org-read-function
9125 "Function for extracting keys: "))
9126 (error "Missing key extractor")))))
9128 (and (= (downcase sorting-type) ?r)
9129 (not property)
9130 (setq property
9131 (completing-read "Property: "
9132 (mapcar #'list (org-buffer-property-keys t))
9133 nil t)))
9135 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9136 (message "Sorting entries...")
9138 (save-restriction
9139 (narrow-to-region start end)
9140 (let ((dcst (downcase sorting-type))
9141 (case-fold-search nil)
9142 (now (current-time)))
9143 (sort-subr
9144 (/= dcst sorting-type)
9145 ;; This function moves to the beginning character of the "record" to
9146 ;; be sorted.
9147 (lambda nil
9148 (if (re-search-forward re nil t)
9149 (goto-char (match-beginning 0))
9150 (goto-char (point-max))))
9151 ;; This function moves to the last character of the "record" being
9152 ;; sorted.
9153 (lambda nil
9154 (save-match-data
9155 (condition-case nil
9156 (outline-forward-same-level 1)
9157 (error
9158 (goto-char (point-max))))))
9159 ;; This function returns the value that gets sorted against.
9160 (lambda nil
9161 (cond
9162 ((= dcst ?n)
9163 (if (looking-at org-complex-heading-regexp)
9164 (string-to-number (org-sort-remove-invisible (match-string 4)))
9165 nil))
9166 ((= dcst ?a)
9167 (if (looking-at org-complex-heading-regexp)
9168 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9169 nil))
9170 ((= dcst ?k)
9171 (or (get-text-property (point) :org-clock-minutes) 0))
9172 ((= dcst ?t)
9173 (let ((end (save-excursion (outline-next-heading) (point))))
9174 (if (or (re-search-forward org-ts-regexp end t)
9175 (re-search-forward org-ts-regexp-both end t))
9176 (org-time-string-to-seconds (match-string 0))
9177 (float-time now))))
9178 ((= dcst ?c)
9179 (let ((end (save-excursion (outline-next-heading) (point))))
9180 (if (re-search-forward
9181 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9182 end t)
9183 (org-time-string-to-seconds (match-string 0))
9184 (float-time now))))
9185 ((= dcst ?s)
9186 (let ((end (save-excursion (outline-next-heading) (point))))
9187 (if (re-search-forward org-scheduled-time-regexp end t)
9188 (org-time-string-to-seconds (match-string 1))
9189 (float-time now))))
9190 ((= dcst ?d)
9191 (let ((end (save-excursion (outline-next-heading) (point))))
9192 (if (re-search-forward org-deadline-time-regexp end t)
9193 (org-time-string-to-seconds (match-string 1))
9194 (float-time now))))
9195 ((= dcst ?p)
9196 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9197 (string-to-char (match-string 2))
9198 org-default-priority))
9199 ((= dcst ?r)
9200 (or (org-entry-get nil property) ""))
9201 ((= dcst ?o)
9202 (when (looking-at org-complex-heading-regexp)
9203 (let* ((m (match-string 2))
9204 (s (if (member m org-done-keywords) '- '+)))
9205 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9206 ((= dcst ?f)
9207 (if getkey-func
9208 (progn
9209 (setq tmp (funcall getkey-func))
9210 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9211 tmp)
9212 (error "Invalid key function `%s'" getkey-func)))
9213 (t (error "Invalid sorting type `%c'" sorting-type))))
9215 (cond
9216 ((= dcst ?a) 'string<)
9217 ((= dcst ?f)
9218 (or compare-func
9219 (and interactive?
9220 (org-read-function
9221 (concat "Function for comparing keys "
9222 "(empty for default `sort-subr' predicate): ")
9223 'allow-empty))))
9224 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9225 (run-hooks 'org-after-sorting-entries-or-items-hook)
9226 ;; Reset the clock marker if needed
9227 (when cmstr
9228 (save-excursion
9229 (goto-char start)
9230 (search-forward cmstr nil t)
9231 (move-marker org-clock-marker (point))))
9232 (message "Sorting entries...done")))
9234 ;;; The orgstruct minor mode
9236 ;; Define a minor mode which can be used in other modes in order to
9237 ;; integrate the Org mode structure editing commands.
9239 ;; This is really a hack, because the Org mode structure commands use
9240 ;; keys which normally belong to the major mode. Here is how it
9241 ;; works: The minor mode defines all the keys necessary to operate the
9242 ;; structure commands, but wraps the commands into a function which
9243 ;; tests if the cursor is currently at a headline or a plain list
9244 ;; item. If that is the case, the structure command is used,
9245 ;; temporarily setting many Org mode variables like regular
9246 ;; expressions for filling etc. However, when any of those keys is
9247 ;; used at a different location, function uses `key-binding' to look
9248 ;; up if the key has an associated command in another currently active
9249 ;; keymap (minor modes, major mode, global), and executes that
9250 ;; command. There might be problems if any of the keys is otherwise
9251 ;; used as a prefix key.
9253 (defcustom orgstruct-heading-prefix-regexp ""
9254 "Regexp that matches the custom prefix of Org headlines in
9255 orgstruct(++)-mode."
9256 :group 'org
9257 :version "24.4"
9258 :package-version '(Org . "8.3")
9259 :type 'regexp)
9260 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9262 (defcustom orgstruct-setup-hook nil
9263 "Hook run after orgstruct-mode-map is filled."
9264 :group 'org
9265 :version "24.4"
9266 :package-version '(Org . "8.0")
9267 :type 'hook)
9269 (defvar orgstruct-initialized nil)
9271 (defvar org-local-vars nil
9272 "List of local variables, for use by `orgstruct-mode'.")
9274 ;;;###autoload
9275 (define-minor-mode orgstruct-mode
9276 "Toggle the minor mode `orgstruct-mode'.
9277 This mode is for using Org mode structure commands in other
9278 modes. The following keys behave as if Org mode were active, if
9279 the cursor is on a headline, or on a plain list item (both as
9280 defined by Org mode)."
9281 nil " OrgStruct" (make-sparse-keymap)
9282 (funcall (if orgstruct-mode
9283 'add-to-invisibility-spec
9284 'remove-from-invisibility-spec)
9285 '(outline . t))
9286 (when orgstruct-mode
9287 (org-load-modules-maybe)
9288 (unless orgstruct-initialized
9289 (orgstruct-setup)
9290 (setq orgstruct-initialized t))))
9292 ;;;###autoload
9293 (defun turn-on-orgstruct ()
9294 "Unconditionally turn on `orgstruct-mode'."
9295 (orgstruct-mode 1))
9297 (defvar-local orgstruct-is-++ nil
9298 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9299 (defvar-local org-fb-vars nil)
9300 (defun orgstruct++-mode (&optional arg)
9301 "Toggle `orgstruct-mode', the enhanced version of it.
9302 In addition to setting orgstruct-mode, this also exports all
9303 indentation and autofilling variables from Org mode into the
9304 buffer. It will also recognize item context in multiline items."
9305 (interactive "P")
9306 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9307 (if (< arg 1)
9308 (progn (orgstruct-mode -1)
9309 (dolist (v org-fb-vars)
9310 (set (make-local-variable (car v))
9311 (if (eq (car-safe (cadr v)) 'quote)
9312 (cl-cadadr v)
9313 (nth 1 v)))))
9314 (orgstruct-mode 1)
9315 (setq org-fb-vars nil)
9316 (unless org-local-vars
9317 (setq org-local-vars (org-get-local-variables)))
9318 (let (var val)
9319 (dolist (x org-local-vars)
9320 (when (string-match
9321 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9322 \\|fill-prefix\\|indent-\\)"
9323 (symbol-name (car x)))
9324 (setq var (car x) val (nth 1 x))
9325 (push (list var `(quote ,(eval var))) org-fb-vars)
9326 (set (make-local-variable var)
9327 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9328 (setq-local orgstruct-is-++ t))))
9330 ;;;###autoload
9331 (defun turn-on-orgstruct++ ()
9332 "Unconditionally turn on `orgstruct++-mode'."
9333 (orgstruct++-mode 1))
9335 (defun orgstruct-error ()
9336 "Error when there is no default binding for a structure key."
9337 (interactive)
9338 (funcall (if (fboundp 'user-error)
9339 'user-error
9340 'error)
9341 "This key has no function outside structure elements"))
9343 (defun orgstruct-setup ()
9344 "Setup orgstruct keymap."
9345 (dolist (cell '((org-demote . t)
9346 (org-metaleft . t)
9347 (org-metaright . t)
9348 (org-promote . t)
9349 (org-shiftmetaleft . t)
9350 (org-shiftmetaright . t)
9351 org-backward-element
9352 org-backward-heading-same-level
9353 org-ctrl-c-ret
9354 org-ctrl-c-minus
9355 org-ctrl-c-star
9356 org-cycle
9357 org-force-cycle-archived
9358 org-forward-heading-same-level
9359 org-insert-heading
9360 org-insert-heading-respect-content
9361 org-kill-note-or-show-branches
9362 org-mark-subtree
9363 org-meta-return
9364 org-metadown
9365 org-metaup
9366 org-narrow-to-subtree
9367 org-promote-subtree
9368 org-reveal
9369 org-shiftdown
9370 org-shiftleft
9371 org-shiftmetadown
9372 org-shiftmetaup
9373 org-shiftright
9374 org-shifttab
9375 org-shifttab
9376 org-shiftup
9377 org-show-children
9378 org-show-subtree
9379 org-sort
9380 org-up-element
9381 outline-demote
9382 outline-next-visible-heading
9383 outline-previous-visible-heading
9384 outline-promote
9385 outline-up-heading))
9386 (let ((f (or (car-safe cell) cell))
9387 (disable-when-heading-prefix (cdr-safe cell)))
9388 (when (fboundp f)
9389 (let ((new-bindings))
9390 (dolist (binding (nconc (where-is-internal f org-mode-map)
9391 (where-is-internal f outline-mode-map)))
9392 (push binding new-bindings)
9393 ;; TODO use local-function-key-map
9394 (dolist (rep '(("<tab>" . "TAB")
9395 ("<return>" . "RET")
9396 ("<escape>" . "ESC")
9397 ("<delete>" . "DEL")))
9398 (setq binding (read-kbd-macro
9399 (let ((case-fold-search))
9400 (replace-regexp-in-string
9401 (regexp-quote (cdr rep))
9402 (car rep)
9403 (key-description binding)))))
9404 (cl-pushnew binding new-bindings :test 'equal)))
9405 (dolist (binding new-bindings)
9406 (let ((key (lookup-key orgstruct-mode-map binding)))
9407 (when (or (not key) (numberp key))
9408 (ignore-errors
9409 (org-defkey orgstruct-mode-map
9410 binding
9411 (orgstruct-make-binding
9412 f binding disable-when-heading-prefix))))))))))
9413 (run-hooks 'orgstruct-setup-hook))
9415 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9416 "Create a function for binding in the structure minor mode.
9417 FUN is the command to call inside a table. KEY is the key that
9418 should be checked in for a command to execute outside of tables.
9419 Non-nil `disable-when-heading-prefix' means to disable the command
9420 if `orgstruct-heading-prefix-regexp' is not empty."
9421 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9422 (let ((nname name)
9423 (i 0))
9424 (while (fboundp (intern nname))
9425 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9426 (setq name (intern nname)))
9427 (eval
9428 (let ((bindings '((org-heading-regexp
9429 (concat "^"
9430 orgstruct-heading-prefix-regexp
9431 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9432 (org-outline-regexp
9433 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9434 (org-outline-regexp-bol
9435 (concat "^" org-outline-regexp))
9436 (outline-regexp org-outline-regexp)
9437 (outline-heading-end-regexp "\n")
9438 (outline-level 'org-outline-level)
9439 (outline-heading-alist))))
9440 `(defun ,name (arg)
9441 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9442 "Outside of structure, run the binding of `"
9443 (key-description key) "'."
9444 (when disable-when-heading-prefix
9445 (concat
9446 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9447 "back to the default binding due to limitations of Org's implementation of\n"
9448 "`" (symbol-name fun) "'.")))
9449 (interactive "p")
9450 (let* ((disable
9451 ,(and disable-when-heading-prefix
9452 '(not (string= orgstruct-heading-prefix-regexp ""))))
9453 (fallback
9454 (or disable
9455 (not
9456 (let* ,bindings
9457 (org-context-p 'headline 'item
9458 ,(when (memq fun
9459 '(org-insert-heading
9460 org-insert-heading-respect-content
9461 org-meta-return))
9462 '(when orgstruct-is-++
9463 'item-body))))))))
9464 (if fallback
9465 (let* ((orgstruct-mode)
9466 (binding
9467 (let ((key ,key))
9468 (catch 'exit
9469 (dolist
9470 (rep
9471 '(nil
9472 ("<\\([^>]*\\)tab>" . "\\1TAB")
9473 ("<\\([^>]*\\)return>" . "\\1RET")
9474 ("<\\([^>]*\\)escape>" . "\\1ESC")
9475 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9476 nil)
9477 (when rep
9478 (setq key (read-kbd-macro
9479 (let ((case-fold-search))
9480 (replace-regexp-in-string
9481 (car rep)
9482 (cdr rep)
9483 (key-description key))))))
9484 (when (key-binding key)
9485 (throw 'exit (key-binding key))))))))
9486 (if (keymapp binding)
9487 (org-set-transient-map binding)
9488 (let ((func (or binding
9489 (unless disable
9490 'orgstruct-error))))
9491 (when func
9492 (call-interactively func)))))
9493 (org-run-like-in-org-mode
9494 (lambda ()
9495 (interactive)
9496 (let* ,bindings
9497 (call-interactively ',fun)))))))))
9498 name))
9500 (defun org-contextualize-keys (alist contexts)
9501 "Return valid elements in ALIST depending on CONTEXTS.
9503 `org-agenda-custom-commands' or `org-capture-templates' are the
9504 values used for ALIST, and `org-agenda-custom-commands-contexts'
9505 or `org-capture-templates-contexts' are the associated contexts
9506 definitions."
9507 (let ((contexts
9508 ;; normalize contexts
9509 (mapcar
9510 (lambda(c) (cond ((listp (cadr c))
9511 (list (car c) (car c) (nth 1 c)))
9512 ((string= "" (cadr c))
9513 (list (car c) (car c) (nth 2 c)))
9514 (t c)))
9515 contexts))
9516 (a alist) r s)
9517 ;; loop over all commands or templates
9518 (dolist (c a)
9519 (let (vrules repl)
9520 (cond
9521 ((not (assoc (car c) contexts))
9522 (push c r))
9523 ((and (assoc (car c) contexts)
9524 (setq vrules (org-contextualize-validate-key
9525 (car c) contexts)))
9526 (mapc (lambda (vr)
9527 (unless (equal (car vr) (cadr vr))
9528 (setq repl vr)))
9529 vrules)
9530 (if (not repl) (push c r)
9531 (push (cadr repl) s)
9532 (push
9533 (cons (car c)
9534 (cdr (or (assoc (cadr repl) alist)
9535 (error "Undefined key `%s' as contextual replacement for `%s'"
9536 (cadr repl) (car c)))))
9537 r))))))
9538 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9539 (delq
9541 (delete-dups
9542 (mapcar (lambda (x)
9543 (let ((tpl (car x)))
9544 (unless (delq
9546 (mapcar (lambda (y)
9547 (equal y tpl))
9549 x)))
9550 (reverse r))))))
9552 (defun org-contextualize-validate-key (key contexts)
9553 "Check CONTEXTS for agenda or capture KEY."
9554 (let (res)
9555 (dolist (r contexts)
9556 (dolist (rr (car (last r)))
9557 (when
9558 (and (equal key (car r))
9559 (if (functionp rr) (funcall rr)
9560 (or (and (eq (car rr) 'in-file)
9561 (buffer-file-name)
9562 (string-match (cdr rr) (buffer-file-name)))
9563 (and (eq (car rr) 'in-mode)
9564 (string-match (cdr rr) (symbol-name major-mode)))
9565 (and (eq (car rr) 'in-buffer)
9566 (string-match (cdr rr) (buffer-name)))
9567 (when (and (eq (car rr) 'not-in-file)
9568 (buffer-file-name))
9569 (not (string-match (cdr rr) (buffer-file-name))))
9570 (when (eq (car rr) 'not-in-mode)
9571 (not (string-match (cdr rr) (symbol-name major-mode))))
9572 (when (eq (car rr) 'not-in-buffer)
9573 (not (string-match (cdr rr) (buffer-name)))))))
9574 (push r res))))
9575 (delete-dups (delq nil res))))
9577 (defun org-context-p (&rest contexts)
9578 "Check if local context is any of CONTEXTS.
9579 Possible values in the list of contexts are `table', `headline', and `item'."
9580 (let ((pos (point)))
9581 (goto-char (point-at-bol))
9582 (prog1 (or (and (memq 'table contexts)
9583 (looking-at "[ \t]*|"))
9584 (and (memq 'headline contexts)
9585 (looking-at org-outline-regexp))
9586 (and (memq 'item contexts)
9587 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9588 (and (memq 'item-body contexts)
9589 (org-in-item-p)))
9590 (goto-char pos))))
9592 (defconst org-unique-local-variables
9593 '(org-element--cache
9594 org-element--cache-objects
9595 org-element--cache-sync-keys
9596 org-element--cache-sync-requests
9597 org-element--cache-sync-timer)
9598 "List of local variables that cannot be transferred to another buffer.")
9600 (defun org-get-local-variables ()
9601 "Return a list of all local variables in an Org mode buffer."
9602 (delq nil
9603 (mapcar
9604 (lambda (x)
9605 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9606 (name (car binding)))
9607 (and (not (get name 'org-state))
9608 (not (memq name org-unique-local-variables))
9609 (string-match-p
9610 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9611 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9612 (symbol-name name))
9613 binding)))
9614 (with-temp-buffer
9615 (org-mode)
9616 (buffer-local-variables)))))
9618 (defun org-clone-local-variables (from-buffer &optional regexp)
9619 "Clone local variables from FROM-BUFFER.
9620 Optional argument REGEXP selects variables to clone."
9621 (dolist (pair (buffer-local-variables from-buffer))
9622 (pcase pair
9623 (`(,name . ,value) ;ignore unbound variables
9624 (when (and (not (memq name org-unique-local-variables))
9625 (or (null regexp) (string-match-p regexp (symbol-name name))))
9626 (set (make-local-variable name) value))))))
9628 ;;;###autoload
9629 (defun org-run-like-in-org-mode (cmd)
9630 "Run a command, pretending that the current buffer is in Org mode.
9631 This will temporarily bind local variables that are typically bound in
9632 Org mode to the values they have in Org mode, and then interactively
9633 call CMD."
9634 (org-load-modules-maybe)
9635 (unless org-local-vars
9636 (setq org-local-vars (org-get-local-variables)))
9637 (let (binds)
9638 (dolist (var org-local-vars)
9639 (when (or (not (boundp (car var)))
9640 (eq (symbol-value (car var))
9641 (default-value (car var))))
9642 (push (list (car var) `(quote ,(cadr var))) binds)))
9643 (eval `(let ,binds
9644 (call-interactively (quote ,cmd))))))
9646 (defun org-get-category (&optional pos force-refresh)
9647 "Get the category applying to position POS."
9648 (save-match-data
9649 (when force-refresh (org-refresh-category-properties))
9650 (let ((pos (or pos (point))))
9651 (or (get-text-property pos 'org-category)
9652 (progn (org-refresh-category-properties)
9653 (get-text-property pos 'org-category))))))
9655 ;;; Refresh properties
9657 (defun org-refresh-properties (dprop tprop)
9658 "Refresh buffer text properties.
9659 DPROP is the drawer property and TPROP is either the
9660 corresponding text property to set, or an alist with each element
9661 being a text property (as a symbol) and a function to apply to
9662 the value of the drawer property."
9663 (let* ((case-fold-search t)
9664 (inhibit-read-only t)
9665 (inherit? (org-property-inherit-p dprop))
9666 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9667 (global (and inherit? (org--property-global-value dprop nil))))
9668 (org-with-silent-modifications
9669 (org-with-point-at 1
9670 ;; Set global values (e.g., values defined through
9671 ;; "#+PROPERTY:" keywords) to the whole buffer.
9672 (when global (put-text-property (point-min) (point-max) tprop global))
9673 ;; Set local values.
9674 (while (re-search-forward property-re nil t)
9675 (when (org-at-property-p)
9676 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9677 (outline-next-heading))))))
9679 (defun org-refresh-property (tprop p &optional inherit)
9680 "Refresh the buffer text property TPROP from the drawer property P.
9681 The refresh happens only for the current headline, or the whole
9682 sub-tree if optional argument INHERIT is non-nil."
9683 (unless (org-before-first-heading-p)
9684 (save-excursion
9685 (org-back-to-heading t)
9686 (let ((start (point))
9687 (end (save-excursion
9688 (if inherit (org-end-of-subtree t t)
9689 (or (outline-next-heading) (point-max))))))
9690 (if (symbolp tprop)
9691 ;; TPROP is a text property symbol.
9692 (put-text-property start end tprop p)
9693 ;; TPROP is an alist with (property . function) elements.
9694 (pcase-dolist (`(,prop . ,f) tprop)
9695 (put-text-property start end prop (funcall f p))))))))
9697 (defun org-refresh-category-properties ()
9698 "Refresh category text properties in the buffer."
9699 (let ((case-fold-search t)
9700 (inhibit-read-only t)
9701 (default-category
9702 (cond ((null org-category)
9703 (if buffer-file-name
9704 (file-name-sans-extension
9705 (file-name-nondirectory buffer-file-name))
9706 "???"))
9707 ((symbolp org-category) (symbol-name org-category))
9708 (t org-category))))
9709 (org-with-silent-modifications
9710 (org-with-wide-buffer
9711 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9712 ;; This is the default category for the buffer. If none is
9713 ;; found, fall-back to `org-category' or buffer file name.
9714 (put-text-property
9715 (point-min) (point-max)
9716 'org-category
9717 (catch 'buffer-category
9718 (goto-char (point-max))
9719 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9720 (let ((element (org-element-at-point)))
9721 (when (eq (org-element-type element) 'keyword)
9722 (throw 'buffer-category
9723 (org-element-property :value element)))))
9724 default-category))
9725 ;; Set sub-tree specific categories.
9726 (goto-char (point-min))
9727 (let ((regexp (org-re-property "CATEGORY")))
9728 (while (re-search-forward regexp nil t)
9729 (let ((value (match-string-no-properties 3)))
9730 (when (org-at-property-p)
9731 (put-text-property
9732 (save-excursion (org-back-to-heading t) (point))
9733 (save-excursion (org-end-of-subtree t t) (point))
9734 'org-category
9735 value)))))))))
9737 (defun org-refresh-stats-properties ()
9738 "Refresh stats text properties in the buffer."
9739 (org-with-silent-modifications
9740 (org-with-point-at 1
9741 (let ((regexp (concat org-outline-regexp-bol
9742 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9743 (while (re-search-forward regexp nil t)
9744 (let* ((numerator (string-to-number (match-string 1)))
9745 (denominator (and (match-end 2)
9746 (string-to-number (match-string 2))))
9747 (stats (cond ((not denominator) numerator) ;percent
9748 ((= denominator 0) 0)
9749 (t (/ (* numerator 100) denominator)))))
9750 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9751 'org-stats stats)))))))
9753 (defun org-refresh-effort-properties ()
9754 "Refresh effort properties"
9755 (org-refresh-properties
9756 org-effort-property
9757 '((effort . identity)
9758 (effort-minutes . org-duration-string-to-minutes))))
9760 ;;;; Link Stuff
9762 ;;; Link abbreviations
9764 (defun org-link-expand-abbrev (link)
9765 "Apply replacements as defined in `org-link-abbrev-alist'."
9766 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9767 (let* ((key (match-string 1 link))
9768 (as (or (assoc key org-link-abbrev-alist-local)
9769 (assoc key org-link-abbrev-alist)))
9770 (tag (and (match-end 2) (match-string 3 link)))
9771 rpl)
9772 (if (not as)
9773 link
9774 (setq rpl (cdr as))
9775 (cond
9776 ((symbolp rpl) (funcall rpl tag))
9777 ((string-match "%(\\([^)]+\\))" rpl)
9778 (replace-match
9779 (save-match-data
9780 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9781 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9782 ((string-match "%h" rpl)
9783 (replace-match (url-hexify-string (or tag "")) t t rpl))
9784 (t (concat rpl tag)))))
9785 link))
9787 ;;; Storing and inserting links
9789 (defvar org-insert-link-history nil
9790 "Minibuffer history for links inserted with `org-insert-link'.")
9792 (defvar org-stored-links nil
9793 "Contains the links stored with `org-store-link'.")
9795 (defvar org-store-link-plist nil
9796 "Plist with info about the most recently link created with `org-store-link'.")
9798 (defun org-store-link-functions ()
9799 "Return a list of functions that are called to create and store a link.
9800 The functions defined in the :store property of
9801 `org-link-parameters'.
9803 Each function will be called in turn until one returns a non-nil
9804 value. Each function should check if it is responsible for
9805 creating this link (for example by looking at the major mode).
9806 If not, it must exit and return nil. If yes, it should return
9807 a non-nil value after calling `org-store-link-props' with a list
9808 of properties and values. Special properties are:
9810 :type The link prefix, like \"http\". This must be given.
9811 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9812 This is obligatory as well.
9813 :description Optional default description for the second pair
9814 of brackets in an Org mode link. The user can still change
9815 this when inserting this link into an Org mode buffer.
9817 In addition to these, any additional properties can be specified
9818 and then used in capture templates."
9819 (cl-loop for link in org-link-parameters
9820 with store-func
9821 do (setq store-func (org-link-get-parameter (car link) :store))
9822 if store-func
9823 collect store-func))
9825 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9826 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9828 ;;;###autoload
9829 (defun org-store-link (arg)
9830 "Store an org-link to the current location.
9831 \\<org-mode-map>
9832 This link is added to `org-stored-links' and can later be inserted
9833 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9835 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9836 A single
9837 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9838 `org-gnus-prefer-web-links' for links to Usenet articles.
9840 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9841 skipping storing functions that are not
9842 part of Org core.
9844 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9845 prefix ARG forces storing a link for each line in the
9846 active region."
9847 (interactive "P")
9848 (org-load-modules-maybe)
9849 (if (and (equal arg '(64)) (org-region-active-p))
9850 (save-excursion
9851 (let ((end (region-end)))
9852 (goto-char (region-beginning))
9853 (set-mark (point))
9854 (while (< (point-at-eol) end)
9855 (move-end-of-line 1) (activate-mark)
9856 (let (current-prefix-arg)
9857 (call-interactively 'org-store-link))
9858 (move-beginning-of-line 2)
9859 (set-mark (point)))))
9860 (setq org-store-link-plist nil)
9861 (let (link cpltxt desc description search
9862 txt custom-id agenda-link sfuns sfunsn)
9863 (cond
9865 ;; Store a link using an external link type
9866 ((and (not (equal arg '(16)))
9867 (setq sfuns
9868 (delq
9869 nil (mapcar (lambda (f)
9870 (let (fs) (if (funcall f) (push f fs))))
9871 (org-store-link-functions)))
9872 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9873 (or (and (cdr sfuns)
9874 (funcall (intern
9875 (completing-read
9876 "Which function for creating the link? "
9877 sfunsn nil t (car sfunsn)))))
9878 (funcall (caar sfuns)))
9879 (setq link (plist-get org-store-link-plist :link)
9880 desc (or (plist-get org-store-link-plist
9881 :description)
9882 link))))
9884 ;; Store a link from a source code buffer.
9885 ((org-src-edit-buffer-p)
9886 (let ((coderef-format (org-src-coderef-format)))
9887 (cond ((save-excursion
9888 (beginning-of-line)
9889 (looking-at (org-src-coderef-regexp coderef-format)))
9890 (setq link (format "(%s)" (match-string-no-properties 3))))
9891 ((called-interactively-p 'any)
9892 (let ((label (read-string "Code line label: ")))
9893 (end-of-line)
9894 (setq link (format coderef-format label))
9895 (let ((gc (- 79 (length link))))
9896 (if (< (current-column) gc)
9897 (org-move-to-column gc t)
9898 (insert " ")))
9899 (insert link)
9900 (setq link (concat "(" label ")"))
9901 (setq desc nil)))
9902 (t (setq link nil)))))
9904 ;; We are in the agenda, link to referenced location
9905 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9906 (let ((m (or (get-text-property (point) 'org-hd-marker)
9907 (get-text-property (point) 'org-marker))))
9908 (when m
9909 (org-with-point-at m
9910 (setq agenda-link
9911 (if (called-interactively-p 'any)
9912 (call-interactively 'org-store-link)
9913 (org-store-link nil)))))))
9915 ((eq major-mode 'calendar-mode)
9916 (let ((cd (calendar-cursor-to-date)))
9917 (setq link
9918 (format-time-string
9919 (car org-time-stamp-formats)
9920 (apply 'encode-time
9921 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9922 nil nil nil))))
9923 (org-store-link-props :type "calendar" :date cd)))
9925 ((eq major-mode 'help-mode)
9926 (setq link (concat "help:" (save-excursion
9927 (goto-char (point-min))
9928 (looking-at "^[^ ]+")
9929 (match-string 0))))
9930 (org-store-link-props :type "help"))
9932 ((eq major-mode 'w3-mode)
9933 (setq cpltxt (if (and (buffer-name)
9934 (not (string-match "Untitled" (buffer-name))))
9935 (buffer-name)
9936 (url-view-url t))
9937 link (url-view-url t))
9938 (org-store-link-props :type "w3" :url (url-view-url t)))
9940 ((eq major-mode 'image-mode)
9941 (setq cpltxt (concat "file:"
9942 (abbreviate-file-name buffer-file-name))
9943 link cpltxt)
9944 (org-store-link-props :type "image" :file buffer-file-name))
9946 ;; In dired, store a link to the file of the current line
9947 ((derived-mode-p 'dired-mode)
9948 (let ((file (dired-get-filename nil t)))
9949 (setq file (if file
9950 (abbreviate-file-name
9951 (expand-file-name (dired-get-filename nil t)))
9952 ;; otherwise, no file so use current directory.
9953 default-directory))
9954 (setq cpltxt (concat "file:" file)
9955 link cpltxt)))
9957 ((setq search (run-hook-with-args-until-success
9958 'org-create-file-search-functions))
9959 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9960 "::" search))
9961 (setq cpltxt (or description link)))
9963 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9964 (org-with-limited-levels
9965 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9966 (cond
9967 ;; Store a link using the target at point
9968 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9969 (setq cpltxt
9970 (concat "file:"
9971 (abbreviate-file-name
9972 (buffer-file-name (buffer-base-buffer)))
9973 "::" (match-string 1))
9974 link cpltxt))
9975 ((and (featurep 'org-id)
9976 (or (eq org-id-link-to-org-use-id t)
9977 (and (called-interactively-p 'any)
9978 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9979 (and (eq org-id-link-to-org-use-id
9980 'create-if-interactive-and-no-custom-id)
9981 (not custom-id))))
9982 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9983 ;; Store a link using the ID at point
9984 (setq link (condition-case nil
9985 (prog1 (org-id-store-link)
9986 (setq desc (or (plist-get org-store-link-plist
9987 :description)
9988 "")))
9989 (error
9990 ;; Probably before first headline, link only to file
9991 (concat "file:"
9992 (abbreviate-file-name
9993 (buffer-file-name (buffer-base-buffer))))))))
9995 ;; Just link to current headline
9996 (setq cpltxt (concat "file:"
9997 (abbreviate-file-name
9998 (buffer-file-name (buffer-base-buffer)))))
9999 ;; Add a context search string
10000 (when (org-xor org-context-in-file-links
10001 (equal arg '(4)))
10002 (let* ((element (org-element-at-point))
10003 (name (org-element-property :name element)))
10004 (setq txt (cond
10005 ((org-at-heading-p) nil)
10006 (name)
10007 ((org-region-active-p)
10008 (buffer-substring (region-beginning) (region-end)))))
10009 (when (or (null txt) (string-match "\\S-" txt))
10010 (setq cpltxt
10011 (concat cpltxt "::"
10012 (condition-case nil
10013 (org-make-org-heading-search-string txt)
10014 (error "")))
10015 desc (or name
10016 (nth 4 (ignore-errors (org-heading-components)))
10017 "NONE")))))
10018 (when (string-match "::\\'" cpltxt)
10019 (setq cpltxt (substring cpltxt 0 -2)))
10020 (setq link cpltxt)))))
10022 ((buffer-file-name (buffer-base-buffer))
10023 ;; Just link to this file here.
10024 (setq cpltxt (concat "file:"
10025 (abbreviate-file-name
10026 (buffer-file-name (buffer-base-buffer)))))
10027 ;; Add a context string.
10028 (when (org-xor org-context-in-file-links
10029 (equal arg '(4)))
10030 (setq txt (if (org-region-active-p)
10031 (buffer-substring (region-beginning) (region-end))
10032 (buffer-substring (point-at-bol) (point-at-eol))))
10033 ;; Only use search option if there is some text.
10034 (when (string-match "\\S-" txt)
10035 (setq cpltxt
10036 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10037 desc "NONE")))
10038 (setq link cpltxt))
10040 ((called-interactively-p 'interactive)
10041 (user-error "No method for storing a link from this buffer"))
10043 (t (setq link nil)))
10045 ;; We're done setting link and desc, clean up
10046 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10047 (setq link (or link cpltxt)
10048 desc (or desc cpltxt))
10049 (cond ((not desc))
10050 ((equal desc "NONE") (setq desc nil))
10051 (t (setq desc
10052 (replace-regexp-in-string
10053 org-bracket-link-analytic-regexp
10054 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10055 desc))))
10056 ;; Return the link
10057 (if (not (and (or (called-interactively-p 'any)
10058 executing-kbd-macro)
10059 link))
10060 (or agenda-link (and link (org-make-link-string link desc)))
10061 (push (list link desc) org-stored-links)
10062 (message "Stored: %s" (or desc link))
10063 (when custom-id
10064 (setq link (concat "file:" (abbreviate-file-name
10065 (buffer-file-name)) "::#" custom-id))
10066 (push (list link desc) org-stored-links))
10067 (car org-stored-links)))))
10069 (defun org-store-link-props (&rest plist)
10070 "Store link properties, extract names, addresses and dates."
10071 (let ((x (plist-get plist :from)))
10072 (when x
10073 (let ((adr (mail-extract-address-components x)))
10074 (setq plist (plist-put plist :fromname (car adr)))
10075 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10076 (let ((x (plist-get plist :to)))
10077 (when x
10078 (let ((adr (mail-extract-address-components x)))
10079 (setq plist (plist-put plist :toname (car adr)))
10080 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10081 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10082 (when x
10083 (setq plist (plist-put plist :date-timestamp
10084 (format-time-string
10085 (org-time-stamp-format t) x)))
10086 (setq plist (plist-put plist :date-timestamp-inactive
10087 (format-time-string
10088 (org-time-stamp-format t t) x)))))
10089 (let ((from (plist-get plist :from))
10090 (to (plist-get plist :to)))
10091 (when (and from to org-from-is-user-regexp)
10092 (setq plist
10093 (plist-put plist :fromto
10094 (if (string-match org-from-is-user-regexp from)
10095 (concat "to %t")
10096 (concat "from %f"))))))
10097 (setq org-store-link-plist plist))
10099 (defun org-add-link-props (&rest plist)
10100 "Add these properties to the link property list."
10101 (let (key value)
10102 (while plist
10103 (setq key (pop plist) value (pop plist))
10104 (setq org-store-link-plist
10105 (plist-put org-store-link-plist key value)))))
10107 (defun org-email-link-description (&optional fmt)
10108 "Return the description part of an email link.
10109 This takes information from `org-store-link-plist' and formats it
10110 according to FMT (default from `org-email-link-description-format')."
10111 (setq fmt (or fmt org-email-link-description-format))
10112 (let* ((p org-store-link-plist)
10113 (to (plist-get p :toaddress))
10114 (from (plist-get p :fromaddress))
10115 (table
10116 (list
10117 (cons "%c" (plist-get p :fromto))
10118 (cons "%F" (plist-get p :from))
10119 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10120 (cons "%T" (plist-get p :to))
10121 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10122 (cons "%s" (plist-get p :subject))
10123 (cons "%d" (plist-get p :date))
10124 (cons "%m" (plist-get p :message-id)))))
10125 (when (string-match "%c" fmt)
10126 ;; Check if the user wrote this message
10127 (if (and org-from-is-user-regexp from to
10128 (save-match-data (string-match org-from-is-user-regexp from)))
10129 (setq fmt (replace-match "to %t" t t fmt))
10130 (setq fmt (replace-match "from %f" t t fmt))))
10131 (org-replace-escapes fmt table)))
10133 (defun org-make-org-heading-search-string (&optional string)
10134 "Make search string for the current headline or STRING."
10135 (let ((s (or string
10136 (and (derived-mode-p 'org-mode)
10137 (save-excursion
10138 (org-back-to-heading t)
10139 (org-element-property :raw-value (org-element-at-point))))))
10140 (lines org-context-in-file-links))
10141 (or string (setq s (concat "*" s))) ; Add * for headlines
10142 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10143 (when (and string (integerp lines) (> lines 0))
10144 (let ((slines (org-split-string s "\n")))
10145 (when (< lines (length slines))
10146 (setq s (mapconcat
10147 'identity
10148 (reverse (nthcdr (- (length slines) lines)
10149 (reverse slines))) "\n")))))
10150 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10152 (defun org-make-link-string (link &optional description)
10153 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10154 (unless (org-string-nw-p link) (error "Empty link"))
10155 (let ((uri (cond ((string-match org-link-types-re link)
10156 (concat (match-string 1 link)
10157 (org-link-escape (substring link (match-end 1)))))
10158 ;; For readability, url-encode internal links only
10159 ;; when absolutely needed (i.e, when they contain
10160 ;; square brackets). File links however, are
10161 ;; encoded since, e.g., spaces are significant.
10162 ((or (file-name-absolute-p link)
10163 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10164 (org-link-escape link))
10165 (t link)))
10166 (description
10167 (and (org-string-nw-p description)
10168 ;; Remove brackets from description, as they are fatal.
10169 (replace-regexp-in-string
10170 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10171 (org-trim description)))))
10172 (format "[[%s]%s]"
10174 (if description (format "[%s]" description) ""))))
10176 (defconst org-link-escape-chars
10177 ;;%20 %5B %5D %25
10178 '(?\s ?\[ ?\] ?%)
10179 "List of characters that should be escaped in a link when stored to Org.
10180 This is the list that is used for internal purposes.")
10182 (defun org-link-escape (text &optional table merge)
10183 "Return percent escaped representation of TEXT.
10184 TEXT is a string with the text to escape.
10185 Optional argument TABLE is a list with characters that should be
10186 escaped. When nil, `org-link-escape-chars' is used.
10187 If optional argument MERGE is set, merge TABLE into
10188 `org-link-escape-chars'."
10189 (let ((characters-to-encode
10190 (cond ((null table) org-link-escape-chars)
10191 (merge (append org-link-escape-chars table))
10192 (t table))))
10193 (mapconcat
10194 (lambda (c)
10195 (if (or (memq c characters-to-encode)
10196 (and org-url-hexify-p (or (< c 32) (> c 126))))
10197 (mapconcat (lambda (e) (format "%%%.2X" e))
10198 (or (encode-coding-char c 'utf-8)
10199 (error "Unable to percent escape character: %c" c))
10201 (char-to-string c)))
10202 text "")))
10204 (defun org-link-unescape (str)
10205 "Unhex hexified Unicode parts in string STR.
10206 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10207 reciprocal of `org-link-escape', which see."
10208 (if (org-string-nw-p str)
10209 (replace-regexp-in-string
10210 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10211 str))
10213 (defun org-link-unescape-compound (hex)
10214 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10215 Note: this function also decodes single byte encodings like
10216 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10217 (save-match-data
10218 (let* ((bytes (cdr (split-string hex "%")))
10219 (ret "")
10220 (eat 0)
10221 (sum 0))
10222 (while bytes
10223 (let* ((val (string-to-number (pop bytes) 16))
10224 (shift-xor
10225 (if (= 0 eat)
10226 (cond
10227 ((>= val 252) (cons 6 252))
10228 ((>= val 248) (cons 5 248))
10229 ((>= val 240) (cons 4 240))
10230 ((>= val 224) (cons 3 224))
10231 ((>= val 192) (cons 2 192))
10232 (t (cons 0 0)))
10233 (cons 6 128))))
10234 (when (>= val 192) (setq eat (car shift-xor)))
10235 (setq val (logxor val (cdr shift-xor)))
10236 (setq sum (+ (lsh sum (car shift-xor)) val))
10237 (when (> eat 0) (setq eat (- eat 1)))
10238 (cond
10239 ((= 0 eat) ;multi byte
10240 (setq ret (concat ret (char-to-string sum)))
10241 (setq sum 0))
10242 ((not bytes) ; single byte(s)
10243 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10244 ret)))
10246 (defun org-link-unescape-single-byte-sequence (hex)
10247 "Unhexify hex-encoded single byte character sequences."
10248 (mapconcat (lambda (byte)
10249 (char-to-string (string-to-number byte 16)))
10250 (cdr (split-string hex "%")) ""))
10252 (defun org-xor (a b)
10253 "Exclusive or."
10254 (if a (not b) b))
10256 (defun org-fixup-message-id-for-http (s)
10257 "Replace special characters in a message id, so it can be used in an http query."
10258 (when (string-match "%" s)
10259 (setq s (mapconcat (lambda (c)
10260 (if (eq c ?%)
10261 "%25"
10262 (char-to-string c)))
10263 s "")))
10264 (while (string-match "<" s)
10265 (setq s (replace-match "%3C" t t s)))
10266 (while (string-match ">" s)
10267 (setq s (replace-match "%3E" t t s)))
10268 (while (string-match "@" s)
10269 (setq s (replace-match "%40" t t s)))
10272 (defun org-link-prettify (link)
10273 "Return a human-readable representation of LINK.
10274 The car of LINK must be a raw link.
10275 The cdr of LINK must be either a link description or nil."
10276 (let ((desc (or (cadr link) "<no description>")))
10277 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10278 "<" (car link) ">")))
10280 ;;;###autoload
10281 (defun org-insert-link-global ()
10282 "Insert a link like Org mode does.
10283 This command can be called in any mode to insert a link in Org syntax."
10284 (interactive)
10285 (org-load-modules-maybe)
10286 (org-run-like-in-org-mode 'org-insert-link))
10288 (defun org-insert-all-links (arg &optional pre post)
10289 "Insert all links in `org-stored-links'.
10290 When a universal prefix, do not delete the links from `org-stored-links'.
10291 When `ARG' is a number, insert the last N link(s).
10292 `PRE' and `POST' are optional arguments to define a string to
10293 prepend or to append."
10294 (interactive "P")
10295 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10296 (links (copy-sequence org-stored-links))
10297 (pr (or pre "- "))
10298 (po (or post "\n"))
10299 (cnt 1) l)
10300 (if (null org-stored-links)
10301 (message "No link to insert")
10302 (while (and (or (listp arg) (>= arg cnt))
10303 (setq l (if (listp arg)
10304 (pop links)
10305 (pop org-stored-links))))
10306 (setq cnt (1+ cnt))
10307 (insert pr)
10308 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10309 (insert po)))))
10311 (defun org-insert-last-stored-link (arg)
10312 "Insert the last link stored in `org-stored-links'."
10313 (interactive "p")
10314 (org-insert-all-links arg "" "\n"))
10316 (defun org-link-fontify-links-to-this-file ()
10317 "Fontify links to the current file in `org-stored-links'."
10318 (let ((f (buffer-file-name)) a b)
10319 (setq a (mapcar (lambda(l)
10320 (let ((ll (car l)))
10321 (when (and (string-match "^file:\\(.+\\)::" ll)
10322 (equal f (expand-file-name (match-string 1 ll))))
10323 ll)))
10324 org-stored-links))
10325 (when (featurep 'org-id)
10326 (setq b (mapcar (lambda(l)
10327 (let ((ll (car l)))
10328 (when (and (string-match "^id:\\(.+\\)$" ll)
10329 (equal f (expand-file-name
10330 (or (org-id-find-id-file
10331 (match-string 1 ll)) ""))))
10332 ll)))
10333 org-stored-links)))
10334 (mapcar (lambda(l)
10335 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10336 (delq nil (append a b)))))
10338 (defvar org--links-history nil)
10339 (defun org-insert-link (&optional complete-file link-location default-description)
10340 "Insert a link. At the prompt, enter the link.
10342 Completion can be used to insert any of the link protocol prefixes in use.
10344 The history can be used to select a link previously stored with
10345 `org-store-link'. When the empty string is entered (i.e. if you just
10346 press `RET' at the prompt), the link defaults to the most recently
10347 stored link. As `SPC' triggers completion in the minibuffer, you need to
10348 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10350 You will also be prompted for a description, and if one is given, it will
10351 be displayed in the buffer instead of the link.
10353 If there is already a link at point, this command will allow you to edit
10354 link and description parts.
10356 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10357 file name can be
10358 selected using completion. The path to the file will be relative to the
10359 current directory if the file is in the current directory or a subdirectory.
10360 Otherwise, the link will be the absolute path as completed in the minibuffer
10361 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10362 option `org-link-file-path-type'.
10364 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10365 absolute path even if the file is in
10366 the current directory or below.
10368 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10369 prefix negates `org-keep-stored-link-after-insertion'.
10371 If `org-make-link-description-function' is non-nil, this function will be
10372 called with the link target, and the result will be the default
10373 link description.
10375 If the LINK-LOCATION parameter is non-nil, this value will be used as
10376 the link location instead of reading one interactively.
10378 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10379 as the default description."
10380 (interactive "P")
10381 (let* ((wcf (current-window-configuration))
10382 (origbuf (current-buffer))
10383 (region (when (org-region-active-p)
10384 (buffer-substring (region-beginning) (region-end))))
10385 (remove (and region (list (region-beginning) (region-end))))
10386 (desc region)
10387 (link link-location)
10388 (abbrevs org-link-abbrev-alist-local)
10389 entry all-prefixes auto-desc)
10390 (cond
10391 (link-location) ; specified by arg, just use it.
10392 ((org-in-regexp org-bracket-link-regexp 1)
10393 ;; We do have a link at point, and we are going to edit it.
10394 (setq remove (list (match-beginning 0) (match-end 0)))
10395 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10396 (setq link (read-string "Link: "
10397 (org-link-unescape
10398 (match-string-no-properties 1)))))
10399 ((or (org-in-regexp org-angle-link-re)
10400 (org-in-regexp org-plain-link-re))
10401 ;; Convert to bracket link
10402 (setq remove (list (match-beginning 0) (match-end 0))
10403 link (read-string "Link: "
10404 (org-unbracket-string "<" ">" (match-string 0)))))
10405 ((member complete-file '((4) (16)))
10406 ;; Completing read for file names.
10407 (setq link (org-file-complete-link complete-file)))
10409 ;; Read link, with completion for stored links.
10410 (org-link-fontify-links-to-this-file)
10411 (org-switch-to-buffer-other-window "*Org Links*")
10412 (with-current-buffer "*Org Links*"
10413 (erase-buffer)
10414 (insert "Insert a link.
10415 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10416 (when org-stored-links
10417 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10418 (insert (mapconcat 'org-link-prettify
10419 (reverse org-stored-links) "\n")))
10420 (goto-char (point-min)))
10421 (let ((cw (selected-window)))
10422 (select-window (get-buffer-window "*Org Links*" 'visible))
10423 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10424 (unless (pos-visible-in-window-p (point-max))
10425 (org-fit-window-to-buffer))
10426 (and (window-live-p cw) (select-window cw)))
10427 (setq all-prefixes (append (mapcar 'car abbrevs)
10428 (mapcar 'car org-link-abbrev-alist)
10429 (org-link-types)))
10430 (unwind-protect
10431 ;; Fake a link history, containing the stored links.
10432 (let ((org--links-history
10433 (append (mapcar #'car org-stored-links)
10434 org-insert-link-history)))
10435 (setq link
10436 (org-completing-read
10437 "Link: "
10438 (append
10439 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10440 (mapcar #'car org-stored-links))
10441 nil nil nil
10442 'org--links-history
10443 (caar org-stored-links)))
10444 (unless (org-string-nw-p link) (user-error "No link selected"))
10445 (dolist (l org-stored-links)
10446 (when (equal link (cadr l))
10447 (setq link (car l))
10448 (setq auto-desc t)))
10449 (when (or (member link all-prefixes)
10450 (and (equal ":" (substring link -1))
10451 (member (substring link 0 -1) all-prefixes)
10452 (setq link (substring link 0 -1))))
10453 (setq link (with-current-buffer origbuf
10454 (org-link-try-special-completion link)))))
10455 (set-window-configuration wcf)
10456 (kill-buffer "*Org Links*"))
10457 (setq entry (assoc link org-stored-links))
10458 (or entry (push link org-insert-link-history))
10459 (setq desc (or desc (nth 1 entry)))))
10461 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10462 (not org-keep-stored-link-after-insertion))
10463 (setq org-stored-links (delq (assoc link org-stored-links)
10464 org-stored-links)))
10466 (when (and (string-match org-plain-link-re link)
10467 (not (string-match org-ts-regexp link)))
10468 ;; URL-like link, normalize the use of angular brackets.
10469 (setq link (org-unbracket-string "<" ">" link)))
10471 ;; Check if we are linking to the current file with a search
10472 ;; option If yes, simplify the link by using only the search
10473 ;; option.
10474 (when (and buffer-file-name
10475 (let ((case-fold-search nil))
10476 (string-match "\\`file:\\(.+?\\)::" link)))
10477 (let ((path (match-string-no-properties 1 link))
10478 (search (substring-no-properties link (match-end 0))))
10479 (save-match-data
10480 (when (equal (file-truename buffer-file-name) (file-truename path))
10481 ;; We are linking to this same file, with a search option
10482 (setq link search)))))
10484 ;; Check if we can/should use a relative path. If yes, simplify the link
10485 (let ((case-fold-search nil))
10486 (when (string-match "\\`\\(file\\|docview\\):" link)
10487 (let* ((type (match-string-no-properties 0 link))
10488 (path (substring-no-properties link (match-end 0)))
10489 (origpath path))
10490 (cond
10491 ((or (eq org-link-file-path-type 'absolute)
10492 (equal complete-file '(16)))
10493 (setq path (abbreviate-file-name (expand-file-name path))))
10494 ((eq org-link-file-path-type 'noabbrev)
10495 (setq path (expand-file-name path)))
10496 ((eq org-link-file-path-type 'relative)
10497 (setq path (file-relative-name path)))
10499 (save-match-data
10500 (if (string-match (concat "^" (regexp-quote
10501 (expand-file-name
10502 (file-name-as-directory
10503 default-directory))))
10504 (expand-file-name path))
10505 ;; We are linking a file with relative path name.
10506 (setq path (substring (expand-file-name path)
10507 (match-end 0)))
10508 (setq path (abbreviate-file-name (expand-file-name path)))))))
10509 (setq link (concat type path))
10510 (when (equal desc origpath)
10511 (setq desc path)))))
10513 (if org-make-link-description-function
10514 (setq desc
10515 (or (condition-case nil
10516 (funcall org-make-link-description-function link desc)
10517 (error (progn (message "Can't get link description from `%s'"
10518 (symbol-name org-make-link-description-function))
10519 (sit-for 2) nil)))
10520 (read-string "Description: " default-description)))
10521 (if default-description (setq desc default-description)
10522 (setq desc (or (and auto-desc desc)
10523 (read-string "Description: " desc)))))
10525 (unless (string-match "\\S-" desc) (setq desc nil))
10526 (when remove (apply 'delete-region remove))
10527 (insert (org-make-link-string link desc))
10528 ;; Redisplay so as the new link has proper invisible characters.
10529 (sit-for 0)))
10531 (defun org-link-try-special-completion (type)
10532 "If there is completion support for link type TYPE, offer it."
10533 (let ((fun (org-link-get-parameter type :complete)))
10534 (if (functionp fun)
10535 (funcall fun)
10536 (read-string "Link (no completion support): " (concat type ":")))))
10538 (defun org-file-complete-link (&optional arg)
10539 "Create a file link using completion."
10540 (let ((file (read-file-name "File: "))
10541 (pwd (file-name-as-directory (expand-file-name ".")))
10542 (pwd1 (file-name-as-directory (abbreviate-file-name
10543 (expand-file-name ".")))))
10544 (cond ((equal arg '(16))
10545 (concat "file:"
10546 (abbreviate-file-name (expand-file-name file))))
10547 ((string-match
10548 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10549 (concat "file:" (match-string 1 file)))
10550 ((string-match
10551 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10552 (expand-file-name file))
10553 (concat "file:"
10554 (match-string 1 (expand-file-name file))))
10555 (t (concat "file:" file)))))
10557 (defun org-completing-read (&rest args)
10558 "Completing-read with SPACE being a normal character."
10559 (let ((enable-recursive-minibuffers t)
10560 (minibuffer-local-completion-map
10561 (copy-keymap minibuffer-local-completion-map)))
10562 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10563 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10564 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10565 'org-time-stamp-inactive)
10566 (apply #'completing-read args)))
10568 ;;; Opening/following a link
10570 (defvar org-link-search-failed nil)
10572 (defvar org-open-link-functions nil
10573 "Hook for functions finding a plain text link.
10574 These functions must take a single argument, the link content.
10575 They will be called for links that look like [[link text][description]]
10576 when LINK TEXT does not have a protocol like \"http:\" and does not look
10577 like a filename (e.g. \"./blue.png\").
10579 These functions will be called *before* Org attempts to resolve the
10580 link by doing text searches in the current buffer - so if you want a
10581 link \"[[target]]\" to still find \"<<target>>\", your function should
10582 handle this as a special case.
10584 When the function does handle the link, it must return a non-nil value.
10585 If it decides that it is not responsible for this link, it must return
10586 nil to indicate that that Org can continue with other options like
10587 exact and fuzzy text search.")
10589 (defun org-next-link (&optional search-backward)
10590 "Move forward to the next link.
10591 If the link is in hidden text, expose it."
10592 (interactive "P")
10593 (when (and org-link-search-failed (eq this-command last-command))
10594 (goto-char (point-min))
10595 (message "Link search wrapped back to beginning of buffer"))
10596 (setq org-link-search-failed nil)
10597 (let* ((pos (point))
10598 (ct (org-context))
10599 (a (assq :link ct))
10600 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10601 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10602 ((looking-at org-any-link-re)
10603 ;; Don't stay stuck at link without an org-link face
10604 (forward-char (if search-backward -1 1))))
10605 (if (funcall srch-fun org-any-link-re nil t)
10606 (progn
10607 (goto-char (match-beginning 0))
10608 (when (org-invisible-p) (org-show-context)))
10609 (goto-char pos)
10610 (setq org-link-search-failed t)
10611 (message "No further link found"))))
10613 (defun org-previous-link ()
10614 "Move backward to the previous link.
10615 If the link is in hidden text, expose it."
10616 (interactive)
10617 (funcall 'org-next-link t))
10619 (defun org-translate-link (s)
10620 "Translate a link string if a translation function has been defined."
10621 (with-temp-buffer
10622 (insert (org-trim s))
10623 (org-trim (org-element-interpret-data (org-element-context)))))
10625 (defun org-translate-link-from-planner (type path)
10626 "Translate a link from Emacs Planner syntax so that Org can follow it.
10627 This is still an experimental function, your mileage may vary."
10628 (cond
10629 ((member type '("http" "https" "news" "ftp"))
10630 ;; standard Internet links are the same.
10631 nil)
10632 ((and (equal type "irc") (string-match "^//" path))
10633 ;; Planner has two / at the beginning of an irc link, we have 1.
10634 ;; We should have zero, actually....
10635 (setq path (substring path 1)))
10636 ((and (equal type "lisp") (string-match "^/" path))
10637 ;; Planner has a slash, we do not.
10638 (setq type "elisp" path (substring path 1)))
10639 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10640 ;; A typical message link. Planner has the id after the final slash,
10641 ;; we separate it with a hash mark
10642 (setq path (concat (match-string 1 path) "#"
10643 (org-unbracket-string "<" ">" (match-string 2 path))))))
10644 (cons type path))
10646 (defun org-find-file-at-mouse (ev)
10647 "Open file link or URL at mouse."
10648 (interactive "e")
10649 (mouse-set-point ev)
10650 (org-open-at-point 'in-emacs))
10652 (defun org-open-at-mouse (ev)
10653 "Open file link or URL at mouse.
10654 See the docstring of `org-open-file' for details."
10655 (interactive "e")
10656 (mouse-set-point ev)
10657 (when (eq major-mode 'org-agenda-mode)
10658 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10659 (org-open-at-point))
10661 (defvar org-window-config-before-follow-link nil
10662 "The window configuration before following a link.
10663 This is saved in case the need arises to restore it.")
10665 ;;;###autoload
10666 (defun org-open-at-point-global ()
10667 "Follow a link or time-stamp like Org mode does.
10668 This command can be called in any mode to follow an external link
10669 or a time-stamp that has Org mode syntax. Its behavior is
10670 undefined when called on internal links (e.g., fuzzy links).
10671 Raise an error when there is nothing to follow. "
10672 (interactive)
10673 (cond ((org-in-regexp org-any-link-re)
10674 (org-open-link-from-string (match-string-no-properties 0)))
10675 ((or (org-in-regexp org-ts-regexp-both nil t)
10676 (org-in-regexp org-tsr-regexp-both nil t))
10677 (org-follow-timestamp-link))
10678 (t (user-error "No link found"))))
10680 ;;;###autoload
10681 (defun org-open-link-from-string (s &optional arg reference-buffer)
10682 "Open a link in the string S, as if it was in Org mode."
10683 (interactive "sLink: \nP")
10684 (let ((reference-buffer (or reference-buffer (current-buffer))))
10685 (with-temp-buffer
10686 (let ((org-inhibit-startup (not reference-buffer)))
10687 (org-mode)
10688 (insert s)
10689 (goto-char (point-min))
10690 (when reference-buffer
10691 (setq org-link-abbrev-alist-local
10692 (with-current-buffer reference-buffer
10693 org-link-abbrev-alist-local)))
10694 (org-open-at-point arg reference-buffer)))))
10696 (defvar org-open-at-point-functions nil
10697 "Hook that is run when following a link at point.
10699 Functions in this hook must return t if they identify and follow
10700 a link at point. If they don't find anything interesting at point,
10701 they must return nil.")
10703 (defvar org-link-search-inhibit-query nil)
10704 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10705 (defun org--open-doi-link (path)
10706 "Open a \"doi\" type link.
10707 PATH is a the path to search for, as a string."
10708 (browse-url (url-encode-url (concat org-doi-server-url path))))
10710 (defun org--open-elisp-link (path)
10711 "Open a \"elisp\" type link.
10712 PATH is the sexp to evaluate, as a string."
10713 (let ((cmd path))
10714 (if (or (and (org-string-nw-p
10715 org-confirm-elisp-link-not-regexp)
10716 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10717 (not org-confirm-elisp-link-function)
10718 (funcall org-confirm-elisp-link-function
10719 (format "Execute \"%s\" as elisp? "
10720 (org-add-props cmd nil 'face 'org-warning))))
10721 (message "%s => %s" cmd
10722 (if (eq (string-to-char cmd) ?\()
10723 (eval (read cmd))
10724 (call-interactively (read cmd))))
10725 (user-error "Abort"))))
10727 (defun org--open-help-link (path)
10728 "Open a \"help\" type link.
10729 PATH is a symbol name, as a string."
10730 (pcase (intern path)
10731 ((and (pred fboundp) variable) (describe-function variable))
10732 ((and (pred boundp) function) (describe-variable function))
10733 (name (user-error "Unknown function or variable: %s" name))))
10735 (defun org--open-shell-link (path)
10736 "Open a \"shell\" type link.
10737 PATH is the command to execute, as a string."
10738 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10739 (cmd path))
10740 (if (or (and (org-string-nw-p
10741 org-confirm-shell-link-not-regexp)
10742 (string-match
10743 org-confirm-shell-link-not-regexp cmd))
10744 (not org-confirm-shell-link-function)
10745 (funcall org-confirm-shell-link-function
10746 (format "Execute \"%s\" in shell? "
10747 (org-add-props cmd nil
10748 'face 'org-warning))))
10749 (progn
10750 (message "Executing %s" cmd)
10751 (shell-command cmd buf)
10752 (when (featurep 'midnight)
10753 (setq clean-buffer-list-kill-buffer-names
10754 (cons (buffer-name buf)
10755 clean-buffer-list-kill-buffer-names))))
10756 (user-error "Abort"))))
10758 (defun org-open-at-point (&optional arg reference-buffer)
10759 "Open link, timestamp, footnote or tags at point.
10761 When point is on a link, follow it. Normally, files will be
10762 opened by an appropriate application. If the optional prefix
10763 argument ARG is non-nil, Emacs will visit the file. With
10764 a double prefix argument, try to open outside of Emacs, in the
10765 application the system uses for this file type.
10767 When point is on a timestamp, open the agenda at the day
10768 specified.
10770 When point is a footnote definition, move to the first reference
10771 found. If it is on a reference, move to the associated
10772 definition.
10774 When point is on a headline, display a list of every link in the
10775 entry, so it is possible to pick one, or all, of them. If point
10776 is on a tag, call `org-tags-view' instead.
10778 When optional argument REFERENCE-BUFFER is non-nil, it should
10779 specify a buffer from where the link search should happen. This
10780 is used internally by `org-open-link-from-string'.
10782 On top of syntactically correct links, this function will also
10783 try to open links and time-stamps in comments, example
10784 blocks... i.e., whenever point is on something looking like
10785 a timestamp or a link."
10786 (interactive "P")
10787 ;; On a code block, open block's results.
10788 (unless (call-interactively 'org-babel-open-src-block-result)
10789 (org-load-modules-maybe)
10790 (setq org-window-config-before-follow-link (current-window-configuration))
10791 (org-remove-occur-highlights nil nil t)
10792 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10793 (let* ((context
10794 ;; Only consider supported types, even if they are not
10795 ;; the closest one.
10796 (org-element-lineage
10797 (org-element-context)
10798 '(clock footnote-definition footnote-reference headline
10799 inlinetask link timestamp)
10801 (type (org-element-type context))
10802 (value (org-element-property :value context)))
10803 (cond
10804 ;; On a headline or an inlinetask, but not on a timestamp,
10805 ;; a link, a footnote reference or on tags.
10806 ((and (memq type '(headline inlinetask))
10807 ;; Not on tags.
10808 (let ((case-fold-search nil))
10809 (and (org-match-line org-complex-heading-regexp)
10810 (or (not (match-beginning 5))
10811 (< (point) (match-beginning 5))))))
10812 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10813 (links (car data))
10814 (links-end (cdr data)))
10815 (if links
10816 (dolist (link (if (stringp links) (list links) links))
10817 (search-forward link nil links-end)
10818 (goto-char (match-beginning 0))
10819 (org-open-at-point))
10820 (require 'org-attach)
10821 (org-attach-reveal 'if-exists))))
10822 ;; On a footnote reference or at definition's label.
10823 ((or (eq type 'footnote-reference)
10824 (and (eq type 'footnote-definition)
10825 (save-excursion
10826 ;; Do not validate action when point is on the
10827 ;; spaces right after the footnote label, in
10828 ;; order to be on par with behaviour on links.
10829 (skip-chars-forward " \t")
10830 (let ((begin
10831 (org-element-property :contents-begin context)))
10832 (if begin (< (point) begin)
10833 (= (org-element-property :post-affiliated context)
10834 (line-beginning-position)))))))
10835 (org-footnote-action))
10836 ;; No valid context. Ignore catch-all types like `headline'.
10837 ;; If point is on something looking like a link or
10838 ;; a time-stamp, try opening it. It may be useful in
10839 ;; comments, example blocks...
10840 ((memq type '(footnote-definition headline inlinetask nil))
10841 (call-interactively #'org-open-at-point-global))
10842 ;; On a clock line, make sure point is on the timestamp
10843 ;; before opening it.
10844 ((and (eq type 'clock)
10845 value
10846 (>= (point) (org-element-property :begin value))
10847 (<= (point) (org-element-property :end value)))
10848 (org-follow-timestamp-link))
10849 ;; Do nothing on white spaces after an object.
10850 ((>= (point)
10851 (save-excursion
10852 (goto-char (org-element-property :end context))
10853 (skip-chars-backward " \t")
10854 (point)))
10855 (user-error "No link found"))
10856 ((eq type 'timestamp) (org-follow-timestamp-link))
10857 ;; On tags within a headline or an inlinetask.
10858 ((and (memq type '(headline inlinetask))
10859 (let ((case-fold-search nil))
10860 (save-excursion (beginning-of-line)
10861 (looking-at org-complex-heading-regexp))
10862 (and (match-beginning 5)
10863 (>= (point) (match-beginning 5)))))
10864 (org-tags-view arg (substring (match-string 5) 0 -1)))
10865 ((eq type 'link)
10866 ;; When link is located within the description of another
10867 ;; link (e.g., an inline image), always open the parent
10868 ;; link.
10869 (let* ((link (let ((up (org-element-property :parent context)))
10870 (if (eq (org-element-type up) 'link) up context)))
10871 (type (org-element-property :type link))
10872 (path (org-link-unescape (org-element-property :path link))))
10873 ;; Switch back to REFERENCE-BUFFER needed when called in
10874 ;; a temporary buffer through `org-open-link-from-string'.
10875 (with-current-buffer (or reference-buffer (current-buffer))
10876 (cond
10877 ((equal type "file")
10878 (if (string-match "[*?{]" (file-name-nondirectory path))
10879 (dired path)
10880 ;; Look into `org-link-parameters' in order to find
10881 ;; a DEDICATED-FUNCTION to open file. The function
10882 ;; will be applied on raw link instead of parsed
10883 ;; link due to the limitation in `org-add-link-type'
10884 ;; ("open" function called with a single argument).
10885 ;; If no such function is found, fallback to
10886 ;; `org-open-file'.
10887 (let* ((option (org-element-property :search-option link))
10888 (app (org-element-property :application link))
10889 (dedicated-function
10890 (org-link-get-parameter
10891 (if app (concat type "+" app) type)
10892 :follow)))
10893 (if dedicated-function
10894 (funcall dedicated-function
10895 (concat path
10896 (and option (concat "::" option))))
10897 (apply #'org-open-file
10898 path
10899 (cond (arg)
10900 ((equal app "emacs") 'emacs)
10901 ((equal app "sys") 'system))
10902 (cond ((not option) nil)
10903 ((string-match-p "\\`[0-9]+\\'" option)
10904 (list (string-to-number option)))
10905 (t (list nil
10906 (org-link-unescape option)))))))))
10907 ((functionp (org-link-get-parameter type :follow))
10908 (funcall (org-link-get-parameter type :follow) path))
10909 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10910 (unless (run-hook-with-args-until-success
10911 'org-open-link-functions path)
10912 (if (not arg) (org-mark-ring-push)
10913 (switch-to-buffer-other-window
10914 (org-get-buffer-for-internal-link (current-buffer))))
10915 (let ((destination
10916 (org-with-wide-buffer
10917 (if (equal type "radio")
10918 (org-search-radio-target
10919 (org-element-property :path link))
10920 (org-link-search
10921 (if (member type '("custom-id" "coderef"))
10922 (org-element-property :raw-link link)
10923 path)
10924 ;; Prevent fuzzy links from matching
10925 ;; themselves.
10926 (and (equal type "fuzzy")
10927 (+ 2 (org-element-property :begin link)))))
10928 (point))))
10929 (unless (and (<= (point-min) destination)
10930 (>= (point-max) destination))
10931 (widen))
10932 (goto-char destination))))
10933 (t (browse-url-at-point))))))
10934 (t (user-error "No link found")))))
10935 (run-hook-with-args 'org-follow-link-hook)))
10937 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10938 "Offer links in the current entry and return the selected link.
10939 If there is only one link, return it.
10940 If NTH is an integer, return the NTH link found.
10941 If ZERO is a string, check also this string for a link, and if
10942 there is one, return it."
10943 (with-current-buffer buffer
10944 (org-with-wide-buffer
10945 (goto-char marker)
10946 (let ((cnt ?0)
10947 have-zero end links link c)
10948 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10949 (push (match-string 0 zero) links)
10950 (setq cnt (1- cnt) have-zero t))
10951 (save-excursion
10952 (org-back-to-heading t)
10953 (setq end (save-excursion (outline-next-heading) (point)))
10954 (while (re-search-forward org-any-link-re end t)
10955 (push (match-string 0) links))
10956 (setq links (org-uniquify (reverse links))))
10957 (cond
10958 ((null links)
10959 (message "No links"))
10960 ((equal (length links) 1)
10961 (setq link (car links)))
10962 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10963 (setq link (nth (if have-zero nth (1- nth)) links)))
10964 (t ; we have to select a link
10965 (save-excursion
10966 (save-window-excursion
10967 (delete-other-windows)
10968 (with-output-to-temp-buffer "*Select Link*"
10969 (dolist (l links)
10970 (cond
10971 ((not (string-match org-bracket-link-regexp l))
10972 (princ (format "[%c] %s\n" (cl-incf cnt)
10973 (org-unbracket-string "<" ">" l))))
10974 ((match-end 3)
10975 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10976 (match-string 3 l) (match-string 1 l))))
10977 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10978 (match-string 1 l)))))))
10979 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10980 (message "Select link to open, RET to open all:")
10981 (setq c (read-char-exclusive))
10982 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10983 (when (equal c ?q) (user-error "Abort"))
10984 (if (equal c ?\C-m)
10985 (setq link links)
10986 (setq nth (- c ?0))
10987 (when have-zero (setq nth (1+ nth)))
10988 (unless (and (integerp nth) (>= (length links) nth))
10989 (user-error "Invalid link selection"))
10990 (setq link (nth (1- nth) links)))))
10991 (cons link end)))))
10993 ;; TODO: These functions are deprecated since `org-open-at-point'
10994 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10995 (defun org-open-file-with-system (path)
10996 "Open file at PATH using the system way of opening it."
10997 (org-open-file path 'system))
10998 (defun org-open-file-with-emacs (path)
10999 "Open file at PATH in Emacs."
11000 (org-open-file path 'emacs))
11003 ;;; File search
11005 (defvar org-create-file-search-functions nil
11006 "List of functions to construct the right search string for a file link.
11007 These functions are called in turn with point at the location to
11008 which the link should point.
11010 A function in the hook should first test if it would like to
11011 handle this file type, for example by checking the `major-mode'
11012 or the file extension. If it decides not to handle this file, it
11013 should just return nil to give other functions a chance. If it
11014 does handle the file, it must return the search string to be used
11015 when following the link. The search string will be part of the
11016 file link, given after a double colon, and `org-open-at-point'
11017 will automatically search for it. If special measures must be
11018 taken to make the search successful, another function should be
11019 added to the companion hook `org-execute-file-search-functions',
11020 which see.
11022 A function in this hook may also use `setq' to set the variable
11023 `description' to provide a suggestion for the descriptive text to
11024 be used for this link when it gets inserted into an Org buffer
11025 with \\[org-insert-link].")
11027 (defvar org-execute-file-search-functions nil
11028 "List of functions to execute a file search triggered by a link.
11030 Functions added to this hook must accept a single argument, the
11031 search string that was part of the file link, the part after the
11032 double colon. The function must first check if it would like to
11033 handle this search, for example by checking the `major-mode' or
11034 the file extension. If it decides not to handle this search, it
11035 should just return nil to give other functions a chance. If it
11036 does handle the search, it must return a non-nil value to keep
11037 other functions from trying.
11039 Each function can access the current prefix argument through the
11040 variable `current-prefix-arg'. Note that a single prefix is used
11041 to force opening a link in Emacs, so it may be good to only use a
11042 numeric or double prefix to guide the search function.
11044 In case this is needed, a function in this hook can also restore
11045 the window configuration before `org-open-at-point' was called using:
11047 (set-window-configuration org-window-config-before-follow-link)")
11049 (defun org-search-radio-target (target)
11050 "Search a radio target matching TARGET in current buffer.
11051 White spaces are not significant."
11052 (let ((re (format "<<<%s>>>"
11053 (mapconcat #'regexp-quote
11054 (org-split-string target "[ \t\n]+")
11055 "[ \t]+\\(?:\n[ \t]*\\)?")))
11056 (origin (point)))
11057 (goto-char (point-min))
11058 (catch :radio-match
11059 (while (re-search-forward re nil t)
11060 (backward-char)
11061 (let ((object (org-element-context)))
11062 (when (eq (org-element-type object) 'radio-target)
11063 (goto-char (org-element-property :begin object))
11064 (org-show-context 'link-search)
11065 (throw :radio-match nil))))
11066 (goto-char origin)
11067 (user-error "No match for radio target: %s" target))))
11069 (defun org-link-search (s &optional avoid-pos stealth)
11070 "Search for a search string S.
11072 If S starts with \"#\", it triggers a custom ID search.
11074 If S is enclosed within parenthesis, it initiates a coderef
11075 search.
11077 If S is surrounded by forward slashes, it is interpreted as
11078 a regular expression. In Org mode files, this will create an
11079 `org-occur' sparse tree. In ordinary files, `occur' will be used
11080 to list matches. If the current buffer is in `dired-mode', grep
11081 will be used to search in all files.
11083 When AVOID-POS is given, ignore matches near that position.
11085 When optional argument STEALTH is non-nil, do not modify
11086 visibility around point, thus ignoring `org-show-context-detail'
11087 variable.
11089 Search is case-insensitive and ignores white spaces. Return type
11090 of matched result, which is either `dedicated' or `fuzzy'."
11091 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11092 (let* ((case-fold-search t)
11093 (origin (point))
11094 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11095 (starred (eq (string-to-char normalized) ?*))
11096 (words (split-string (if starred (substring s 1) s)))
11097 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
11098 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11099 type)
11100 (cond
11101 ;; Check if there are any special search functions.
11102 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11103 ((eq (string-to-char s) ?#)
11104 ;; Look for a custom ID S if S starts with "#".
11105 (let* ((id (substring normalized 1))
11106 (match (org-find-property "CUSTOM_ID" id)))
11107 (if match (progn (goto-char match) (setf type 'dedicated))
11108 (error "No match for custom ID: %s" id))))
11109 ((string-match "\\`(\\(.*\\))\\'" normalized)
11110 ;; Look for coderef targets if S is enclosed within parenthesis.
11111 (let ((coderef (match-string-no-properties 1 normalized))
11112 (re (substring s-single-re 1 -1)))
11113 (goto-char (point-min))
11114 (catch :coderef-match
11115 (while (re-search-forward re nil t)
11116 (let ((element (org-element-at-point)))
11117 (when (and (memq (org-element-type element)
11118 '(example-block src-block))
11119 ;; Build proper regexp according to current
11120 ;; block's label format.
11121 (let ((label-fmt
11122 (regexp-quote
11123 (or (org-element-property :label-fmt element)
11124 org-coderef-label-format))))
11125 (save-excursion
11126 (beginning-of-line)
11127 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11128 (format label-fmt coderef))))))
11129 (setq type 'dedicated)
11130 (goto-char (match-beginning 1))
11131 (throw :coderef-match nil))))
11132 (goto-char origin)
11133 (error "No match for coderef: %s" coderef))))
11134 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11135 ;; Look for a regular expression.
11136 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11137 (match-string 1 s)))
11138 ;; From here, we handle fuzzy links.
11140 ;; Look for targets, only if not in a headline search.
11141 ((and (not starred)
11142 (let ((target (format "<<%s>>" s-multi-re)))
11143 (catch :target-match
11144 (goto-char (point-min))
11145 (while (re-search-forward target nil t)
11146 (backward-char)
11147 (let ((context (org-element-context)))
11148 (when (eq (org-element-type context) 'target)
11149 (setq type 'dedicated)
11150 (goto-char (org-element-property :begin context))
11151 (throw :target-match t))))
11152 nil))))
11153 ;; Look for elements named after S, only if not in a headline
11154 ;; search.
11155 ((and (not starred)
11156 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11157 (catch :name-match
11158 (goto-char (point-min))
11159 (while (re-search-forward name nil t)
11160 (let ((element (org-element-at-point)))
11161 (when (equal words
11162 (split-string
11163 (org-element-property :name element)))
11164 (setq type 'dedicated)
11165 (beginning-of-line)
11166 (throw :name-match t))))
11167 nil))))
11168 ;; Regular text search. Prefer headlines in Org mode buffers.
11169 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11170 ;; statistics cookies and tags.
11171 ((and (derived-mode-p 'org-mode)
11172 (let ((title-re
11173 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11174 org-outline-regexp-bol
11175 org-comment-string
11176 (mapconcat #'regexp-quote words ".+")))
11177 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11178 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11179 (goto-char (point-min))
11180 (catch :found
11181 (while (re-search-forward title-re nil t)
11182 (when (equal words
11183 (split-string
11184 (replace-regexp-in-string
11185 cookie-re ""
11186 (replace-regexp-in-string
11187 comment-re "" (org-get-heading t t)))))
11188 (throw :found t)))
11189 nil)))
11190 (beginning-of-line)
11191 (setq type 'dedicated))
11192 ;; Offer to create non-existent headline depending on
11193 ;; `org-link-search-must-match-exact-headline'.
11194 ((and (derived-mode-p 'org-mode)
11195 (not org-link-search-inhibit-query)
11196 (eq org-link-search-must-match-exact-headline 'query-to-create)
11197 (yes-or-no-p "No match - create this as a new heading? "))
11198 (goto-char (point-max))
11199 (unless (bolp) (newline))
11200 (org-insert-heading nil t t)
11201 (insert s "\n")
11202 (beginning-of-line 0))
11203 ;; Only headlines are looked after. No need to process
11204 ;; further: throw an error.
11205 ((and (derived-mode-p 'org-mode)
11206 (or starred org-link-search-must-match-exact-headline))
11207 (goto-char origin)
11208 (error "No match for fuzzy expression: %s" normalized))
11209 ;; Regular text search.
11210 ((catch :fuzzy-match
11211 (goto-char (point-min))
11212 (while (re-search-forward s-multi-re nil t)
11213 ;; Skip match if it contains AVOID-POS or it is included in
11214 ;; a link with a description but outside the description.
11215 (unless (or (and avoid-pos
11216 (<= (match-beginning 0) avoid-pos)
11217 (> (match-end 0) avoid-pos))
11218 (and (save-match-data
11219 (org-in-regexp org-bracket-link-regexp))
11220 (match-beginning 3)
11221 (or (> (match-beginning 3) (point))
11222 (<= (match-end 3) (point)))
11223 (org-element-lineage
11224 (save-match-data (org-element-context))
11225 '(link) t)))
11226 (goto-char (match-beginning 0))
11227 (setq type 'fuzzy)
11228 (throw :fuzzy-match t)))
11229 nil))
11230 ;; All failed. Throw an error.
11231 (t (goto-char origin)
11232 (error "No match for fuzzy expression: %s" normalized)))
11233 ;; Disclose surroundings of match, if appropriate.
11234 (when (and (derived-mode-p 'org-mode) (not stealth))
11235 (org-show-context 'link-search))
11236 type))
11238 (defun org-get-buffer-for-internal-link (buffer)
11239 "Return a buffer to be used for displaying the link target of internal links."
11240 (cond
11241 ((not org-display-internal-link-with-indirect-buffer)
11242 buffer)
11243 ((string-suffix-p "(Clone)" (buffer-name buffer))
11244 (message "Buffer is already a clone, not making another one")
11245 ;; we also do not modify visibility in this case
11246 buffer)
11247 (t ; make a new indirect buffer for displaying the link
11248 (let* ((bn (buffer-name buffer))
11249 (ibn (concat bn "(Clone)"))
11250 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11251 (with-current-buffer ib (org-overview))
11252 ib))))
11254 (defun org-do-occur (regexp &optional cleanup)
11255 "Call the Emacs command `occur'.
11256 If CLEANUP is non-nil, remove the printout of the regular expression
11257 in the *Occur* buffer. This is useful if the regex is long and not useful
11258 to read."
11259 (occur regexp)
11260 (when cleanup
11261 (let ((cwin (selected-window)) win beg end)
11262 (when (setq win (get-buffer-window "*Occur*"))
11263 (select-window win))
11264 (goto-char (point-min))
11265 (when (re-search-forward "match[a-z]+" nil t)
11266 (setq beg (match-end 0))
11267 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11268 (setq end (1- (match-beginning 0)))))
11269 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11270 (goto-char (point-min))
11271 (select-window cwin))))
11273 ;;; The mark ring for links jumps
11275 (defvar org-mark-ring nil
11276 "Mark ring for positions before jumps in Org mode.")
11277 (defvar org-mark-ring-last-goto nil
11278 "Last position in the mark ring used to go back.")
11279 ;; Fill and close the ring
11280 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11281 (dotimes (_ org-mark-ring-length)
11282 (push (make-marker) org-mark-ring))
11283 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11284 org-mark-ring)
11286 (defun org-mark-ring-push (&optional pos buffer)
11287 "Put the current position or POS into the mark ring and rotate it."
11288 (interactive)
11289 (setq pos (or pos (point)))
11290 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11291 (move-marker (car org-mark-ring)
11292 (or pos (point))
11293 (or buffer (current-buffer)))
11294 (message "%s"
11295 (substitute-command-keys
11296 "Position saved to mark ring, go back with \
11297 `\\[org-mark-ring-goto]'.")))
11299 (defun org-mark-ring-goto (&optional n)
11300 "Jump to the previous position in the mark ring.
11301 With prefix arg N, jump back that many stored positions. When
11302 called several times in succession, walk through the entire ring.
11303 Org mode commands jumping to a different position in the current file,
11304 or to another Org file, automatically push the old position onto the ring."
11305 (interactive "p")
11306 (let (p m)
11307 (if (eq last-command this-command)
11308 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11309 (setq p org-mark-ring))
11310 (setq org-mark-ring-last-goto p)
11311 (setq m (car p))
11312 (pop-to-buffer-same-window (marker-buffer m))
11313 (goto-char m)
11314 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11316 (defun org-add-angle-brackets (s)
11317 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11318 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11321 ;;; Following specific links
11323 (defvar org-agenda-buffer-tmp-name)
11324 (defvar org-agenda-start-on-weekday)
11325 (defun org-follow-timestamp-link ()
11326 "Open an agenda view for the time-stamp date/range at point."
11327 (cond
11328 ((org-at-date-range-p t)
11329 (let ((org-agenda-start-on-weekday)
11330 (t1 (match-string 1))
11331 (t2 (match-string 2)) tt1 tt2)
11332 (setq tt1 (time-to-days (org-time-string-to-time t1))
11333 tt2 (time-to-days (org-time-string-to-time t2)))
11334 (let ((org-agenda-buffer-tmp-name
11335 (format "*Org Agenda(a:%s)"
11336 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11337 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11338 ((org-at-timestamp-p t)
11339 (let ((org-agenda-buffer-tmp-name
11340 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11341 (org-agenda-list nil (time-to-days (org-time-string-to-time
11342 (substring (match-string 1) 0 10)))
11343 1)))
11344 (t (error "This should not happen"))))
11347 ;;; Following file links
11348 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11349 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11350 (declare-function mailcap-mime-info
11351 "mailcap" (string &optional request no-decode))
11352 (defvar org-wait nil)
11353 (defun org-open-file (path &optional in-emacs line search)
11354 "Open the file at PATH.
11355 First, this expands any special file name abbreviations. Then the
11356 configuration variable `org-file-apps' is checked if it contains an
11357 entry for this file type, and if yes, the corresponding command is launched.
11359 If no application is found, Emacs simply visits the file.
11361 With optional prefix argument IN-EMACS, Emacs will visit the file.
11362 With a double \\[universal-argument] \\[universal-argument] \
11363 prefix arg, Org tries to avoid opening in Emacs
11364 and to use an external application to visit the file.
11366 Optional LINE specifies a line to go to, optional SEARCH a string
11367 to search for. If LINE or SEARCH is given, the file will be
11368 opened in Emacs, unless an entry from org-file-apps that makes
11369 use of groups in a regexp matches.
11371 If you want to change the way frames are used when following a
11372 link, please customize `org-link-frame-setup'.
11374 If the file does not exist, an error is thrown."
11375 (let* ((file (if (equal path "")
11376 buffer-file-name
11377 (substitute-in-file-name (expand-file-name path))))
11378 (file-apps (append org-file-apps (org-default-apps)))
11379 (apps (cl-remove-if
11380 'org-file-apps-entry-match-against-dlink-p file-apps))
11381 (apps-dlink (cl-remove-if-not
11382 'org-file-apps-entry-match-against-dlink-p file-apps))
11383 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11384 (dirp (unless remp (file-directory-p file)))
11385 (file (if (and dirp org-open-directory-means-index-dot-org)
11386 (concat (file-name-as-directory file) "index.org")
11387 file))
11388 (a-m-a-p (assq 'auto-mode apps))
11389 (dfile (downcase file))
11390 ;; Reconstruct the original link from the PATH, LINE and
11391 ;; SEARCH args.
11392 (link (cond (line (concat file "::" (number-to-string line)))
11393 (search (concat file "::" search))
11394 (t file)))
11395 (dlink (downcase link))
11396 (old-buffer (current-buffer))
11397 (old-pos (point))
11398 (old-mode major-mode)
11399 (ext
11400 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11401 (match-string 1 dfile)))
11402 cmd link-match-data)
11403 (cond
11404 ((member in-emacs '((16) system))
11405 (setq cmd (cdr (assq 'system apps))))
11406 (in-emacs (setq cmd 'emacs))
11408 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11409 (and dirp (cdr (assq 'directory apps)))
11410 ;; First, try matching against apps-dlink if we
11411 ;; get a match here, store the match data for
11412 ;; later.
11413 (let ((match (assoc-default dlink apps-dlink
11414 'string-match)))
11415 (if match
11416 (progn (setq link-match-data (match-data))
11417 match)
11418 (progn (setq in-emacs (or in-emacs line search))
11419 nil))) ; if we have no match in apps-dlink,
11420 ; always open the file in emacs if line or search
11421 ; is given (for backwards compatibility)
11422 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11423 'string-match)
11424 (cdr (assoc ext apps))
11425 (cdr (assq t apps))))))
11426 (when (eq cmd 'system)
11427 (setq cmd (cdr (assq 'system apps))))
11428 (when (eq cmd 'default)
11429 (setq cmd (cdr (assoc t apps))))
11430 (when (eq cmd 'mailcap)
11431 (require 'mailcap)
11432 (mailcap-parse-mailcaps)
11433 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11434 (command (mailcap-mime-info mime-type)))
11435 (if (stringp command)
11436 (setq cmd command)
11437 (setq cmd 'emacs))))
11438 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11439 (not (file-exists-p file))
11440 (not org-open-non-existing-files))
11441 (user-error "No such file: %s" file))
11442 (cond
11443 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11444 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11445 (while (string-match "['\"]%s['\"]" cmd)
11446 (setq cmd (replace-match "%s" t t cmd)))
11447 (setq cmd (replace-regexp-in-string
11448 "%s"
11449 (shell-quote-argument (convert-standard-filename file))
11451 nil t))
11453 ;; Replace "%1", "%2" etc. in command with group matches from regex
11454 (save-match-data
11455 (let ((match-index 1)
11456 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11457 (set-match-data link-match-data)
11458 (while (<= match-index number-of-groups)
11459 (let ((regex (concat "%" (number-to-string match-index)))
11460 (replace-with (match-string match-index dlink)))
11461 (while (string-match regex cmd)
11462 (setq cmd (replace-match replace-with t t cmd))))
11463 (setq match-index (+ match-index 1)))))
11465 (save-window-excursion
11466 (message "Running %s...done" cmd)
11467 (start-process-shell-command cmd nil cmd)
11468 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11469 ((or (stringp cmd)
11470 (eq cmd 'emacs))
11471 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11472 (widen)
11473 (cond (line (org-goto-line line)
11474 (when (derived-mode-p 'org-mode) (org-reveal)))
11475 (search (org-link-search search))))
11476 ((functionp cmd)
11477 (save-match-data
11478 (set-match-data link-match-data)
11479 (condition-case nil
11480 (funcall cmd file link)
11481 ;; FIXME: Remove this check when most default installations
11482 ;; of Emacs have at least Org 9.0.
11483 ((debug wrong-number-of-arguments wrong-type-argument
11484 invalid-function)
11485 (user-error "Please see Org News for version 9.0 about \
11486 `org-file-apps'--Lisp error: %S" cmd)))))
11487 ((consp cmd)
11488 ;; FIXME: Remove this check when most default installations of
11489 ;; Emacs have at least Org 9.0.
11490 ;; Heads-up instead of silently fall back to
11491 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11492 ;; with sexp instead of a function for `cmd'.
11493 (user-error "Please see Org News for version 9.0 about \
11494 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11495 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11496 (and (derived-mode-p 'org-mode)
11497 (eq old-mode 'org-mode)
11498 (or (not (eq old-buffer (current-buffer)))
11499 (not (eq old-pos (point))))
11500 (org-mark-ring-push old-pos old-buffer))))
11502 (defun org-file-apps-entry-match-against-dlink-p (entry)
11503 "This function returns non-nil if `entry' uses a regular
11504 expression which should be matched against the whole link by
11505 org-open-file.
11507 It assumes that is the case when the entry uses a regular
11508 expression which has at least one grouping construct and the
11509 action is either a lisp form or a command string containing
11510 `%1', i.e. using at least one subexpression match as a
11511 parameter."
11512 (let ((selector (car entry))
11513 (action (cdr entry)))
11514 (if (stringp selector)
11515 (and (> (regexp-opt-depth selector) 0)
11516 (or (and (stringp action)
11517 (string-match "%[0-9]" action))
11518 (consp action)))
11519 nil)))
11521 (defun org-default-apps ()
11522 "Return the default applications for this operating system."
11523 (cond
11524 ((eq system-type 'darwin)
11525 org-file-apps-defaults-macosx)
11526 ((eq system-type 'windows-nt)
11527 org-file-apps-defaults-windowsnt)
11528 (t org-file-apps-defaults-gnu)))
11530 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11531 "Convert extensions to regular expressions in the cars of LIST.
11532 Also, weed out any non-string entries, because the return value is used
11533 only for regexp matching.
11534 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11535 point to the symbol `emacs', indicating that the file should
11536 be opened in Emacs."
11537 (append
11538 (delq nil
11539 (mapcar (lambda (x)
11540 (unless (not (stringp (car x)))
11541 (if (string-match "\\W" (car x))
11543 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11544 list))
11545 (when add-auto-mode
11546 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11548 (defvar ange-ftp-name-format)
11549 (defun org-file-remote-p (file)
11550 "Test whether FILE specifies a location on a remote system.
11551 Return non-nil if the location is indeed remote.
11553 For example, the filename \"/user@host:/foo\" specifies a location
11554 on the system \"/user@host:\"."
11555 (cond ((fboundp 'file-remote-p)
11556 (file-remote-p file))
11557 ((fboundp 'tramp-handle-file-remote-p)
11558 (tramp-handle-file-remote-p file))
11559 ((and (boundp 'ange-ftp-name-format)
11560 (string-match (car ange-ftp-name-format) file))
11561 t)))
11564 ;;;; Refiling
11566 (defun org-get-org-file ()
11567 "Read a filename, with default directory `org-directory'."
11568 (let ((default (or org-default-notes-file remember-data-file)))
11569 (read-file-name (format "File name [%s]: " default)
11570 (file-name-as-directory org-directory)
11571 default)))
11573 (defun org-notes-order-reversed-p ()
11574 "Check if the current file should receive notes in reversed order."
11575 (cond
11576 ((not org-reverse-note-order) nil)
11577 ((eq t org-reverse-note-order) t)
11578 ((not (listp org-reverse-note-order)) nil)
11579 (t (catch 'exit
11580 (dolist (entry org-reverse-note-order)
11581 (when (string-match (car entry) buffer-file-name)
11582 (throw 'exit (cdr entry))))))))
11584 (defvar org-refile-target-table nil
11585 "The list of refile targets, created by `org-refile'.")
11587 (defvar org-agenda-new-buffers nil
11588 "Buffers created to visit agenda files.")
11590 (defvar org-refile-cache nil
11591 "Cache for refile targets.")
11593 (defvar org-refile-markers nil
11594 "All the markers used for caching refile locations.")
11596 (defun org-refile-marker (pos)
11597 "Get a new refile marker, but only if caching is in use."
11598 (if (not org-refile-use-cache)
11600 (let ((m (make-marker)))
11601 (move-marker m pos)
11602 (push m org-refile-markers)
11603 m)))
11605 (defun org-refile-cache-clear ()
11606 "Clear the refile cache and disable all the markers."
11607 (dolist (m org-refile-markers) (move-marker m nil))
11608 (setq org-refile-markers nil)
11609 (setq org-refile-cache nil)
11610 (message "Refile cache has been cleared"))
11612 (defun org-refile-cache-check-set (set)
11613 "Check if all the markers in the cache still have live buffers."
11614 (let (marker)
11615 (catch 'exit
11616 (while (and set (setq marker (nth 3 (pop set))))
11617 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11618 (when (and marker (null (marker-buffer marker)))
11619 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11620 (sit-for 3)
11621 (throw 'exit nil)))
11622 t)))
11624 (defun org-refile-cache-put (set &rest identifiers)
11625 "Push the refile targets SET into the cache, under IDENTIFIERS."
11626 (let* ((key (sha1 (prin1-to-string identifiers)))
11627 (entry (assoc key org-refile-cache)))
11628 (if entry
11629 (setcdr entry set)
11630 (push (cons key set) org-refile-cache))))
11632 (defun org-refile-cache-get (&rest identifiers)
11633 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11634 (cond
11635 ((not org-refile-cache) nil)
11636 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11638 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11639 org-refile-cache))))
11640 (and set (org-refile-cache-check-set set) set)))))
11642 (defvar org-outline-path-cache nil
11643 "Alist between buffer positions and outline paths.
11644 It value is an alist (POSITION . PATH) where POSITION is the
11645 buffer position at the beginning of an entry and PATH is a list
11646 of strings describing the outline path for that entry, in reverse
11647 order.")
11649 (defun org-refile-get-targets (&optional default-buffer)
11650 "Produce a table with refile targets."
11651 (let ((case-fold-search nil)
11652 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11653 (entries (or org-refile-targets '((nil . (:level . 1)))))
11654 targets tgs files desc descre)
11655 (message "Getting targets...")
11656 (with-current-buffer (or default-buffer (current-buffer))
11657 (dolist (entry entries)
11658 (setq files (car entry) desc (cdr entry))
11659 (cond
11660 ((null files) (setq files (list (current-buffer))))
11661 ((eq files 'org-agenda-files)
11662 (setq files (org-agenda-files 'unrestricted)))
11663 ((and (symbolp files) (fboundp files))
11664 (setq files (funcall files)))
11665 ((and (symbolp files) (boundp files))
11666 (setq files (symbol-value files))))
11667 (when (stringp files) (setq files (list files)))
11668 (cond
11669 ((eq (car desc) :tag)
11670 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11671 ((eq (car desc) :todo)
11672 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11673 ((eq (car desc) :regexp)
11674 (setq descre (cdr desc)))
11675 ((eq (car desc) :level)
11676 (setq descre (concat "^\\*\\{" (number-to-string
11677 (if org-odd-levels-only
11678 (1- (* 2 (cdr desc)))
11679 (cdr desc)))
11680 "\\}[ \t]")))
11681 ((eq (car desc) :maxlevel)
11682 (setq descre (concat "^\\*\\{1," (number-to-string
11683 (if org-odd-levels-only
11684 (1- (* 2 (cdr desc)))
11685 (cdr desc)))
11686 "\\}[ \t]")))
11687 (t (error "Bad refiling target description %s" desc)))
11688 (dolist (f files)
11689 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11691 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11692 (progn
11693 (when (bufferp f)
11694 (setq f (buffer-file-name (buffer-base-buffer f))))
11695 (setq f (and f (expand-file-name f)))
11696 (when (eq org-refile-use-outline-path 'file)
11697 (push (list (file-name-nondirectory f) f nil nil) tgs))
11698 (org-with-wide-buffer
11699 (goto-char (point-min))
11700 (setq org-outline-path-cache nil)
11701 (while (re-search-forward descre nil t)
11702 (beginning-of-line)
11703 (let ((case-fold-search nil))
11704 (looking-at org-complex-heading-regexp))
11705 (let ((begin (point))
11706 (heading (match-string-no-properties 4)))
11707 (unless (or (and
11708 org-refile-target-verify-function
11709 (not
11710 (funcall org-refile-target-verify-function)))
11711 (not heading))
11712 (let ((re (format org-complex-heading-regexp-format
11713 (regexp-quote heading)))
11714 (target
11715 (if (not org-refile-use-outline-path) heading
11716 (mapconcat
11717 #'org-protect-slash
11718 (append
11719 (pcase org-refile-use-outline-path
11720 (`file (list (file-name-nondirectory
11721 (buffer-file-name
11722 (buffer-base-buffer)))))
11723 (`full-file-path
11724 (list (buffer-file-name
11725 (buffer-base-buffer))))
11726 (_ nil))
11727 (org-get-outline-path t t))
11728 "/"))))
11729 (push (list target f re (org-refile-marker (point)))
11730 tgs)))
11731 (when (= (point) begin)
11732 ;; Verification function has not moved point.
11733 (end-of-line)))))))
11734 (when org-refile-use-cache
11735 (org-refile-cache-put tgs (buffer-file-name) descre))
11736 (setq targets (append tgs targets))))))
11737 (message "Getting targets...done")
11738 (delete-dups (nreverse targets))))
11740 (defun org-protect-slash (s)
11741 (replace-regexp-in-string "/" "\\/" s nil t))
11743 (defun org--get-outline-path-1 (&optional use-cache)
11744 "Return outline path to current headline.
11746 Outline path is a list of strings, in reverse order. When
11747 optional argument USE-CACHE is non-nil, make use of a cache. See
11748 `org-get-outline-path' for details.
11750 Assume buffer is widened and point is on a headline."
11751 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11752 (let ((p (point))
11753 (heading (let ((case-fold-search nil))
11754 (looking-at org-complex-heading-regexp)
11755 (if (not (match-end 4)) ""
11756 ;; Remove statistics cookies.
11757 (org-trim
11758 (org-link-display-format
11759 (replace-regexp-in-string
11760 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11761 (match-string-no-properties 4))))))))
11762 (if (org-up-heading-safe)
11763 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11764 (when use-cache
11765 (push (cons p path) org-outline-path-cache))
11766 path)
11767 ;; This is a new root node. Since we assume we are moving
11768 ;; forward, we can drop previous cache so as to limit number
11769 ;; of associations there.
11770 (let ((path (list heading)))
11771 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11772 path)))))
11774 (defun org-get-outline-path (&optional with-self use-cache)
11775 "Return the outline path to the current entry.
11777 An outline path is a list of ancestors for current headline, as
11778 a list of strings. Statistics cookies are removed and links are
11779 replaced with their description, if any, or their path otherwise.
11781 When optional argument WITH-SELF is non-nil, the path also
11782 includes the current headline.
11784 When optional argument USE-CACHE is non-nil, cache outline paths
11785 between calls to this function so as to avoid backtracking. This
11786 argument is useful when planning to find more than one outline
11787 path in the same document. In that case, there are two
11788 conditions to satisfy:
11789 - `org-outline-path-cache' is set to nil before starting the
11790 process;
11791 - outline paths are computed by increasing buffer positions."
11792 (org-with-wide-buffer
11793 (and (or (and with-self (org-back-to-heading t))
11794 (org-up-heading-safe))
11795 (reverse (org--get-outline-path-1 use-cache)))))
11797 (defun org-format-outline-path (path &optional width prefix separator)
11798 "Format the outline path PATH for display.
11799 WIDTH is the maximum number of characters that is available.
11800 PREFIX is a prefix to be included in the returned string,
11801 such as the file name.
11802 SEPARATOR is inserted between the different parts of the path,
11803 the default is \"/\"."
11804 (setq width (or width 79))
11805 (setq path (delq nil path))
11806 (unless (> width 0)
11807 (user-error "Argument `width' must be positive"))
11808 (setq separator (or separator "/"))
11809 (let* ((org-odd-levels-only nil)
11810 (fpath (concat
11811 prefix (and prefix path separator)
11812 (mapconcat
11813 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11814 (cl-loop for head in path
11815 for n from 0
11816 collect (org-add-props
11817 head nil 'face
11818 (nth (% n org-n-level-faces) org-level-faces)))
11819 separator))))
11820 (when (> (length fpath) width)
11821 (if (< width 7)
11822 ;; It's unlikely that `width' will be this small, but don't
11823 ;; waste characters by adding ".." if it is.
11824 (setq fpath (substring fpath 0 width))
11825 (setf (substring fpath (- width 2)) "..")))
11826 fpath))
11828 (defun org-display-outline-path (&optional file current separator just-return-string)
11829 "Display the current outline path in the echo area.
11831 If FILE is non-nil, prepend the output with the file name.
11832 If CURRENT is non-nil, append the current heading to the output.
11833 SEPARATOR is passed through to `org-format-outline-path'. It separates
11834 the different parts of the path and defaults to \"/\".
11835 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11836 (interactive "P")
11837 (let* (case-fold-search
11838 (bfn (buffer-file-name (buffer-base-buffer)))
11839 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11840 res)
11841 (when current (setq path (append path
11842 (save-excursion
11843 (org-back-to-heading t)
11844 (when (looking-at org-complex-heading-regexp)
11845 (list (match-string 4)))))))
11846 (setq res
11847 (org-format-outline-path
11848 path
11849 (1- (frame-width))
11850 (and file bfn (concat (file-name-nondirectory bfn) separator))
11851 separator))
11852 (if just-return-string
11853 (org-no-properties res)
11854 (org-unlogged-message "%s" res))))
11856 (defvar org-refile-history nil
11857 "History for refiling operations.")
11859 (defvar org-after-refile-insert-hook nil
11860 "Hook run after `org-refile' has inserted its stuff at the new location.
11861 Note that this is still *before* the stuff will be removed from
11862 the *old* location.")
11864 (defvar org-capture-last-stored-marker)
11865 (defvar org-refile-keep nil
11866 "Non-nil means `org-refile' will copy instead of refile.")
11868 (defun org-copy ()
11869 "Like `org-refile', but copy."
11870 (interactive)
11871 (let ((org-refile-keep t))
11872 (funcall 'org-refile nil nil nil "Copy")))
11874 (defun org-refile (&optional arg default-buffer rfloc msg)
11875 "Move the entry or entries at point to another heading.
11877 The list of target headings is compiled using the information in
11878 `org-refile-targets', which see.
11880 At the target location, the entry is filed as a subitem of the
11881 target heading. Depending on `org-reverse-note-order', the new
11882 subitem will either be the first or the last subitem.
11884 If there is an active region, all entries in that region will be
11885 refiled. However, the region must fulfill the requirement that
11886 the first heading sets the top-level of the moved text.
11888 With a `\\[universal-argument]' ARG, the command will only visit the target \
11889 location
11890 and not actually move anything.
11892 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11893 location where the last
11894 refiling operation has put the subtree.
11896 With a numeric prefix argument of `2', refile to the running clock.
11898 With a numeric prefix argument of `3', emulate `org-refile-keep'
11899 being set to t and copy to the target location, don't move it.
11900 Beware that keeping refiled entries may result in duplicated ID
11901 properties.
11903 RFLOC can be a refile location obtained in a different way.
11905 MSG is a string to replace \"Refile\" in the default prompt with
11906 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11908 See also `org-refile-use-outline-path'.
11910 If you are using target caching (see `org-refile-use-cache'), you
11911 have to clear the target cache in order to find new targets.
11912 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11913 prefix argument (`C-u C-u C-u C-c C-w')."
11914 (interactive "P")
11915 (if (member arg '(0 (64)))
11916 (org-refile-cache-clear)
11917 (let* ((actionmsg (cond (msg msg)
11918 ((equal arg 3) "Refile (and keep)")
11919 (t "Refile")))
11920 (regionp (org-region-active-p))
11921 (region-start (and regionp (region-beginning)))
11922 (region-end (and regionp (region-end)))
11923 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11924 pos it nbuf file level reversed)
11925 (setq last-command nil)
11926 (when regionp
11927 (goto-char region-start)
11928 (or (bolp) (goto-char (point-at-bol)))
11929 (setq region-start (point))
11930 (unless (or (org-kill-is-subtree-p
11931 (buffer-substring region-start region-end))
11932 (prog1 org-refile-active-region-within-subtree
11933 (let ((s (point-at-eol)))
11934 (org-toggle-heading)
11935 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11936 (user-error "The region is not a (sequence of) subtree(s)")))
11937 (if (equal arg '(16))
11938 (org-refile-goto-last-stored)
11939 (when (or
11940 (and (equal arg 2)
11941 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11942 (prog1
11943 (setq it (list (or org-clock-heading "running clock")
11944 (buffer-file-name
11945 (marker-buffer org-clock-hd-marker))
11947 (marker-position org-clock-hd-marker)))
11948 (setq arg nil)))
11949 (setq it
11950 (or rfloc
11951 (let (heading-text)
11952 (save-excursion
11953 (unless (and arg (listp arg))
11954 (org-back-to-heading t)
11955 (setq heading-text
11956 (replace-regexp-in-string
11957 org-bracket-link-regexp
11958 "\\3"
11959 (or (nth 4 (org-heading-components))
11960 ""))))
11961 (org-refile-get-location
11962 (cond ((and arg (listp arg)) "Goto")
11963 (regionp (concat actionmsg " region to"))
11964 (t (concat actionmsg " subtree \""
11965 heading-text "\" to")))
11966 default-buffer
11967 (and (not (equal '(4) arg))
11968 org-refile-allow-creating-parent-nodes)))))))
11969 (setq file (nth 1 it)
11970 pos (nth 3 it))
11971 (when (and (not arg)
11973 (equal (buffer-file-name) file)
11974 (if regionp
11975 (and (>= pos region-start)
11976 (<= pos region-end))
11977 (and (>= pos (point))
11978 (< pos (save-excursion
11979 (org-end-of-subtree t t))))))
11980 (error "Cannot refile to position inside the tree or region"))
11981 (setq nbuf (or (find-buffer-visiting file)
11982 (find-file-noselect file)))
11983 (if (and arg (not (equal arg 3)))
11984 (progn
11985 (pop-to-buffer-same-window nbuf)
11986 (goto-char pos)
11987 (org-show-context 'org-goto))
11988 (if regionp
11989 (progn
11990 (org-kill-new (buffer-substring region-start region-end))
11991 (org-save-markers-in-region region-start region-end))
11992 (org-copy-subtree 1 nil t))
11993 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11994 (find-file-noselect file)))
11995 (setq reversed (org-notes-order-reversed-p))
11996 (org-with-wide-buffer
11997 (if pos
11998 (progn
11999 (goto-char pos)
12000 (looking-at org-outline-regexp)
12001 (setq level (org-get-valid-level (funcall outline-level) 1))
12002 (goto-char
12003 (if reversed
12004 (or (outline-next-heading) (point-max))
12005 (or (save-excursion (org-get-next-sibling))
12006 (org-end-of-subtree t t)
12007 (point-max)))))
12008 (setq level 1)
12009 (if (not reversed)
12010 (goto-char (point-max))
12011 (goto-char (point-min))
12012 (or (outline-next-heading) (goto-char (point-max)))))
12013 (unless (bolp) (newline))
12014 (org-paste-subtree level nil nil t)
12015 (when org-log-refile
12016 (org-add-log-setup 'refile nil nil org-log-refile)
12017 (unless (eq org-log-refile 'note)
12018 (save-excursion (org-add-log-note))))
12019 (and org-auto-align-tags
12020 (let ((org-loop-over-headlines-in-active-region nil))
12021 (org-set-tags nil t)))
12022 (let ((bookmark-name (plist-get org-bookmark-names-plist
12023 :last-refile)))
12024 (when bookmark-name
12025 (with-demoted-errors
12026 (bookmark-set bookmark-name))))
12027 ;; If we are refiling for capture, make sure that the
12028 ;; last-capture pointers point here
12029 (when (bound-and-true-p org-capture-is-refiling)
12030 (let ((bookmark-name (plist-get org-bookmark-names-plist
12031 :last-capture-marker)))
12032 (when bookmark-name
12033 (with-demoted-errors
12034 (bookmark-set bookmark-name))))
12035 (move-marker org-capture-last-stored-marker (point)))
12036 (when (fboundp 'deactivate-mark) (deactivate-mark))
12037 (run-hooks 'org-after-refile-insert-hook)))
12038 (unless org-refile-keep
12039 (if regionp
12040 (delete-region (point) (+ (point) (- region-end region-start)))
12041 (delete-region
12042 (and (org-back-to-heading t) (point))
12043 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12044 (when (featurep 'org-inlinetask)
12045 (org-inlinetask-remove-END-maybe))
12046 (setq org-markers-to-move nil)
12047 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12049 (defun org-refile-goto-last-stored ()
12050 "Go to the location where the last refile was stored."
12051 (interactive)
12052 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12053 (message "This is the location of the last refile"))
12055 (defun org-refile--get-location (refloc tbl)
12056 "When user refile to REFLOC, find the associated target in TBL.
12057 Also check `org-refile-target-table'."
12058 (car (delq
12060 (mapcar
12061 (lambda (r) (or (assoc r tbl)
12062 (assoc r org-refile-target-table)))
12063 (list (replace-regexp-in-string "/$" "" refloc)
12064 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12066 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12067 "Prompt the user for a refile location, using PROMPT.
12068 PROMPT should not be suffixed with a colon and a space, because
12069 this function appends the default value from
12070 `org-refile-history' automatically, if that is not empty."
12071 (let ((org-refile-targets org-refile-targets)
12072 (org-refile-use-outline-path org-refile-use-outline-path))
12073 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12074 (unless org-refile-target-table
12075 (user-error "No refile targets"))
12076 (let* ((cbuf (current-buffer))
12077 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12078 (cfunc (if (and org-refile-use-outline-path
12079 org-outline-path-complete-in-steps)
12080 #'org-olpath-completing-read
12081 #'completing-read))
12082 (extra (if org-refile-use-outline-path "/" ""))
12083 (cbnex (concat (buffer-name) extra))
12084 (filename (and cfn (expand-file-name cfn)))
12085 (tbl (mapcar
12086 (lambda (x)
12087 (if (and (not (member org-refile-use-outline-path
12088 '(file full-file-path)))
12089 (not (equal filename (nth 1 x))))
12090 (cons (concat (car x) extra " ("
12091 (file-name-nondirectory (nth 1 x)) ")")
12092 (cdr x))
12093 (cons (concat (car x) extra) (cdr x))))
12094 org-refile-target-table))
12095 (completion-ignore-case t)
12096 cdef
12097 (prompt (concat prompt
12098 (or (and (car org-refile-history)
12099 (concat " (default " (car org-refile-history) ")"))
12100 (and (assoc cbnex tbl) (setq cdef cbnex)
12101 (concat " (default " cbnex ")"))) ": "))
12102 pa answ parent-target child parent old-hist)
12103 (setq old-hist org-refile-history)
12104 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12105 nil 'org-refile-history (or cdef (car org-refile-history))))
12106 (if (setq pa (org-refile--get-location answ tbl))
12107 (progn
12108 (org-refile-check-position pa)
12109 (when (or (not org-refile-history)
12110 (not (eq old-hist org-refile-history))
12111 (not (equal (car pa) (car org-refile-history))))
12112 (setq org-refile-history
12113 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12114 org-refile-history
12115 (cdr org-refile-history))))
12116 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12117 (pop org-refile-history)))
12119 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12120 (progn
12121 (setq parent (match-string 1 answ)
12122 child (match-string 2 answ))
12123 (setq parent-target (org-refile--get-location parent tbl))
12124 (when (and parent-target
12125 (or (eq new-nodes t)
12126 (and (eq new-nodes 'confirm)
12127 (y-or-n-p (format "Create new node \"%s\"? "
12128 child)))))
12129 (org-refile-new-child parent-target child)))
12130 (user-error "Invalid target location")))))
12132 (declare-function org-string-nw-p "org-macs" (s))
12133 (defun org-refile-check-position (refile-pointer)
12134 "Check if the refile pointer matches the headline to which it points."
12135 (let* ((file (nth 1 refile-pointer))
12136 (re (nth 2 refile-pointer))
12137 (pos (nth 3 refile-pointer))
12138 buffer)
12139 (if (and (not (markerp pos)) (not file))
12140 (user-error "Please indicate a target file in the refile path")
12141 (when (org-string-nw-p re)
12142 (setq buffer (if (markerp pos)
12143 (marker-buffer pos)
12144 (or (find-buffer-visiting file)
12145 (find-file-noselect file))))
12146 (with-current-buffer buffer
12147 (org-with-wide-buffer
12148 (goto-char pos)
12149 (beginning-of-line 1)
12150 (unless (looking-at-p re)
12151 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12153 (defun org-refile-new-child (parent-target child)
12154 "Use refile target PARENT-TARGET to add new CHILD below it."
12155 (unless parent-target
12156 (error "Cannot find parent for new node"))
12157 (let ((file (nth 1 parent-target))
12158 (pos (nth 3 parent-target))
12159 level)
12160 (with-current-buffer (or (find-buffer-visiting file)
12161 (find-file-noselect file))
12162 (org-with-wide-buffer
12163 (if pos
12164 (goto-char pos)
12165 (goto-char (point-max))
12166 (unless (bolp) (newline)))
12167 (when (looking-at org-outline-regexp)
12168 (setq level (funcall outline-level))
12169 (org-end-of-subtree t t))
12170 (org-back-over-empty-lines)
12171 (insert "\n" (make-string
12172 (if pos (org-get-valid-level level 1) 1) ?*)
12173 " " child "\n")
12174 (beginning-of-line 0)
12175 (list (concat (car parent-target) "/" child) file "" (point))))))
12177 (defun org-olpath-completing-read (prompt collection &rest args)
12178 "Read an outline path like a file name."
12179 (let ((thetable collection))
12180 (apply #'completing-read
12181 prompt
12182 (lambda (string predicate &optional flag)
12183 (cond
12184 ((eq flag nil) (try-completion string thetable))
12185 ((eq flag t)
12186 (let ((l (length string)))
12187 (mapcar (lambda (x)
12188 (let ((r (substring x l))
12189 (f (if (string-match " ([^)]*)$" x)
12190 (match-string 0 x)
12191 "")))
12192 (if (string-match "/" r)
12193 (concat string (substring r 0 (match-end 0)) f)
12194 x)))
12195 (all-completions string thetable predicate))))
12196 ;; Exact match?
12197 ((eq flag 'lambda) (assoc string thetable))))
12198 args)))
12200 ;;;; Dynamic blocks
12202 (defun org-find-dblock (name)
12203 "Find the first dynamic block with name NAME in the buffer.
12204 If not found, stay at current position and return nil."
12205 (let ((case-fold-search t) pos)
12206 (save-excursion
12207 (goto-char (point-min))
12208 (setq pos (and (re-search-forward
12209 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12210 (match-beginning 0))))
12211 (when pos (goto-char pos))
12212 pos))
12214 (defun org-create-dblock (plist)
12215 "Create a dynamic block section, with parameters taken from PLIST.
12216 PLIST must contain a :name entry which is used as the name of the block."
12217 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12218 (end-of-line 1)
12219 (newline))
12220 (let ((col (current-column))
12221 (name (plist-get plist :name)))
12222 (insert "#+BEGIN: " name)
12223 (while plist
12224 (if (eq (car plist) :name)
12225 (setq plist (cddr plist))
12226 (insert " " (prin1-to-string (pop plist)))))
12227 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12228 (beginning-of-line -2)))
12230 (defun org-prepare-dblock ()
12231 "Prepare dynamic block for refresh.
12232 This empties the block, puts the cursor at the insert position and returns
12233 the property list including an extra property :name with the block name."
12234 (unless (looking-at org-dblock-start-re)
12235 (user-error "Not at a dynamic block"))
12236 (let* ((begdel (1+ (match-end 0)))
12237 (name (org-no-properties (match-string 1)))
12238 (params (append (list :name name)
12239 (read (concat "(" (match-string 3) ")")))))
12240 (save-excursion
12241 (beginning-of-line 1)
12242 (skip-chars-forward " \t")
12243 (setq params (plist-put params :indentation-column (current-column))))
12244 (unless (re-search-forward org-dblock-end-re nil t)
12245 (error "Dynamic block not terminated"))
12246 (setq params
12247 (append params
12248 (list :content (buffer-substring
12249 begdel (match-beginning 0)))))
12250 (delete-region begdel (match-beginning 0))
12251 (goto-char begdel)
12252 (open-line 1)
12253 params))
12255 (defun org-map-dblocks (&optional command)
12256 "Apply COMMAND to all dynamic blocks in the current buffer.
12257 If COMMAND is not given, use `org-update-dblock'."
12258 (let ((cmd (or command 'org-update-dblock)))
12259 (save-excursion
12260 (goto-char (point-min))
12261 (while (re-search-forward org-dblock-start-re nil t)
12262 (goto-char (match-beginning 0))
12263 (save-excursion
12264 (condition-case nil
12265 (funcall cmd)
12266 (error (message "Error during update of dynamic block"))))
12267 (unless (re-search-forward org-dblock-end-re nil t)
12268 (error "Dynamic block not terminated"))))))
12270 (defun org-dblock-update (&optional arg)
12271 "User command for updating dynamic blocks.
12272 Update the dynamic block at point. With prefix ARG, update all dynamic
12273 blocks in the buffer."
12274 (interactive "P")
12275 (if arg
12276 (org-update-all-dblocks)
12277 (or (looking-at org-dblock-start-re)
12278 (org-beginning-of-dblock))
12279 (org-update-dblock)))
12281 (defun org-update-dblock ()
12282 "Update the dynamic block at point.
12283 This means to empty the block, parse for parameters and then call
12284 the correct writing function."
12285 (interactive)
12286 (save-excursion
12287 (let* ((win (selected-window))
12288 (pos (point))
12289 (line (org-current-line))
12290 (params (org-prepare-dblock))
12291 (name (plist-get params :name))
12292 (indent (plist-get params :indentation-column))
12293 (cmd (intern (concat "org-dblock-write:" name))))
12294 (message "Updating dynamic block `%s' at line %d..." name line)
12295 (funcall cmd params)
12296 (message "Updating dynamic block `%s' at line %d...done" name line)
12297 (goto-char pos)
12298 (when (and indent (> indent 0))
12299 (setq indent (make-string indent ?\ ))
12300 (save-excursion
12301 (select-window win)
12302 (org-beginning-of-dblock)
12303 (forward-line 1)
12304 (while (not (looking-at org-dblock-end-re))
12305 (insert indent)
12306 (beginning-of-line 2))
12307 (when (looking-at org-dblock-end-re)
12308 (and (looking-at "[ \t]+")
12309 (replace-match ""))
12310 (insert indent)))))))
12312 (defun org-beginning-of-dblock ()
12313 "Find the beginning of the dynamic block at point.
12314 Error if there is no such block at point."
12315 (let ((pos (point))
12316 beg)
12317 (end-of-line 1)
12318 (if (and (re-search-backward org-dblock-start-re nil t)
12319 (setq beg (match-beginning 0))
12320 (re-search-forward org-dblock-end-re nil t)
12321 (> (match-end 0) pos))
12322 (goto-char beg)
12323 (goto-char pos)
12324 (error "Not in a dynamic block"))))
12326 (defun org-update-all-dblocks ()
12327 "Update all dynamic blocks in the buffer.
12328 This function can be used in a hook."
12329 (interactive)
12330 (when (derived-mode-p 'org-mode)
12331 (org-map-dblocks 'org-update-dblock)))
12334 ;;;; Completion
12336 (declare-function org-export-backend-options "ox" (cl-x) t)
12337 (defun org-get-export-keywords ()
12338 "Return a list of all currently understood export keywords.
12339 Export keywords include options, block names, attributes and
12340 keywords relative to each registered export back-end."
12341 (let (keywords)
12342 (dolist (backend
12343 (bound-and-true-p org-export-registered-backends)
12344 (delq nil keywords))
12345 ;; Back-end name (for keywords, like #+LATEX:)
12346 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12347 (dolist (option-entry (org-export-backend-options backend))
12348 ;; Back-end options.
12349 (push (nth 1 option-entry) keywords)))))
12351 (defconst org-options-keywords
12352 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12353 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12354 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12355 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12356 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12358 (defcustom org-structure-template-alist
12359 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12360 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12361 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12362 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12363 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12364 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12365 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12366 ("L" "#+LaTeX: ")
12367 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12368 ("H" "#+HTML: ")
12369 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12370 ("A" "#+ASCII: ")
12371 ("i" "#+INDEX: ?")
12372 ("I" "#+INCLUDE: %file ?"))
12373 "Structure completion elements.
12374 This is a list of abbreviation keys and values. The value gets inserted
12375 if you type `<' followed by the key and then press the completion key,
12376 usually `TAB'. %file will be replaced by a file name after prompting
12377 for the file using completion. The cursor will be placed at the position
12378 of the `?' in the template.
12379 There are two templates for each key, the first uses the original Org syntax,
12380 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12381 the default when the /org-mtags.el/ module has been loaded. See also the
12382 variable `org-mtags-prefer-muse-templates'."
12383 :group 'org-completion
12384 :type '(repeat
12385 (list
12386 (string :tag "Key")
12387 (string :tag "Template")))
12388 :version "26.1"
12389 :package-version '(Org . "8.3"))
12391 (defun org-try-structure-completion ()
12392 "Try to complete a structure template before point.
12393 This looks for strings like \"<e\" on an otherwise empty line and
12394 expands them."
12395 (let ((l (buffer-substring (point-at-bol) (point)))
12397 (when (and (looking-at "[ \t]*$")
12398 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12399 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12400 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12401 (match-beginning 1)) a)
12402 t)))
12404 (defun org-complete-expand-structure-template (start cell)
12405 "Expand a structure template."
12406 (let ((rpl (nth 1 cell))
12407 (ind ""))
12408 (delete-region start (point))
12409 (when (string-match "\\`[ \t]*#\\+" rpl)
12410 (cond
12411 ((bolp))
12412 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12413 (setq ind (buffer-substring (point-at-bol) (point))))
12414 (t (newline))))
12415 (setq start (point))
12416 (when (string-match "%file" rpl)
12417 (setq rpl (replace-match
12418 (concat
12419 "\""
12420 (save-match-data
12421 (abbreviate-file-name (read-file-name "Include file: ")))
12422 "\"")
12423 t t rpl)))
12424 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12425 (concat "\n" ind)))
12426 (insert rpl)
12427 (when (re-search-backward "\\?" start t) (delete-char 1))))
12429 ;;;; TODO, DEADLINE, Comments
12431 (defun org-toggle-comment ()
12432 "Change the COMMENT state of an entry."
12433 (interactive)
12434 (save-excursion
12435 (org-back-to-heading)
12436 (let ((case-fold-search nil))
12437 (looking-at org-complex-heading-regexp))
12438 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12439 (skip-chars-forward " \t")
12440 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12441 (if (org-in-commented-heading-p t)
12442 (delete-region (point)
12443 (progn (search-forward " " (line-end-position) 'move)
12444 (skip-chars-forward " \t")
12445 (point)))
12446 (insert org-comment-string)
12447 (unless (eolp) (insert " ")))))
12449 (defvar org-last-todo-state-is-todo nil
12450 "This is non-nil when the last TODO state change led to a TODO state.
12451 If the last change removed the TODO tag or switched to DONE, then
12452 this is nil.")
12454 (defvar org-setting-tags nil) ; dynamically skipped
12456 (defvar org-todo-setup-filter-hook nil
12457 "Hook for functions that pre-filter todo specs.
12458 Each function takes a todo spec and returns either nil or the spec
12459 transformed into canonical form." )
12461 (defvar org-todo-get-default-hook nil
12462 "Hook for functions that get a default item for todo.
12463 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12464 nil or a string to be used for the todo mark." )
12466 (defvar org-agenda-headline-snapshot-before-repeat)
12468 (defun org-current-effective-time ()
12469 "Return current time adjusted for `org-extend-today-until' variable."
12470 (let* ((ct (org-current-time))
12471 (dct (decode-time ct))
12472 (ct1
12473 (cond
12474 (org-use-last-clock-out-time-as-effective-time
12475 (or (org-clock-get-last-clock-out-time) ct))
12476 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12477 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12478 (t ct))))
12479 ct1))
12481 (defun org-todo-yesterday (&optional arg)
12482 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12483 (interactive "P")
12484 (if (eq major-mode 'org-agenda-mode)
12485 (apply 'org-agenda-todo-yesterday arg)
12486 (let* ((org-use-effective-time t)
12487 (hour (nth 2 (decode-time (org-current-time))))
12488 (org-extend-today-until (1+ hour)))
12489 (org-todo arg))))
12491 (defvar org-block-entry-blocking ""
12492 "First entry preventing the TODO state change.")
12494 (defun org-cancel-repeater ()
12495 "Cancel a repeater by setting its numeric value to zero."
12496 (interactive)
12497 (save-excursion
12498 (org-back-to-heading t)
12499 (let ((bound1 (point))
12500 (bound0 (save-excursion (outline-next-heading) (point))))
12501 (when (and (re-search-forward
12502 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12503 org-deadline-time-regexp "\\)\\|\\("
12504 org-ts-regexp "\\)")
12505 bound0 t)
12506 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12507 bound1 t))
12508 (replace-match "0" t nil nil 1)))))
12510 (defvar org-state)
12511 (defvar org-blocked-by-checkboxes)
12512 (defun org-todo (&optional arg)
12513 "Change the TODO state of an item.
12515 The state of an item is given by a keyword at the start of the heading,
12516 like
12517 *** TODO Write paper
12518 *** DONE Call mom
12520 The different keywords are specified in the variable `org-todo-keywords'.
12521 By default the available states are \"TODO\" and \"DONE\". So, for this
12522 example: when the item starts with TODO, it is changed to DONE.
12523 When it starts with DONE, the DONE is removed. And when neither TODO nor
12524 DONE are present, add TODO at the beginning of the heading.
12526 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12527 state.
12528 With numeric prefix ARG, switch to that state.
12529 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12530 next set of TODO \
12531 keywords (nextset).
12532 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12533 prefix, circumvent any state blocking.
12534 With a numeric prefix arg of 0, inhibit note taking for the change.
12535 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12537 When called through ELisp, arg is also interpreted in the following way:
12538 `none' -> empty state
12539 \"\" -> switch to empty state
12540 `done' -> switch to DONE
12541 `nextset' -> switch to the next set of keywords
12542 `previousset' -> switch to the previous set of keywords
12543 \"WAITING\" -> switch to the specified keyword, but only if it
12544 really is a member of `org-todo-keywords'."
12545 (interactive "P")
12546 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12547 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12548 'region-start-level 'region))
12549 org-loop-over-headlines-in-active-region)
12550 (org-map-entries
12551 `(org-todo ,arg)
12552 org-loop-over-headlines-in-active-region
12553 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12554 (when (equal arg '(16)) (setq arg 'nextset))
12555 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12556 (let ((org-blocker-hook org-blocker-hook)
12557 commentp
12558 case-fold-search)
12559 (when (equal arg '(64))
12560 (setq arg nil org-blocker-hook nil))
12561 (when (and org-blocker-hook
12562 (or org-inhibit-blocking
12563 (org-entry-get nil "NOBLOCKING")))
12564 (setq org-blocker-hook nil))
12565 (save-excursion
12566 (catch 'exit
12567 (org-back-to-heading t)
12568 (when (org-in-commented-heading-p t)
12569 (org-toggle-comment)
12570 (setq commentp t))
12571 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12572 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12573 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12574 (let* ((match-data (match-data))
12575 (startpos (point-at-bol))
12576 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12577 (org-log-done org-log-done)
12578 (org-log-repeat org-log-repeat)
12579 (org-todo-log-states org-todo-log-states)
12580 (org-inhibit-logging
12581 (if (equal arg 0)
12582 (progn (setq arg nil) 'note) org-inhibit-logging))
12583 (this (match-string 1))
12584 (hl-pos (match-beginning 0))
12585 (head (org-get-todo-sequence-head this))
12586 (ass (assoc head org-todo-kwd-alist))
12587 (interpret (nth 1 ass))
12588 (done-word (nth 3 ass))
12589 (final-done-word (nth 4 ass))
12590 (org-last-state (or this ""))
12591 (completion-ignore-case t)
12592 (member (member this org-todo-keywords-1))
12593 (tail (cdr member))
12594 (org-state (cond
12595 ((and org-todo-key-trigger
12596 (or (and (equal arg '(4))
12597 (eq org-use-fast-todo-selection 'prefix))
12598 (and (not arg) org-use-fast-todo-selection
12599 (not (eq org-use-fast-todo-selection
12600 'prefix)))))
12601 ;; Use fast selection.
12602 (org-fast-todo-selection))
12603 ((and (equal arg '(4))
12604 (or (not org-use-fast-todo-selection)
12605 (not org-todo-key-trigger)))
12606 ;; Read a state with completion.
12607 (completing-read
12608 "State: " (mapcar #'list org-todo-keywords-1)
12609 nil t))
12610 ((eq arg 'right)
12611 (if this
12612 (if tail (car tail) nil)
12613 (car org-todo-keywords-1)))
12614 ((eq arg 'left)
12615 (unless (equal member org-todo-keywords-1)
12616 (if this
12617 (nth (- (length org-todo-keywords-1)
12618 (length tail) 2)
12619 org-todo-keywords-1)
12620 (org-last org-todo-keywords-1))))
12621 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12622 (setq arg nil))) ;hack to fall back to cycling
12623 (arg
12624 ;; User or caller requests a specific state.
12625 (cond
12626 ((equal arg "") nil)
12627 ((eq arg 'none) nil)
12628 ((eq arg 'done) (or done-word (car org-done-keywords)))
12629 ((eq arg 'nextset)
12630 (or (car (cdr (member head org-todo-heads)))
12631 (car org-todo-heads)))
12632 ((eq arg 'previousset)
12633 (let ((org-todo-heads (reverse org-todo-heads)))
12634 (or (car (cdr (member head org-todo-heads)))
12635 (car org-todo-heads))))
12636 ((car (member arg org-todo-keywords-1)))
12637 ((stringp arg)
12638 (user-error "State `%s' not valid in this file" arg))
12639 ((nth (1- (prefix-numeric-value arg))
12640 org-todo-keywords-1))))
12641 ((null member) (or head (car org-todo-keywords-1)))
12642 ((equal this final-done-word) nil) ;-> make empty
12643 ((null tail) nil) ;-> first entry
12644 ((memq interpret '(type priority))
12645 (if (eq this-command last-command)
12646 (car tail)
12647 (if (> (length tail) 0)
12648 (or done-word (car org-done-keywords))
12649 nil)))
12651 (car tail))))
12652 (org-state (or
12653 (run-hook-with-args-until-success
12654 'org-todo-get-default-hook org-state org-last-state)
12655 org-state))
12656 (next (if org-state (concat " " org-state " ") " "))
12657 (change-plist (list :type 'todo-state-change :from this :to org-state
12658 :position startpos))
12659 dolog now-done-p)
12660 (when org-blocker-hook
12661 (let (org-blocked-by-checkboxes block-reason)
12662 (setq org-last-todo-state-is-todo
12663 (not (member this org-done-keywords)))
12664 (unless (save-excursion
12665 (save-match-data
12666 (org-with-wide-buffer
12667 (run-hook-with-args-until-failure
12668 'org-blocker-hook change-plist))))
12669 (setq block-reason (if org-blocked-by-checkboxes
12670 "contained checkboxes"
12671 (format "\"%s\"" org-block-entry-blocking)))
12672 (if (called-interactively-p 'interactive)
12673 (user-error "TODO state change from %s to %s blocked (by %s)"
12674 this org-state block-reason)
12675 ;; Fail silently.
12676 (message "TODO state change from %s to %s blocked (by %s)"
12677 this org-state block-reason)
12678 (throw 'exit nil)))))
12679 (store-match-data match-data)
12680 (replace-match next t t)
12681 (cond ((equal this org-state)
12682 (message "TODO state was already %s" (org-trim next)))
12683 ((not (pos-visible-in-window-p hl-pos))
12684 (message "TODO state changed to %s" (org-trim next))))
12685 (unless head
12686 (setq head (org-get-todo-sequence-head org-state)
12687 ass (assoc head org-todo-kwd-alist)
12688 interpret (nth 1 ass)
12689 done-word (nth 3 ass)
12690 final-done-word (nth 4 ass)))
12691 (when (memq arg '(nextset previousset))
12692 (message "Keyword-Set %d/%d: %s"
12693 (- (length org-todo-sets) -1
12694 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12695 (length org-todo-sets)
12696 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12697 (setq org-last-todo-state-is-todo
12698 (not (member org-state org-done-keywords)))
12699 (setq now-done-p (and (member org-state org-done-keywords)
12700 (not (member this org-done-keywords))))
12701 (and logging (org-local-logging logging))
12702 (when (and (or org-todo-log-states org-log-done)
12703 (not (eq org-inhibit-logging t))
12704 (not (memq arg '(nextset previousset))))
12705 ;; We need to look at recording a time and note.
12706 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12707 (nth 2 (assoc this org-todo-log-states))))
12708 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12709 (setq dolog 'time))
12710 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12711 (and org-state
12712 (member org-state org-not-done-keywords)
12713 (not (member this org-not-done-keywords))))
12714 ;; This is now a todo state and was not one before
12715 ;; If there was a CLOSED time stamp, get rid of it.
12716 (org-add-planning-info nil nil 'closed))
12717 (when (and now-done-p org-log-done)
12718 ;; It is now done, and it was not done before.
12719 (org-add-planning-info 'closed (org-current-effective-time))
12720 (when (and (not dolog) (eq 'note org-log-done))
12721 (org-add-log-setup 'done org-state this 'note)))
12722 (when (and org-state dolog)
12723 ;; This is a non-nil state, and we need to log it.
12724 (org-add-log-setup 'state org-state this dolog)))
12725 ;; Fixup tag positioning.
12726 (org-todo-trigger-tag-changes org-state)
12727 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12728 (when org-provide-todo-statistics
12729 (org-update-parent-todo-statistics))
12730 (run-hooks 'org-after-todo-state-change-hook)
12731 (when (and arg (not (member org-state org-done-keywords)))
12732 (setq head (org-get-todo-sequence-head org-state)))
12733 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12734 ;; Do we need to trigger a repeat?
12735 (when now-done-p
12736 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12737 ;; This is for the agenda, take a snapshot of the headline.
12738 (save-match-data
12739 (setq org-agenda-headline-snapshot-before-repeat
12740 (org-get-heading))))
12741 (org-auto-repeat-maybe org-state))
12742 ;; Fixup cursor location if close to the keyword.
12743 (when (and (outline-on-heading-p)
12744 (not (bolp))
12745 (save-excursion (beginning-of-line 1)
12746 (looking-at org-todo-line-regexp))
12747 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12748 (goto-char (or (match-end 2) (match-end 1)))
12749 (and (looking-at " ") (just-one-space)))
12750 (when org-trigger-hook
12751 (save-excursion
12752 (run-hook-with-args 'org-trigger-hook change-plist)))
12753 (when commentp (org-toggle-comment))))))))
12755 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12756 "Block turning an entry into a TODO, using the hierarchy.
12757 This checks whether the current task should be blocked from state
12758 changes. Such blocking occurs when:
12760 1. The task has children which are not all in a completed state.
12762 2. A task has a parent with the property :ORDERED:, and there
12763 are siblings prior to the current task with incomplete
12764 status.
12766 3. The parent of the task is blocked because it has siblings that should
12767 be done first, or is child of a block grandparent TODO entry."
12769 (if (not org-enforce-todo-dependencies)
12770 t ; if locally turned off don't block
12771 (catch 'dont-block
12772 ;; If this is not a todo state change, or if this entry is already DONE,
12773 ;; do not block
12774 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12775 (member (plist-get change-plist :from)
12776 (cons 'done org-done-keywords))
12777 (member (plist-get change-plist :to)
12778 (cons 'todo org-not-done-keywords))
12779 (not (plist-get change-plist :to)))
12780 (throw 'dont-block t))
12781 ;; If this task has children, and any are undone, it's blocked
12782 (save-excursion
12783 (org-back-to-heading t)
12784 (let ((this-level (funcall outline-level)))
12785 (outline-next-heading)
12786 (let ((child-level (funcall outline-level)))
12787 (while (and (not (eobp))
12788 (> child-level this-level))
12789 ;; this todo has children, check whether they are all
12790 ;; completed
12791 (when (and (not (org-entry-is-done-p))
12792 (org-entry-is-todo-p))
12793 (setq org-block-entry-blocking (org-get-heading))
12794 (throw 'dont-block nil))
12795 (outline-next-heading)
12796 (setq child-level (funcall outline-level))))))
12797 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12798 ;; any previous siblings are undone, it's blocked
12799 (save-excursion
12800 (org-back-to-heading t)
12801 (let* ((pos (point))
12802 (parent-pos (and (org-up-heading-safe) (point)))
12803 (case-fold-search nil))
12804 (unless parent-pos (throw 'dont-block t)) ; no parent
12805 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12806 (forward-line 1)
12807 (re-search-forward org-not-done-heading-regexp pos t))
12808 (setq org-block-entry-blocking (match-string 0))
12809 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12810 ;; Search further up the hierarchy, to see if an ancestor is blocked
12811 (while t
12812 (goto-char parent-pos)
12813 (unless (looking-at org-not-done-heading-regexp)
12814 (throw 'dont-block t)) ; do not block, parent is not a TODO
12815 (setq pos (point))
12816 (setq parent-pos (and (org-up-heading-safe) (point)))
12817 (unless parent-pos (throw 'dont-block t)) ; no parent
12818 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12819 (forward-line 1)
12820 (re-search-forward org-not-done-heading-regexp pos t)
12821 (setq org-block-entry-blocking (org-get-heading)))
12822 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12824 (defcustom org-track-ordered-property-with-tag nil
12825 "Should the ORDERED property also be shown as a tag?
12826 The ORDERED property decides if an entry should require subtasks to be
12827 completed in sequence. Since a property is not very visible, setting
12828 this option means that toggling the ORDERED property with the command
12829 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12830 not relevant for the behavior, but it makes things more visible.
12832 Note that toggling the tag with tags commands will not change the property
12833 and therefore not influence behavior!
12835 This can be t, meaning the tag ORDERED should be used, It can also be a
12836 string to select a different tag for this task."
12837 :group 'org-todo
12838 :type '(choice
12839 (const :tag "No tracking" nil)
12840 (const :tag "Track with ORDERED tag" t)
12841 (string :tag "Use other tag")))
12843 (defun org-toggle-ordered-property ()
12844 "Toggle the ORDERED property of the current entry.
12845 For better visibility, you can track the value of this property with a tag.
12846 See variable `org-track-ordered-property-with-tag'."
12847 (interactive)
12848 (let* ((t1 org-track-ordered-property-with-tag)
12849 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12850 (save-excursion
12851 (org-back-to-heading)
12852 (if (org-entry-get nil "ORDERED")
12853 (progn
12854 (org-delete-property "ORDERED")
12855 (and tag (org-toggle-tag tag 'off))
12856 (message "Subtasks can be completed in arbitrary order"))
12857 (org-entry-put nil "ORDERED" "t")
12858 (and tag (org-toggle-tag tag 'on))
12859 (message "Subtasks must be completed in sequence")))))
12861 (defun org-block-todo-from-checkboxes (change-plist)
12862 "Block turning an entry into a TODO, using checkboxes.
12863 This checks whether the current task should be blocked from state
12864 changes because there are unchecked boxes in this entry."
12865 (if (not org-enforce-todo-checkbox-dependencies)
12866 t ; if locally turned off don't block
12867 (catch 'dont-block
12868 ;; If this is not a todo state change, or if this entry is already DONE,
12869 ;; do not block
12870 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12871 (member (plist-get change-plist :from)
12872 (cons 'done org-done-keywords))
12873 (member (plist-get change-plist :to)
12874 (cons 'todo org-not-done-keywords))
12875 (not (plist-get change-plist :to)))
12876 (throw 'dont-block t))
12877 ;; If this task has checkboxes that are not checked, it's blocked
12878 (save-excursion
12879 (org-back-to-heading t)
12880 (let ((beg (point)) end)
12881 (outline-next-heading)
12882 (setq end (point))
12883 (goto-char beg)
12884 (when (org-list-search-forward
12885 (concat (org-item-beginning-re)
12886 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12887 "\\[[- ]\\]")
12888 end t)
12889 (when (boundp 'org-blocked-by-checkboxes)
12890 (setq org-blocked-by-checkboxes t))
12891 (throw 'dont-block nil))))
12892 t))) ; do not block
12894 (defun org-entry-blocked-p ()
12895 "Non-nil if entry at point is blocked."
12896 (and (not (org-entry-get nil "NOBLOCKING"))
12897 (member (org-entry-get nil "TODO") org-not-done-keywords)
12898 (not (run-hook-with-args-until-failure
12899 'org-blocker-hook
12900 (list :type 'todo-state-change
12901 :position (point)
12902 :from 'todo
12903 :to 'done)))))
12905 (defun org-update-statistics-cookies (all)
12906 "Update the statistics cookie, either from TODO or from checkboxes.
12907 This should be called with the cursor in a line with a statistics
12908 cookie. When called with a \\[universal-argument] prefix, update
12909 all statistics cookies in the buffer."
12910 (interactive "P")
12911 (if all
12912 (progn
12913 (org-update-checkbox-count 'all)
12914 (org-map-entries 'org-update-parent-todo-statistics))
12915 (if (not (org-at-heading-p))
12916 (org-update-checkbox-count)
12917 (let ((pos (point-marker))
12918 end l1 l2)
12919 (ignore-errors (org-back-to-heading t))
12920 (if (not (org-at-heading-p))
12921 (org-update-checkbox-count)
12922 (setq l1 (org-outline-level))
12923 (setq end (save-excursion
12924 (outline-next-heading)
12925 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12926 (point)))
12927 (if (and (save-excursion
12928 (re-search-forward
12929 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12930 (not (save-excursion (re-search-forward
12931 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12932 (org-update-checkbox-count)
12933 (if (and l2 (> l2 l1))
12934 (progn
12935 (goto-char end)
12936 (org-update-parent-todo-statistics))
12937 (goto-char pos)
12938 (beginning-of-line 1)
12939 (while (re-search-forward
12940 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12941 (point-at-eol) t)
12942 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12943 (goto-char pos)
12944 (move-marker pos nil)))))
12946 (defvar org-entry-property-inherited-from) ;; defined below
12947 (defun org-update-parent-todo-statistics ()
12948 "Update any statistics cookie in the parent of the current headline.
12949 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12950 the entire subtree and this will travel up the hierarchy and update
12951 statistics everywhere."
12952 (let* ((prop (save-excursion (org-up-heading-safe)
12953 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12954 (recursive (or (not org-hierarchical-todo-statistics)
12955 (and prop (string-match "\\<recursive\\>" prop))))
12956 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12958 (first t)
12959 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12960 level ltoggle l1 new ndel
12961 (cnt-all 0) (cnt-done 0) is-percent kwd
12962 checkbox-beg cookie-present)
12963 (catch 'exit
12964 (save-excursion
12965 (beginning-of-line 1)
12966 (setq ltoggle (funcall outline-level))
12967 ;; Three situations are to consider:
12969 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12970 ;; to the top-level ancestor on the headline;
12972 ;; 2. If parent has "recursive" property, repeat up to the
12973 ;; headline setting that property, taking inheritance into
12974 ;; account;
12976 ;; 3. Else, move up to direct parent and proceed only once.
12977 (while (and (setq level (org-up-heading-safe))
12978 (or recursive first)
12979 (>= (point) lim))
12980 (setq first nil cookie-present nil)
12981 (unless (and level
12982 (not (string-match
12983 "\\<checkbox\\>"
12984 (downcase (or (org-entry-get nil "COOKIE_DATA")
12985 "")))))
12986 (throw 'exit nil))
12987 (while (re-search-forward box-re (point-at-eol) t)
12988 (setq cnt-all 0 cnt-done 0 cookie-present t)
12989 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12990 (save-match-data
12991 (unless (outline-next-heading) (throw 'exit nil))
12992 (while (and (looking-at org-complex-heading-regexp)
12993 (> (setq l1 (length (match-string 1))) level))
12994 (setq kwd (and (or recursive (= l1 ltoggle))
12995 (match-string 2)))
12996 (if (or (eq org-provide-todo-statistics 'all-headlines)
12997 (and (eq org-provide-todo-statistics t)
12998 (or (member kwd org-done-keywords)))
12999 (and (listp org-provide-todo-statistics)
13000 (stringp (car org-provide-todo-statistics))
13001 (or (member kwd org-provide-todo-statistics)
13002 (member kwd org-done-keywords)))
13003 (and (listp org-provide-todo-statistics)
13004 (listp (car org-provide-todo-statistics))
13005 (or (member kwd (car org-provide-todo-statistics))
13006 (and (member kwd org-done-keywords)
13007 (member kwd (cadr org-provide-todo-statistics))))))
13008 (setq cnt-all (1+ cnt-all))
13009 (and (eq org-provide-todo-statistics t)
13011 (setq cnt-all (1+ cnt-all))))
13012 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13013 (member kwd org-done-keywords))
13014 (and (listp org-provide-todo-statistics)
13015 (listp (car org-provide-todo-statistics))
13016 (member kwd org-done-keywords)
13017 (member kwd (cadr org-provide-todo-statistics)))
13018 (and (listp org-provide-todo-statistics)
13019 (stringp (car org-provide-todo-statistics))
13020 (member kwd org-done-keywords)))
13021 (setq cnt-done (1+ cnt-done)))
13022 (outline-next-heading)))
13023 (setq new
13024 (if is-percent
13025 (format "[%d%%]" (floor (* 100.0 cnt-done)
13026 (max 1 cnt-all)))
13027 (format "[%d/%d]" cnt-done cnt-all))
13028 ndel (- (match-end 0) checkbox-beg))
13029 (goto-char checkbox-beg)
13030 (insert new)
13031 (delete-region (point) (+ (point) ndel))
13032 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13033 (when cookie-present
13034 (run-hook-with-args 'org-after-todo-statistics-hook
13035 cnt-done (- cnt-all cnt-done))))))
13036 (run-hooks 'org-todo-statistics-hook)))
13038 (defvar org-after-todo-statistics-hook nil
13039 "Hook that is called after a TODO statistics cookie has been updated.
13040 Each function is called with two arguments: the number of not-done entries
13041 and the number of done entries.
13043 For example, the following function, when added to this hook, will switch
13044 an entry to DONE when all children are done, and back to TODO when new
13045 entries are set to a TODO status. Note that this hook is only called
13046 when there is a statistics cookie in the headline!
13048 (defun org-summary-todo (n-done n-not-done)
13049 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13050 (let (org-log-done org-log-states) ; turn off logging
13051 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13054 (defvar org-todo-statistics-hook nil
13055 "Hook that is run whenever Org thinks TODO statistics should be updated.
13056 This hook runs even if there is no statistics cookie present, in which case
13057 `org-after-todo-statistics-hook' would not run.")
13059 (defun org-todo-trigger-tag-changes (state)
13060 "Apply the changes defined in `org-todo-state-tags-triggers'."
13061 (let ((l org-todo-state-tags-triggers)
13062 changes)
13063 (when (or (not state) (equal state ""))
13064 (setq changes (append changes (cdr (assoc "" l)))))
13065 (when (and (stringp state) (> (length state) 0))
13066 (setq changes (append changes (cdr (assoc state l)))))
13067 (when (member state org-not-done-keywords)
13068 (setq changes (append changes (cdr (assq 'todo l)))))
13069 (when (member state org-done-keywords)
13070 (setq changes (append changes (cdr (assq 'done l)))))
13071 (dolist (c changes)
13072 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13074 (defun org-local-logging (value)
13075 "Get logging settings from a property VALUE."
13076 ;; Directly set the variables, they are already local.
13077 (setq org-log-done nil
13078 org-log-repeat nil
13079 org-todo-log-states nil)
13080 (dolist (w (org-split-string value))
13081 (let (a)
13082 (cond
13083 ((setq a (assoc w org-startup-options))
13084 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13085 (set (nth 1 a) (nth 2 a))))
13086 ((setq a (org-extract-log-state-settings w))
13087 (and (member (car a) org-todo-keywords-1)
13088 (push a org-todo-log-states)))))))
13090 (defun org-get-todo-sequence-head (kwd)
13091 "Return the head of the TODO sequence to which KWD belongs.
13092 If KWD is not set, check if there is a text property remembering the
13093 right sequence."
13094 (let (p)
13095 (cond
13096 ((not kwd)
13097 (or (get-text-property (point-at-bol) 'org-todo-head)
13098 (progn
13099 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13100 nil (point-at-eol)))
13101 (get-text-property p 'org-todo-head))))
13102 ((not (member kwd org-todo-keywords-1))
13103 (car org-todo-keywords-1))
13104 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13106 (defun org-fast-todo-selection ()
13107 "Fast TODO keyword selection with single keys.
13108 Returns the new TODO keyword, or nil if no state change should occur."
13109 (let* ((fulltable org-todo-key-alist)
13110 (done-keywords org-done-keywords) ;; needed for the faces.
13111 (maxlen (apply 'max (mapcar
13112 (lambda (x)
13113 (if (stringp (car x)) (string-width (car x)) 0))
13114 fulltable)))
13115 (expert nil)
13116 (fwidth (+ maxlen 3 1 3))
13117 (ncol (/ (- (window-width) 4) fwidth))
13118 tg cnt e c tbl
13119 groups ingroup)
13120 (save-excursion
13121 (save-window-excursion
13122 (if expert
13123 (set-buffer (get-buffer-create " *Org todo*"))
13124 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13125 (erase-buffer)
13126 (setq-local org-done-keywords done-keywords)
13127 (setq tbl fulltable cnt 0)
13128 (while (setq e (pop tbl))
13129 (cond
13130 ((equal e '(:startgroup))
13131 (push '() groups) (setq ingroup t)
13132 (unless (= cnt 0)
13133 (setq cnt 0)
13134 (insert "\n"))
13135 (insert "{ "))
13136 ((equal e '(:endgroup))
13137 (setq ingroup nil cnt 0)
13138 (insert "}\n"))
13139 ((equal e '(:newline))
13140 (unless (= cnt 0)
13141 (setq cnt 0)
13142 (insert "\n")
13143 (setq e (car tbl))
13144 (while (equal (car tbl) '(:newline))
13145 (insert "\n")
13146 (setq tbl (cdr tbl)))))
13148 (setq tg (car e) c (cdr e))
13149 (when ingroup (push tg (car groups)))
13150 (setq tg (org-add-props tg nil 'face
13151 (org-get-todo-face tg)))
13152 (when (and (= cnt 0) (not ingroup)) (insert " "))
13153 (insert "[" c "] " tg (make-string
13154 (- fwidth 4 (length tg)) ?\ ))
13155 (when (= (setq cnt (1+ cnt)) ncol)
13156 (insert "\n")
13157 (when ingroup (insert " "))
13158 (setq cnt 0)))))
13159 (insert "\n")
13160 (goto-char (point-min))
13161 (unless expert (org-fit-window-to-buffer))
13162 (message "[a-z..]:Set [SPC]:clear")
13163 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13164 (cond
13165 ((or (= c ?\C-g)
13166 (and (= c ?q) (not (rassoc c fulltable))))
13167 (setq quit-flag t))
13168 ((= c ?\ ) nil)
13169 ((setq e (rassoc c fulltable) tg (car e))
13171 (t (setq quit-flag t)))))))
13173 (defun org-entry-is-todo-p ()
13174 (member (org-get-todo-state) org-not-done-keywords))
13176 (defun org-entry-is-done-p ()
13177 (member (org-get-todo-state) org-done-keywords))
13179 (defun org-get-todo-state ()
13180 "Return the TODO keyword of the current subtree."
13181 (save-excursion
13182 (org-back-to-heading t)
13183 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13184 (match-end 2)
13185 (match-string 2))))
13187 (defun org-at-date-range-p (&optional inactive-ok)
13188 "Non-nil if point is inside a date range.
13190 When optional argument INACTIVE-OK is non-nil, also consider
13191 inactive time ranges.
13193 When this function returns a non-nil value, match data is set
13194 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13195 on INACTIVE-OK."
13196 (interactive)
13197 (save-excursion
13198 (catch 'exit
13199 (let ((pos (point)))
13200 (skip-chars-backward "^[<\r\n")
13201 (skip-chars-backward "<[")
13202 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13203 (>= (match-end 0) pos)
13204 (throw 'exit t))
13205 (skip-chars-backward "^<[\r\n")
13206 (skip-chars-backward "<[")
13207 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13208 (>= (match-end 0) pos)
13209 (throw 'exit t)))
13210 nil)))
13212 (defun org-get-repeat (&optional tagline)
13213 "Check if there is a deadline/schedule with repeater in this entry."
13214 (save-match-data
13215 (save-excursion
13216 (org-back-to-heading t)
13217 (and (re-search-forward (if tagline
13218 (concat tagline "\\s-*" org-repeat-re)
13219 org-repeat-re)
13220 (org-entry-end-position) t)
13221 (match-string-no-properties 1)))))
13223 (defvar org-last-changed-timestamp)
13224 (defvar org-last-inserted-timestamp)
13225 (defvar org-log-post-message)
13226 (defvar org-log-note-purpose)
13227 (defvar org-log-note-how nil)
13228 (defvar org-log-note-extra)
13229 (defun org-auto-repeat-maybe (done-word)
13230 "Check if the current headline contains a repeated time-stamp.
13232 If yes, set TODO state back to what it was and change the base date
13233 of repeating deadline/scheduled time stamps to new date.
13235 This function is run automatically after each state change to a DONE state."
13236 (let* ((repeat (org-get-repeat))
13237 (aa (assoc org-last-state org-todo-kwd-alist))
13238 (interpret (nth 1 aa))
13239 (head (nth 2 aa))
13240 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13241 (msg "Entry repeats: ")
13242 (org-log-done nil)
13243 (org-todo-log-states nil))
13244 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13245 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13246 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13247 org-todo-repeat-to-state)))
13248 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
13249 to-state)
13250 ((eq interpret 'type) org-last-state)
13251 (head)
13252 (t 'none))))
13253 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13254 (org-entry-put nil "LAST_REPEAT" (format-time-string
13255 (org-time-stamp-format t t))))
13256 (when org-log-repeat
13257 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13258 (memq 'org-add-log-note post-command-hook))
13259 ;; We are already setup for some record.
13260 (when (eq org-log-repeat 'note)
13261 ;; Make sure we take a note, not only a time stamp.
13262 (setq org-log-note-how 'note))
13263 ;; Set up for taking a record.
13264 (org-add-log-setup 'state
13265 (or done-word (car org-done-keywords))
13266 org-last-state
13267 org-log-repeat)))
13268 (org-back-to-heading t)
13269 (org-add-planning-info nil nil 'closed)
13270 (let ((end (save-excursion (outline-next-heading) (point)))
13271 (planning-re (regexp-opt
13272 (list org-scheduled-string org-deadline-string))))
13273 (while (re-search-forward org-ts-regexp end t)
13274 (let* ((ts (match-string 0))
13275 (planning? (org-at-planning-p))
13276 (type (if (not planning?) "Plain:"
13277 (save-excursion
13278 (re-search-backward
13279 planning-re (line-beginning-position) t)
13280 (match-string 0)))))
13281 (cond
13282 ;; Ignore fake time-stamps (e.g., within comments).
13283 ((and (not planning?)
13284 (not (org-at-property-p))
13285 (not (eq 'timestamp
13286 (org-element-type (save-excursion
13287 (backward-char)
13288 (org-element-context)))))))
13289 ;; Time-stamps without a repeater are usually skipped.
13290 ;; However, a SCHEDULED time-stamp without one is
13291 ;; removed, as it is considered as no longer relevant.
13292 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13293 (when (equal type org-scheduled-string)
13294 (org-remove-timestamp-with-keyword type)))
13296 (let ((n (string-to-number (match-string 2 ts)))
13297 (what (match-string 3 ts)))
13298 (when (equal what "w") (setq n (* n 7) what "d"))
13299 (when (and (equal what "h")
13300 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13301 ts)))
13302 (user-error
13303 "Cannot repeat in Repeat in %d hour(s) because no hour \
13304 has been set"
13306 ;; Preparation, see if we need to modify the start
13307 ;; date for the change.
13308 (when (match-end 1)
13309 (let ((time (save-match-data (org-time-string-to-time ts))))
13310 (cond
13311 ((equal (match-string 1 ts) ".")
13312 ;; Shift starting date to today
13313 (org-timestamp-change
13314 (- (org-today) (time-to-days time))
13315 'day))
13316 ((equal (match-string 1 ts) "+")
13317 (let ((nshiftmax 10)
13318 (nshift 0))
13319 (while (or (= nshift 0)
13320 (not (time-less-p (current-time) time)))
13321 (when (= (cl-incf nshift) nshiftmax)
13322 (or (y-or-n-p
13323 (format "%d repeater intervals were not \
13324 enough to shift date past today. Continue? "
13325 nshift))
13326 (user-error "Abort")))
13327 (org-timestamp-change n (cdr (assoc what whata)))
13328 (org-at-timestamp-p t)
13329 (setq ts (match-string 1))
13330 (setq time
13331 (save-match-data
13332 (org-time-string-to-time ts)))))
13333 (org-timestamp-change (- n) (cdr (assoc what whata)))
13334 ;; Rematch, so that we have everything in place
13335 ;; for the real shift.
13336 (org-at-timestamp-p t)
13337 (setq ts (match-string 1))
13338 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13339 ts)))))
13340 (save-excursion
13341 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13342 (setq msg
13343 (concat
13344 msg type " " org-last-changed-timestamp " "))))))))
13345 (setq org-log-post-message msg)
13346 (message "%s" msg))))
13348 (defun org-show-todo-tree (arg)
13349 "Make a compact tree which shows all headlines marked with TODO.
13350 The tree will show the lines where the regexp matches, and all higher
13351 headlines above the match.
13352 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13353 With a numeric prefix N, construct a sparse tree for the Nth element
13354 of `org-todo-keywords-1'."
13355 (interactive "P")
13356 (let ((case-fold-search nil)
13357 (kwd-re
13358 (cond ((null arg) org-not-done-regexp)
13359 ((equal arg '(4))
13360 (let ((kwd
13361 (completing-read "Keyword (or KWD1|KWD2|...): "
13362 (mapcar #'list org-todo-keywords-1))))
13363 (concat "\\("
13364 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13365 "\\)\\>")))
13366 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13367 (regexp-quote (nth (1- (prefix-numeric-value arg))
13368 org-todo-keywords-1)))
13369 (t (user-error "Invalid prefix argument: %s" arg)))))
13370 (message "%d TODO entries found"
13371 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13373 (defun org--deadline-or-schedule (arg type time)
13374 "Insert DEADLINE or SCHEDULE information in current entry.
13375 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13376 `org-schedule' for information about ARG and TIME arguments."
13377 (let* ((deadline? (eq type 'deadline))
13378 (keyword (if deadline? org-deadline-string org-scheduled-string))
13379 (log (if deadline? org-log-redeadline org-log-reschedule))
13380 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13381 (old-date-time (and old-date (org-time-string-to-time old-date)))
13382 ;; Save repeater cookie from either TIME or current scheduled
13383 ;; time stamp. We are going to insert it back at the end of
13384 ;; the process.
13385 (repeater (or (and (org-string-nw-p time)
13386 ;; We use `org-repeat-re' because we need
13387 ;; to tell the difference between a real
13388 ;; repeater and a time delta, e.g. "+2d".
13389 (string-match org-repeat-re time)
13390 (match-string 1 time))
13391 (and (org-string-nw-p old-date)
13392 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13393 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13394 old-date)
13395 (match-string 1 old-date)))))
13396 (pcase arg
13397 (`(4)
13398 (when (and old-date log)
13399 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13400 nil old-date log))
13401 (org-remove-timestamp-with-keyword keyword)
13402 (message (if deadline? "Item no longer has a deadline."
13403 "Item is no longer scheduled.")))
13404 (`(16)
13405 (save-excursion
13406 (org-back-to-heading t)
13407 (let ((regexp (if deadline? org-deadline-time-regexp
13408 org-scheduled-time-regexp)))
13409 (if (not (re-search-forward regexp (line-end-position 2) t))
13410 (user-error (if deadline? "No deadline information to update"
13411 "No scheduled information to update"))
13412 (let* ((rpl0 (match-string 1))
13413 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13414 (msg (if deadline? "Warn starting from" "Delay until")))
13415 (replace-match
13416 (concat keyword
13417 " <" rpl
13418 (format " -%dd"
13419 (abs (- (time-to-days
13420 (save-match-data
13421 (org-read-date
13422 nil t nil msg old-date-time)))
13423 (time-to-days old-date-time))))
13424 ">") t t))))))
13426 (org-add-planning-info type time 'closed)
13427 (when (and old-date
13429 (not (equal old-date org-last-inserted-timestamp)))
13430 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13431 org-last-inserted-timestamp
13432 old-date
13433 log))
13434 (when repeater
13435 (save-excursion
13436 (org-back-to-heading t)
13437 (when (re-search-forward
13438 (concat keyword " " org-last-inserted-timestamp)
13439 (line-end-position 2)
13441 (goto-char (1- (match-end 0)))
13442 (insert " " repeater)
13443 (setq org-last-inserted-timestamp
13444 (concat (substring org-last-inserted-timestamp 0 -1)
13445 " " repeater
13446 (substring org-last-inserted-timestamp -1))))))
13447 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13448 org-last-inserted-timestamp)))))
13450 (defun org-deadline (arg &optional time)
13451 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13452 With one universal prefix argument, remove any deadline from the item.
13453 With two universal prefix arguments, prompt for a warning delay.
13454 With argument TIME, set the deadline at the corresponding date. TIME
13455 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13456 (interactive "P")
13457 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13458 (org-map-entries
13459 (lambda () (org--deadline-or-schedule arg 'deadline time))
13461 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13462 'region-start-level
13463 'region)
13464 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13465 (org--deadline-or-schedule arg 'deadline time)))
13467 (defun org-schedule (arg &optional time)
13468 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13469 With one universal prefix argument, remove any scheduling date from the item.
13470 With two universal prefix arguments, prompt for a delay cookie.
13471 With argument TIME, scheduled at the corresponding date. TIME can
13472 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13473 (interactive "P")
13474 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13475 (org-map-entries
13476 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13478 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13479 'region-start-level
13480 'region)
13481 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13482 (org--deadline-or-schedule arg 'scheduled time)))
13484 (defun org-get-scheduled-time (pom &optional inherit)
13485 "Get the scheduled time as a time tuple, of a format suitable
13486 for calling org-schedule with, or if there is no scheduling,
13487 returns nil."
13488 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13489 (when time
13490 (apply 'encode-time (org-parse-time-string time)))))
13492 (defun org-get-deadline-time (pom &optional inherit)
13493 "Get the deadline as a time tuple, of a format suitable for
13494 calling org-deadline with, or if there is no scheduling, returns
13495 nil."
13496 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13497 (when time
13498 (apply 'encode-time (org-parse-time-string time)))))
13500 (defun org-remove-timestamp-with-keyword (keyword)
13501 "Remove all time stamps with KEYWORD in the current entry."
13502 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13503 beg)
13504 (save-excursion
13505 (org-back-to-heading t)
13506 (setq beg (point))
13507 (outline-next-heading)
13508 (while (re-search-backward re beg t)
13509 (replace-match "")
13510 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13511 (equal (char-before) ?\ ))
13512 (backward-delete-char 1)
13513 (when (string-match "^[ \t]*$" (buffer-substring
13514 (point-at-bol) (point-at-eol)))
13515 (delete-region (point-at-bol)
13516 (min (point-max) (1+ (point-at-eol))))))))))
13518 (defvar org-time-was-given) ; dynamically scoped parameter
13519 (defvar org-end-time-was-given) ; dynamically scoped parameter
13521 (defun org-at-planning-p ()
13522 "Non-nil when point is on a planning info line."
13523 ;; This is as accurate and faster than `org-element-at-point' since
13524 ;; planning info location is fixed in the section.
13525 (org-with-wide-buffer
13526 (beginning-of-line)
13527 (and (looking-at-p org-planning-line-re)
13528 (eq (point)
13529 (ignore-errors
13530 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13531 (org-back-to-heading t)
13532 (org-with-limited-levels (org-back-to-heading t)))
13533 (line-beginning-position 2))))))
13535 (defun org-add-planning-info (what &optional time &rest remove)
13536 "Insert new timestamp with keyword in the planning line.
13537 WHAT indicates what kind of time stamp to add. It is a symbol
13538 among `closed', `deadline', `scheduled' and nil. TIME indicates
13539 the time to use. If none is given, the user is prompted for
13540 a date. REMOVE indicates what kind of entries to remove. An old
13541 WHAT entry will also be removed."
13542 (let (org-time-was-given org-end-time-was-given default-time default-input)
13543 (catch 'exit
13544 (when (and (memq what '(scheduled deadline))
13545 (or (not time)
13546 (and (stringp time)
13547 (string-match "^[-+]+[0-9]" time))))
13548 ;; Try to get a default date/time from existing timestamp
13549 (save-excursion
13550 (org-back-to-heading t)
13551 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13552 (when (re-search-forward (if (eq what 'scheduled)
13553 org-scheduled-time-regexp
13554 org-deadline-time-regexp)
13555 end t)
13556 (setq ts (match-string 1)
13557 default-time (apply 'encode-time (org-parse-time-string ts))
13558 default-input (and ts (org-get-compact-tod ts)))))))
13559 (when what
13560 (setq time
13561 (if (stringp time)
13562 ;; This is a string (relative or absolute), set
13563 ;; proper date.
13564 (apply #'encode-time
13565 (org-read-date-analyze
13566 time default-time (decode-time default-time)))
13567 ;; If necessary, get the time from the user
13568 (or time (org-read-date nil 'to-time nil nil
13569 default-time default-input)))))
13571 (org-with-wide-buffer
13572 (org-back-to-heading t)
13573 (forward-line)
13574 (unless (bolp) (insert "\n"))
13575 (cond ((looking-at-p org-planning-line-re)
13576 ;; Move to current indentation.
13577 (skip-chars-forward " \t")
13578 ;; Check if we have to remove something.
13579 (dolist (type (if what (cons what remove) remove))
13580 (save-excursion
13581 (when (re-search-forward
13582 (cl-case type
13583 (closed org-closed-time-regexp)
13584 (deadline org-deadline-time-regexp)
13585 (scheduled org-scheduled-time-regexp)
13586 (otherwise
13587 (error "Invalid planning type: %s" type)))
13588 (line-end-position) t)
13589 ;; Delete until next keyword or end of line.
13590 (delete-region
13591 (match-beginning 0)
13592 (if (re-search-forward org-keyword-time-not-clock-regexp
13593 (line-end-position)
13595 (match-beginning 0)
13596 (line-end-position))))))
13597 ;; If there is nothing more to add and no more keyword
13598 ;; is left, remove the line completely.
13599 (if (and (looking-at-p "[ \t]*$") (not what))
13600 (delete-region (line-beginning-position)
13601 (line-beginning-position 2))
13602 ;; If we removed last keyword, do not leave trailing
13603 ;; white space at the end of line.
13604 (let ((p (point)))
13605 (save-excursion
13606 (end-of-line)
13607 (unless (= (skip-chars-backward " \t" p) 0)
13608 (delete-region (point) (line-end-position)))))))
13609 ((not what) (throw 'exit nil)) ; Nothing to do.
13610 (t (insert-before-markers "\n")
13611 (backward-char 1)
13612 (when org-adapt-indentation
13613 (indent-to-column (1+ (org-outline-level))))))
13614 (when what
13615 ;; Insert planning keyword.
13616 (insert (cl-case what
13617 (closed org-closed-string)
13618 (deadline org-deadline-string)
13619 (scheduled org-scheduled-string)
13620 (otherwise (error "Invalid planning type: %s" what)))
13621 " ")
13622 ;; Insert associated timestamp.
13623 (let ((ts (org-insert-time-stamp
13624 time
13625 (or org-time-was-given
13626 (and (eq what 'closed) org-log-done-with-time))
13627 (eq what 'closed)
13628 nil nil (list org-end-time-was-given))))
13629 (unless (eolp) (insert " "))
13630 ts))))))
13632 (defvar org-log-note-marker (make-marker)
13633 "Marker pointing at the entry where the note is to be inserted.")
13634 (defvar org-log-note-purpose nil)
13635 (defvar org-log-note-state nil)
13636 (defvar org-log-note-previous-state nil)
13637 (defvar org-log-note-extra nil)
13638 (defvar org-log-note-window-configuration nil)
13639 (defvar org-log-note-return-to (make-marker))
13640 (defvar org-log-note-effective-time nil
13641 "Remembered current time so that dynamically scoped
13642 `org-extend-today-until' affects timestamps in state change log")
13644 (defvar org-log-post-message nil
13645 "Message to be displayed after a log note has been stored.
13646 The auto-repeater uses this.")
13648 (defun org-add-note ()
13649 "Add a note to the current entry.
13650 This is done in the same way as adding a state change note."
13651 (interactive)
13652 (org-add-log-setup 'note))
13654 (defun org-log-beginning (&optional create)
13655 "Return expected start of log notes in current entry.
13656 When optional argument CREATE is non-nil, the function creates
13657 a drawer to store notes, if necessary. Returned position ignores
13658 narrowing."
13659 (org-with-wide-buffer
13660 (let ((drawer (org-log-into-drawer)))
13661 (cond
13662 (drawer
13663 (org-end-of-meta-data)
13664 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13665 (end (if (org-at-heading-p) (point)
13666 (save-excursion (outline-next-heading) (point))))
13667 (case-fold-search t))
13668 (catch 'exit
13669 ;; Try to find existing drawer.
13670 (while (re-search-forward regexp end t)
13671 (let ((element (org-element-at-point)))
13672 (when (eq (org-element-type element) 'drawer)
13673 (let ((cend (org-element-property :contents-end element)))
13674 (when (and (not org-log-states-order-reversed) cend)
13675 (goto-char cend)))
13676 (throw 'exit nil))))
13677 ;; No drawer found. Create one, if permitted.
13678 (when create
13679 (unless (bolp) (insert "\n"))
13680 (let ((beg (point)))
13681 (insert ":" drawer ":\n:END:\n")
13682 (org-indent-region beg (point)))
13683 (end-of-line -1)))))
13685 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13686 (skip-chars-forward " \t\n")
13687 (beginning-of-line)
13688 (unless org-log-states-order-reversed
13689 (org-skip-over-state-notes)
13690 (skip-chars-backward " \t\n")
13691 (forward-line)))))
13692 (if (bolp) (point) (line-beginning-position 2))))
13694 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13695 "Set up the post command hook to take a note.
13696 If this is about to TODO state change, the new state is expected in STATE.
13697 HOW is an indicator what kind of note should be created.
13698 EXTRA is additional text that will be inserted into the notes buffer."
13699 (move-marker org-log-note-marker (point))
13700 (setq org-log-note-purpose purpose
13701 org-log-note-state state
13702 org-log-note-previous-state prev-state
13703 org-log-note-how how
13704 org-log-note-extra extra
13705 org-log-note-effective-time (org-current-effective-time))
13706 (add-hook 'post-command-hook 'org-add-log-note 'append))
13708 (defun org-skip-over-state-notes ()
13709 "Skip past the list of State notes in an entry."
13710 (when (ignore-errors (goto-char (org-in-item-p)))
13711 (let* ((struct (org-list-struct))
13712 (prevs (org-list-prevs-alist struct))
13713 (regexp
13714 (concat "[ \t]*- +"
13715 (replace-regexp-in-string
13716 " +" " +"
13717 (org-replace-escapes
13718 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13719 `(("%d" . ,org-ts-regexp-inactive)
13720 ("%D" . ,org-ts-regexp)
13721 ("%s" . "\"\\S-+\"")
13722 ("%S" . "\"\\S-+\"")
13723 ("%t" . ,org-ts-regexp-inactive)
13724 ("%T" . ,org-ts-regexp)
13725 ("%u" . ".*?")
13726 ("%U" . ".*?")))))))
13727 (while (looking-at-p regexp)
13728 (goto-char (or (org-list-get-next-item (point) struct prevs)
13729 (org-list-get-item-end (point) struct)))))))
13731 (defun org-add-log-note (&optional _purpose)
13732 "Pop up a window for taking a note, and add this note later."
13733 (remove-hook 'post-command-hook 'org-add-log-note)
13734 (setq org-log-note-window-configuration (current-window-configuration))
13735 (delete-other-windows)
13736 (move-marker org-log-note-return-to (point))
13737 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13738 (goto-char org-log-note-marker)
13739 (org-switch-to-buffer-other-window "*Org Note*")
13740 (erase-buffer)
13741 (if (memq org-log-note-how '(time state))
13742 (org-store-log-note)
13743 (let ((org-inhibit-startup t)) (org-mode))
13744 (insert (format "# Insert note for %s.
13745 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13746 (cond
13747 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13748 ((eq org-log-note-purpose 'done) "closed todo item")
13749 ((eq org-log-note-purpose 'state)
13750 (format "state change from \"%s\" to \"%s\""
13751 (or org-log-note-previous-state "")
13752 (or org-log-note-state "")))
13753 ((eq org-log-note-purpose 'reschedule)
13754 "rescheduling")
13755 ((eq org-log-note-purpose 'delschedule)
13756 "no longer scheduled")
13757 ((eq org-log-note-purpose 'redeadline)
13758 "changing deadline")
13759 ((eq org-log-note-purpose 'deldeadline)
13760 "removing deadline")
13761 ((eq org-log-note-purpose 'refile)
13762 "refiling")
13763 ((eq org-log-note-purpose 'note)
13764 "this entry")
13765 (t (error "This should not happen")))))
13766 (when org-log-note-extra (insert org-log-note-extra))
13767 (setq-local org-finish-function 'org-store-log-note)
13768 (run-hooks 'org-log-buffer-setup-hook)))
13770 (defvar org-note-abort nil) ; dynamically scoped
13771 (defun org-store-log-note ()
13772 "Finish taking a log note, and insert it to where it belongs."
13773 (let ((txt (prog1 (buffer-string)
13774 (kill-buffer)))
13775 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13776 lines)
13777 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13778 (setq txt (replace-match "" t t txt)))
13779 (when (string-match "\\s-+\\'" txt)
13780 (setq txt (replace-match "" t t txt)))
13781 (setq lines (org-split-string txt "\n"))
13782 (when (org-string-nw-p note)
13783 (setq note
13784 (org-replace-escapes
13785 note
13786 (list (cons "%u" (user-login-name))
13787 (cons "%U" user-full-name)
13788 (cons "%t" (format-time-string
13789 (org-time-stamp-format 'long 'inactive)
13790 org-log-note-effective-time))
13791 (cons "%T" (format-time-string
13792 (org-time-stamp-format 'long nil)
13793 org-log-note-effective-time))
13794 (cons "%d" (format-time-string
13795 (org-time-stamp-format nil 'inactive)
13796 org-log-note-effective-time))
13797 (cons "%D" (format-time-string
13798 (org-time-stamp-format nil nil)
13799 org-log-note-effective-time))
13800 (cons "%s" (cond
13801 ((not org-log-note-state) "")
13802 ((string-match-p org-ts-regexp
13803 org-log-note-state)
13804 (format "\"[%s]\""
13805 (substring org-log-note-state 1 -1)))
13806 (t (format "\"%s\"" org-log-note-state))))
13807 (cons "%S"
13808 (cond
13809 ((not org-log-note-previous-state) "")
13810 ((string-match-p org-ts-regexp
13811 org-log-note-previous-state)
13812 (format "\"[%s]\""
13813 (substring
13814 org-log-note-previous-state 1 -1)))
13815 (t (format "\"%s\""
13816 org-log-note-previous-state)))))))
13817 (when lines (setq note (concat note " \\\\")))
13818 (push note lines))
13819 (when (and lines (not org-note-abort))
13820 (with-current-buffer (marker-buffer org-log-note-marker)
13821 (org-with-wide-buffer
13822 ;; Find location for the new note.
13823 (goto-char org-log-note-marker)
13824 (set-marker org-log-note-marker nil)
13825 ;; Note associated to a clock is to be located right after
13826 ;; the clock. Do not move point.
13827 (unless (eq org-log-note-purpose 'clock-out)
13828 (goto-char (org-log-beginning t)))
13829 ;; Make sure point is at the beginning of an empty line.
13830 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13831 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13832 ;; In an existing list, add a new item at the top level.
13833 ;; Otherwise, indent line like a regular one.
13834 (let ((itemp (org-in-item-p)))
13835 (if itemp
13836 (indent-line-to
13837 (let ((struct (save-excursion
13838 (goto-char itemp) (org-list-struct))))
13839 (org-list-get-ind (org-list-get-top-point struct) struct)))
13840 (org-indent-line)))
13841 (insert (org-list-bullet-string "-") (pop lines))
13842 (let ((ind (org-list-item-body-column (line-beginning-position))))
13843 (dolist (line lines)
13844 (insert "\n")
13845 (indent-line-to ind)
13846 (insert line)))
13847 (message "Note stored")
13848 (org-back-to-heading t)
13849 (org-cycle-hide-drawers 'children))
13850 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13851 ;; from within `org-add-log-note' because `buffer-undo-list'
13852 ;; is then modified outside of `org-with-remote-undo'.
13853 (when (eq this-command 'org-agenda-todo)
13854 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13855 ;; Don't add undo information when called from `org-agenda-todo'.
13856 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13857 (set-window-configuration org-log-note-window-configuration)
13858 (with-current-buffer (marker-buffer org-log-note-return-to)
13859 (goto-char org-log-note-return-to))
13860 (move-marker org-log-note-return-to nil)
13861 (when org-log-post-message (message "%s" org-log-post-message))))
13863 (defun org-remove-empty-drawer-at (pos)
13864 "Remove an empty drawer at position POS.
13865 POS may also be a marker."
13866 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13867 (org-with-wide-buffer
13868 (goto-char pos)
13869 (let ((drawer (org-element-at-point)))
13870 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13871 (not (org-element-property :contents-begin drawer)))
13872 (delete-region (org-element-property :begin drawer)
13873 (progn (goto-char (org-element-property :end drawer))
13874 (skip-chars-backward " \r\t\n")
13875 (forward-line)
13876 (point))))))))
13878 (defvar org-ts-type nil)
13879 (defun org-sparse-tree (&optional arg type)
13880 "Create a sparse tree, prompt for the details.
13881 This command can create sparse trees. You first need to select the type
13882 of match used to create the tree:
13884 t Show all TODO entries.
13885 T Show entries with a specific TODO keyword.
13886 m Show entries selected by a tags/property match.
13887 p Enter a property name and its value (both with completion on existing
13888 names/values) and show entries with that property.
13889 r Show entries matching a regular expression (`/' can be used as well).
13890 b Show deadlines and scheduled items before a date.
13891 a Show deadlines and scheduled items after a date.
13892 d Show deadlines due within `org-deadline-warning-days'.
13893 D Show deadlines and scheduled items between a date range."
13894 (interactive "P")
13895 (setq type (or type org-sparse-tree-default-date-type))
13896 (setq org-ts-type type)
13897 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13898 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13899 \[c]ycle through date types: %s"
13900 (cl-case type
13901 (all "all timestamps")
13902 (scheduled "only scheduled")
13903 (deadline "only deadline")
13904 (active "only active timestamps")
13905 (inactive "only inactive timestamps")
13906 (closed "with a closed time-stamp")
13907 (otherwise "scheduled/deadline")))
13908 (let ((answer (read-char-exclusive)))
13909 (cl-case answer
13911 (org-sparse-tree
13913 (cadr
13914 (memq type '(nil all scheduled deadline active inactive closed)))))
13915 (?d (call-interactively 'org-check-deadlines))
13916 (?b (call-interactively 'org-check-before-date))
13917 (?a (call-interactively 'org-check-after-date))
13918 (?D (call-interactively 'org-check-dates-range))
13919 (?t (call-interactively 'org-show-todo-tree))
13920 (?T (org-show-todo-tree '(4)))
13921 (?m (call-interactively 'org-match-sparse-tree))
13922 ((?p ?P)
13923 (let* ((kwd (completing-read
13924 "Property: " (mapcar #'list (org-buffer-property-keys))))
13925 (value (completing-read
13926 "Value: " (mapcar #'list (org-property-values kwd)))))
13927 (unless (string-match "\\`{.*}\\'" value)
13928 (setq value (concat "\"" value "\"")))
13929 (org-match-sparse-tree arg (concat kwd "=" value))))
13930 ((?r ?R ?/) (call-interactively 'org-occur))
13931 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13933 (defvar-local org-occur-highlights nil
13934 "List of overlays used for occur matches.")
13935 (defvar-local org-occur-parameters nil
13936 "Parameters of the active org-occur calls.
13937 This is a list, each call to org-occur pushes as cons cell,
13938 containing the regular expression and the callback, onto the list.
13939 The list can contain several entries if `org-occur' has been called
13940 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13941 will only contain one set of parameters. When the highlights are
13942 removed (for example with `C-c C-c', or with the next edit (depending
13943 on `org-remove-highlights-with-change'), this variable is emptied
13944 as well.")
13946 (defun org-occur (regexp &optional keep-previous callback)
13947 "Make a compact tree which shows all matches of REGEXP.
13949 The tree will show the lines where the regexp matches, and any other context
13950 defined in `org-show-context-detail', which see.
13952 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13953 done by a previous call to `org-occur' will be kept, to allow stacking of
13954 calls to this command.
13956 Optional argument CALLBACK can be a function of no argument. In this case,
13957 it is called with point at the end of the match, match data being set
13958 accordingly. Current match is shown only if the return value is non-nil.
13959 The function must neither move point nor alter narrowing."
13960 (interactive "sRegexp: \nP")
13961 (when (equal regexp "")
13962 (user-error "Regexp cannot be empty"))
13963 (unless keep-previous
13964 (org-remove-occur-highlights nil nil t))
13965 (push (cons regexp callback) org-occur-parameters)
13966 (let ((cnt 0))
13967 (save-excursion
13968 (goto-char (point-min))
13969 (when (or (not keep-previous) ; do not want to keep
13970 (not org-occur-highlights)) ; no previous matches
13971 ;; hide everything
13972 (org-overview))
13973 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13974 (isearch-no-upper-case-p regexp t)
13975 org-occur-case-fold-search)))
13976 (while (re-search-forward regexp nil t)
13977 (when (or (not callback)
13978 (save-match-data (funcall callback)))
13979 (setq cnt (1+ cnt))
13980 (when org-highlight-sparse-tree-matches
13981 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13982 (org-show-context 'occur-tree)))))
13983 (when org-remove-highlights-with-change
13984 (add-hook 'before-change-functions 'org-remove-occur-highlights
13985 nil 'local))
13986 (unless org-sparse-tree-open-archived-trees
13987 (org-hide-archived-subtrees (point-min) (point-max)))
13988 (run-hooks 'org-occur-hook)
13989 (when (called-interactively-p 'interactive)
13990 (message "%d match(es) for regexp %s" cnt regexp))
13991 cnt))
13993 (defun org-occur-next-match (&optional n _reset)
13994 "Function for `next-error-function' to find sparse tree matches.
13995 N is the number of matches to move, when negative move backwards.
13996 This function always goes back to the starting point when no
13997 match is found."
13998 (let* ((limit (if (< n 0) (point-min) (point-max)))
13999 (search-func (if (< n 0)
14000 'previous-single-char-property-change
14001 'next-single-char-property-change))
14002 (n (abs n))
14003 (pos (point))
14005 (catch 'exit
14006 (while (setq p1 (funcall search-func (point) 'org-type))
14007 (when (equal p1 limit)
14008 (goto-char pos)
14009 (user-error "No more matches"))
14010 (when (equal (get-char-property p1 'org-type) 'org-occur)
14011 (setq n (1- n))
14012 (when (= n 0)
14013 (goto-char p1)
14014 (throw 'exit (point))))
14015 (goto-char p1))
14016 (goto-char p1)
14017 (user-error "No more matches"))))
14019 (defun org-show-context (&optional key)
14020 "Make sure point and context are visible.
14021 Optional argument KEY, when non-nil, is a symbol. See
14022 `org-show-context-detail' for allowed values and how much is to
14023 be shown."
14024 (org-show-set-visibility
14025 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14026 ((cdr (assq key org-show-context-detail)))
14027 (t (cdr (assq 'default org-show-context-detail))))))
14029 (defun org-show-set-visibility (detail)
14030 "Set visibility around point according to DETAIL.
14031 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14032 `tree', `canonical' or t. See `org-show-context-detail' for more
14033 information."
14034 ;; Show current heading and possibly its entry, following headline
14035 ;; or all children.
14036 (if (and (org-at-heading-p) (not (eq detail 'local)))
14037 (org-flag-heading nil)
14038 (org-show-entry)
14039 ;; If point is hidden within a drawer or a block, make sure to
14040 ;; expose it.
14041 (dolist (o (overlays-at (point)))
14042 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14043 (delete-overlay o)))
14044 (unless (org-before-first-heading-p)
14045 (org-with-limited-levels
14046 (cl-case detail
14047 ((tree canonical t) (org-show-children))
14048 ((nil minimal ancestors))
14049 (t (save-excursion
14050 (outline-next-heading)
14051 (org-flag-heading nil)))))))
14052 ;; Show all siblings.
14053 (when (eq detail 'lineage) (org-show-siblings))
14054 ;; Show ancestors, possibly with their children.
14055 (when (memq detail '(ancestors lineage tree canonical t))
14056 (save-excursion
14057 (while (org-up-heading-safe)
14058 (org-flag-heading nil)
14059 (when (memq detail '(canonical t)) (org-show-entry))
14060 (when (memq detail '(tree canonical t)) (org-show-children))))))
14062 (defvar org-reveal-start-hook nil
14063 "Hook run before revealing a location.")
14065 (defun org-reveal (&optional siblings)
14066 "Show current entry, hierarchy above it, and the following headline.
14068 This can be used to show a consistent set of context around
14069 locations exposed with `org-show-context'.
14071 With optional argument SIBLINGS, on each level of the hierarchy all
14072 siblings are shown. This repairs the tree structure to what it would
14073 look like when opened with hierarchical calls to `org-cycle'.
14075 With a \\[universal-argument] \\[universal-argument] prefix, \
14076 go to the parent and show the entire tree."
14077 (interactive "P")
14078 (run-hooks 'org-reveal-start-hook)
14079 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14080 ((equal siblings '(16))
14081 (save-excursion
14082 (when (org-up-heading-safe)
14083 (org-show-subtree)
14084 (run-hook-with-args 'org-cycle-hook 'subtree))))
14085 (t (org-show-set-visibility 'lineage))))
14087 (defun org-highlight-new-match (beg end)
14088 "Highlight from BEG to END and mark the highlight is an occur headline."
14089 (let ((ov (make-overlay beg end)))
14090 (overlay-put ov 'face 'secondary-selection)
14091 (overlay-put ov 'org-type 'org-occur)
14092 (push ov org-occur-highlights)))
14094 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14095 "Remove the occur highlights from the buffer.
14096 BEG and END are ignored. If NOREMOVE is nil, remove this function
14097 from the `before-change-functions' in the current buffer."
14098 (interactive)
14099 (unless org-inhibit-highlight-removal
14100 (mapc #'delete-overlay org-occur-highlights)
14101 (setq org-occur-highlights nil)
14102 (setq org-occur-parameters nil)
14103 (unless noremove
14104 (remove-hook 'before-change-functions
14105 'org-remove-occur-highlights 'local))))
14107 ;;;; Priorities
14109 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14110 "Regular expression matching the priority indicator.")
14112 (defvar org-remove-priority-next-time nil)
14114 (defun org-priority-up ()
14115 "Increase the priority of the current item."
14116 (interactive)
14117 (org-priority 'up))
14119 (defun org-priority-down ()
14120 "Decrease the priority of the current item."
14121 (interactive)
14122 (org-priority 'down))
14124 (defun org-priority (&optional action _show)
14125 "Change the priority of an item.
14126 ACTION can be `set', `up', `down', or a character."
14127 (interactive "P")
14128 (if (equal action '(4))
14129 (org-show-priority)
14130 (unless org-enable-priority-commands
14131 (user-error "Priority commands are disabled"))
14132 (setq action (or action 'set))
14133 (let (current new news have remove)
14134 (save-excursion
14135 (org-back-to-heading t)
14136 (when (looking-at org-priority-regexp)
14137 (setq current (string-to-char (match-string 2))
14138 have t))
14139 (cond
14140 ((eq action 'remove)
14141 (setq remove t new ?\ ))
14142 ((or (eq action 'set)
14143 (integerp action))
14144 (if (not (eq action 'set))
14145 (setq new action)
14146 (message "Priority %c-%c, SPC to remove: "
14147 org-highest-priority org-lowest-priority)
14148 (save-match-data
14149 (setq new (read-char-exclusive))))
14150 (when (and (= (upcase org-highest-priority) org-highest-priority)
14151 (= (upcase org-lowest-priority) org-lowest-priority))
14152 (setq new (upcase new)))
14153 (cond ((equal new ?\ ) (setq remove t))
14154 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14155 (user-error "Priority must be between `%c' and `%c'"
14156 org-highest-priority org-lowest-priority))))
14157 ((eq action 'up)
14158 (setq new (if have
14159 (1- current) ; normal cycling
14160 ;; last priority was empty
14161 (if (eq last-command this-command)
14162 org-lowest-priority ; wrap around empty to lowest
14163 ;; default
14164 (if org-priority-start-cycle-with-default
14165 org-default-priority
14166 (1- org-default-priority))))))
14167 ((eq action 'down)
14168 (setq new (if have
14169 (1+ current) ; normal cycling
14170 ;; last priority was empty
14171 (if (eq last-command this-command)
14172 org-highest-priority ; wrap around empty to highest
14173 ;; default
14174 (if org-priority-start-cycle-with-default
14175 org-default-priority
14176 (1+ org-default-priority))))))
14177 (t (user-error "Invalid action")))
14178 (when (or (< (upcase new) org-highest-priority)
14179 (> (upcase new) org-lowest-priority))
14180 (if (and (memq action '(up down))
14181 (not have) (not (eq last-command this-command)))
14182 ;; `new' is from default priority
14183 (error
14184 "The default can not be set, see `org-default-priority' why")
14185 ;; normal cycling: `new' is beyond highest/lowest priority
14186 ;; and is wrapped around to the empty priority
14187 (setq remove t)))
14188 (setq news (format "%c" new))
14189 (if have
14190 (if remove
14191 (replace-match "" t t nil 1)
14192 (replace-match news t t nil 2))
14193 (if remove
14194 (user-error "No priority cookie found in line")
14195 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14196 (if (match-end 2)
14197 (progn
14198 (goto-char (match-end 2))
14199 (insert " [#" news "]"))
14200 (goto-char (match-beginning 3))
14201 (insert "[#" news "] "))))
14202 (org-set-tags nil 'align))
14203 (if remove
14204 (message "Priority removed")
14205 (message "Priority of current item set to %s" news)))))
14207 (defun org-show-priority ()
14208 "Show the priority of the current item.
14209 This priority is composed of the main priority given with the [#A] cookies,
14210 and by additional input from the age of a schedules or deadline entry."
14211 (interactive)
14212 (let ((pri (if (eq major-mode 'org-agenda-mode)
14213 (org-get-at-bol 'priority)
14214 (save-excursion
14215 (save-match-data
14216 (beginning-of-line)
14217 (and (looking-at org-heading-regexp)
14218 (org-get-priority (match-string 0))))))))
14219 (message "Priority is %d" (if pri pri -1000))))
14221 (defun org-get-priority (s)
14222 "Find priority cookie and return priority."
14223 (save-match-data
14224 (if (functionp org-get-priority-function)
14225 (funcall org-get-priority-function)
14226 (if (not (string-match org-priority-regexp s))
14227 (* 1000 (- org-lowest-priority org-default-priority))
14228 (* 1000 (- org-lowest-priority
14229 (string-to-char (match-string 2 s))))))))
14231 ;;;; Tags
14233 (defvar org-agenda-archives-mode)
14234 (defvar org-map-continue-from nil
14235 "Position from where mapping should continue.
14236 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14238 (defvar org-scanner-tags nil
14239 "The current tag list while the tags scanner is running.")
14241 (defvar org-trust-scanner-tags nil
14242 "Should `org-get-tags-at' use the tags for the scanner.
14243 This is for internal dynamical scoping only.
14244 When this is non-nil, the function `org-get-tags-at' will return the value
14245 of `org-scanner-tags' instead of building the list by itself. This
14246 can lead to large speed-ups when the tags scanner is used in a file with
14247 many entries, and when the list of tags is retrieved, for example to
14248 obtain a list of properties. Building the tags list for each entry in such
14249 a file becomes an N^2 operation - but with this variable set, it scales
14250 as N.")
14252 (defvar org--matcher-tags-todo-only nil)
14254 (defun org-scan-tags (action matcher todo-only &optional start-level)
14255 "Scan headline tags with inheritance and produce output ACTION.
14257 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14258 or `agenda' to produce an entry list for an agenda view. It can also be
14259 a Lisp form or a function that should be called at each matched headline, in
14260 this case the return value is a list of all return values from these calls.
14262 MATCHER is a function accepting three arguments, returning
14263 a non-nil value whenever a given set of tags qualifies a headline
14264 for inclusion. See `org-make-tags-matcher' for more information.
14265 As a special case, it can also be set to t (respectively nil) in
14266 order to match all (respectively none) headline.
14268 When TODO-ONLY is non-nil, only lines with a not-done TODO
14269 keyword are included in the output.
14271 START-LEVEL can be a string with asterisks, reducing the scope to
14272 headlines matching this string."
14273 (require 'org-agenda)
14274 (let* ((re (concat "^"
14275 (if start-level
14276 ;; Get the correct level to match
14277 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14278 org-outline-regexp)
14279 " *\\(\\<\\("
14280 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14281 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14282 (props (list 'face 'default
14283 'done-face 'org-agenda-done
14284 'undone-face 'default
14285 'mouse-face 'highlight
14286 'org-not-done-regexp org-not-done-regexp
14287 'org-todo-regexp org-todo-regexp
14288 'org-complex-heading-regexp org-complex-heading-regexp
14289 'help-echo
14290 (format "mouse-2 or RET jump to org file %s"
14291 (abbreviate-file-name
14292 (or (buffer-file-name (buffer-base-buffer))
14293 (buffer-name (buffer-base-buffer)))))))
14294 (org-map-continue-from nil)
14295 lspos tags tags-list
14296 (tags-alist (list (cons 0 org-file-tags)))
14297 (llast 0) rtn rtn1 level category i txt
14298 todo marker entry priority
14299 ts-date ts-date-type ts-date-pair)
14300 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14301 (setq action (list 'lambda nil action)))
14302 (save-excursion
14303 (goto-char (point-min))
14304 (when (eq action 'sparse-tree)
14305 (org-overview)
14306 (org-remove-occur-highlights))
14307 (while (let (case-fold-search)
14308 (re-search-forward re nil t))
14309 (setq org-map-continue-from nil)
14310 (catch :skip
14311 (setq todo
14312 ;; TODO: is the 1-2 difference a bug?
14313 (when (match-end 1) (match-string-no-properties 2))
14314 tags (when (match-end 4) (match-string-no-properties 4)))
14315 (goto-char (setq lspos (match-beginning 0)))
14316 (setq level (org-reduced-level (org-outline-level))
14317 category (org-get-category))
14318 (when (eq action 'agenda)
14319 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14320 ts-date (car ts-date-pair)
14321 ts-date-type (cdr ts-date-pair)))
14322 (setq i llast llast level)
14323 ;; remove tag lists from same and sublevels
14324 (while (>= i level)
14325 (when (setq entry (assoc i tags-alist))
14326 (setq tags-alist (delete entry tags-alist)))
14327 (setq i (1- i)))
14328 ;; add the next tags
14329 (when tags
14330 (setq tags (org-split-string tags ":")
14331 tags-alist
14332 (cons (cons level tags) tags-alist)))
14333 ;; compile tags for current headline
14334 (setq tags-list
14335 (if org-use-tag-inheritance
14336 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14337 tags)
14338 org-scanner-tags tags-list)
14339 (when org-use-tag-inheritance
14340 (setcdr (car tags-alist)
14341 (mapcar (lambda (x)
14342 (setq x (copy-sequence x))
14343 (org-add-prop-inherited x))
14344 (cdar tags-alist))))
14345 (when (and tags org-use-tag-inheritance
14346 (or (not (eq t org-use-tag-inheritance))
14347 org-tags-exclude-from-inheritance))
14348 ;; Selective inheritance, remove uninherited ones.
14349 (setcdr (car tags-alist)
14350 (org-remove-uninherited-tags (cdar tags-alist))))
14351 (when (and
14353 ;; eval matcher only when the todo condition is OK
14354 (and (or (not todo-only) (member todo org-not-done-keywords))
14355 (if (functionp matcher)
14356 (let ((case-fold-search t) (org-trust-scanner-tags t))
14357 (funcall matcher todo tags-list level))
14358 matcher))
14360 ;; Call the skipper, but return t if it does not
14361 ;; skip, so that the `and' form continues evaluating.
14362 (progn
14363 (unless (eq action 'sparse-tree) (org-agenda-skip))
14366 ;; Check if timestamps are deselecting this entry
14367 (or (not todo-only)
14368 (and (member todo org-not-done-keywords)
14369 (or (not org-agenda-tags-todo-honor-ignore-options)
14370 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14372 ;; select this headline
14373 (cond
14374 ((eq action 'sparse-tree)
14375 (and org-highlight-sparse-tree-matches
14376 (org-get-heading) (match-end 0)
14377 (org-highlight-new-match
14378 (match-beginning 1) (match-end 1)))
14379 (org-show-context 'tags-tree))
14380 ((eq action 'agenda)
14381 (setq txt (org-agenda-format-item
14383 (concat
14384 (if (eq org-tags-match-list-sublevels 'indented)
14385 (make-string (1- level) ?.) "")
14386 (org-get-heading))
14387 (make-string level ?\s)
14388 category
14389 tags-list)
14390 priority (org-get-priority txt))
14391 (goto-char lspos)
14392 (setq marker (org-agenda-new-marker))
14393 (org-add-props txt props
14394 'org-marker marker 'org-hd-marker marker 'org-category category
14395 'todo-state todo
14396 'ts-date ts-date
14397 'priority priority
14398 'type (concat "tagsmatch" ts-date-type))
14399 (push txt rtn))
14400 ((functionp action)
14401 (setq org-map-continue-from nil)
14402 (save-excursion
14403 (setq rtn1 (funcall action))
14404 (push rtn1 rtn)))
14405 (t (user-error "Invalid action")))
14407 ;; if we are to skip sublevels, jump to end of subtree
14408 (unless org-tags-match-list-sublevels
14409 (org-end-of-subtree t)
14410 (backward-char 1))))
14411 ;; Get the correct position from where to continue
14412 (if org-map-continue-from
14413 (goto-char org-map-continue-from)
14414 (and (= (point) lspos) (end-of-line 1)))))
14415 (when (and (eq action 'sparse-tree)
14416 (not org-sparse-tree-open-archived-trees))
14417 (org-hide-archived-subtrees (point-min) (point-max)))
14418 (nreverse rtn)))
14420 (defun org-remove-uninherited-tags (tags)
14421 "Remove all tags that are not inherited from the list TAGS."
14422 (cond
14423 ((eq org-use-tag-inheritance t)
14424 (if org-tags-exclude-from-inheritance
14425 (org-delete-all org-tags-exclude-from-inheritance tags)
14426 tags))
14427 ((not org-use-tag-inheritance) nil)
14428 ((stringp org-use-tag-inheritance)
14429 (delq nil (mapcar
14430 (lambda (x)
14431 (if (and (string-match org-use-tag-inheritance x)
14432 (not (member x org-tags-exclude-from-inheritance)))
14433 x nil))
14434 tags)))
14435 ((listp org-use-tag-inheritance)
14436 (delq nil (mapcar
14437 (lambda (x)
14438 (if (member x org-use-tag-inheritance) x nil))
14439 tags)))))
14441 (defun org-match-sparse-tree (&optional todo-only match)
14442 "Create a sparse tree according to tags string MATCH.
14444 MATCH is a string with match syntax. It can contain a selection
14445 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14446 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14447 those. See the manual for details.
14449 If optional argument TODO-ONLY is non-nil, only select lines that
14450 are also TODO tasks."
14451 (interactive "P")
14452 (org-agenda-prepare-buffers (list (current-buffer)))
14453 (let ((org--matcher-tags-todo-only todo-only))
14454 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14455 org--matcher-tags-todo-only)))
14457 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14459 (defvar org-cached-props nil)
14460 (defun org-cached-entry-get (pom property)
14461 (if (or (eq t org-use-property-inheritance)
14462 (and (stringp org-use-property-inheritance)
14463 (let ((case-fold-search t))
14464 (string-match-p org-use-property-inheritance property)))
14465 (and (listp org-use-property-inheritance)
14466 (member-ignore-case property org-use-property-inheritance)))
14467 ;; Caching is not possible, check it directly.
14468 (org-entry-get pom property 'inherit)
14469 ;; Get all properties, so we can do complicated checks easily.
14470 (cdr (assoc-string property
14471 (or org-cached-props
14472 (setq org-cached-props (org-entry-properties pom)))
14473 t))))
14475 (defun org-global-tags-completion-table (&optional files)
14476 "Return the list of all tags in all agenda buffer/files.
14477 Optional FILES argument is a list of files which can be used
14478 instead of the agenda files."
14479 (save-excursion
14480 (org-uniquify
14481 (delq nil
14482 (apply #'append
14483 (mapcar
14484 (lambda (file)
14485 (set-buffer (find-file-noselect file))
14486 (mapcar (lambda (x)
14487 (and (stringp (car-safe x))
14488 (list (car-safe x))))
14489 (or org-current-tag-alist (org-get-buffer-tags))))
14490 (if (car-safe files) files
14491 (org-agenda-files))))))))
14493 (defun org-make-tags-matcher (match)
14494 "Create the TAGS/TODO matcher form for the selection string MATCH.
14496 Returns a cons of the selection string MATCH and a function
14497 implementing the matcher.
14499 The matcher is to be called at an Org entry, with point on the
14500 headline, and returns non-nil if the entry matches the selection
14501 string MATCH. It must be called with three arguments: the TODO
14502 keyword at the entry (or nil if none), the list of all tags at
14503 the entry including inherited ones and the reduced level of the
14504 headline. Additionally, the category of the entry, if any, must
14505 be specified as the text property `org-category' on the headline.
14507 This function sets the variable `org--matcher-tags-todo-only' to
14508 a non-nil value if the matcher restricts matching to TODO
14509 entries, otherwise it is not touched.
14511 See also `org-scan-tags'."
14512 (unless match
14513 ;; Get a new match request, with completion against the global
14514 ;; tags table and the local tags in current buffer.
14515 (let ((org-last-tags-completion-table
14516 (org-uniquify
14517 (delq nil (append (org-get-buffer-tags)
14518 (org-global-tags-completion-table))))))
14519 (setq match
14520 (completing-read
14521 "Match: "
14522 'org-tags-completion-function nil nil nil 'org-tags-history))))
14524 (let ((match0 match)
14525 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14526 (start 0)
14527 tagsmatch todomatch tagsmatcher todomatcher)
14529 ;; Expand group tags.
14530 (setq match (org-tags-expand match))
14532 ;; Check if there is a TODO part of this match, which would be the
14533 ;; part after a "/". To make sure that this slash is not part of
14534 ;; a property value to be matched against, we also check that
14535 ;; there is no / after that slash. First, find the last slash.
14536 (let ((s 0))
14537 (while (string-match "/+" match s)
14538 (setq start (match-beginning 0))
14539 (setq s (match-end 0))))
14540 (if (and (string-match "/+" match start)
14541 (not (string-match-p "\"" match start)))
14542 ;; Match contains also a TODO-matching request.
14543 (progn
14544 (setq tagsmatch (substring match 0 (match-beginning 0)))
14545 (setq todomatch (substring match (match-end 0)))
14546 (when (string-prefix-p "!" todomatch)
14547 (setq org--matcher-tags-todo-only t)
14548 (setq todomatch (substring todomatch 1)))
14549 (when (string-match "\\`\\s-*\\'" todomatch)
14550 (setq todomatch nil)))
14551 ;; Only matching tags.
14552 (setq tagsmatch match)
14553 (setq todomatch nil))
14555 ;; Make the tags matcher.
14556 (when (org-string-nw-p tagsmatch)
14557 (let ((orlist nil)
14558 (orterms (org-split-string tagsmatch "|"))
14559 term)
14560 (while (setq term (pop orterms))
14561 (while (and (equal (substring term -1) "\\") orterms)
14562 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14563 (while (string-match re term)
14564 (let* ((rest (substring term (match-end 0)))
14565 (minus (and (match-end 1)
14566 (equal (match-string 1 term) "-")))
14567 (tag (save-match-data
14568 (replace-regexp-in-string
14569 "\\\\-" "-" (match-string 2 term))))
14570 (regexp (eq (string-to-char tag) ?{))
14571 (levelp (match-end 4))
14572 (propp (match-end 5))
14574 (cond
14575 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14576 (levelp
14577 `(,(org-op-to-function (match-string 3 term))
14578 level
14579 ,(string-to-number (match-string 4 term))))
14580 (propp
14581 (let* ((gv (pcase (upcase (match-string 5 term))
14582 ("CATEGORY"
14583 '(get-text-property (point) 'org-category))
14584 ("TODO" 'todo)
14585 (p `(org-cached-entry-get nil ,p))))
14586 (pv (match-string 7 term))
14587 (regexp (eq (string-to-char pv) ?{))
14588 (strp (eq (string-to-char pv) ?\"))
14589 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14590 (po (org-op-to-function (match-string 6 term)
14591 (if timep 'time strp))))
14592 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14593 (when timep (setq pv (org-matcher-time pv)))
14594 (cond ((and regexp (eq po 'org<>))
14595 `(not (string-match ,pv (or ,gv ""))))
14596 (regexp `(string-match ,pv (or ,gv "")))
14597 (strp `(,po (or ,gv "") ,pv))
14599 `(,po
14600 (string-to-number (or ,gv ""))
14601 ,(string-to-number pv))))))
14602 (t `(member ,tag tags-list)))))
14603 (push (if minus `(not ,mm) mm) tagsmatcher)
14604 (setq term rest)))
14605 (push `(and ,@tagsmatcher) orlist)
14606 (setq tagsmatcher nil))
14607 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14609 ;; Make the TODO matcher.
14610 (when (org-string-nw-p todomatch)
14611 (let ((orlist nil))
14612 (dolist (term (org-split-string todomatch "|"))
14613 (while (string-match re term)
14614 (let* ((minus (and (match-end 1)
14615 (equal (match-string 1 term) "-")))
14616 (kwd (match-string 2 term))
14617 (regexp (eq (string-to-char kwd) ?{))
14618 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14619 `(equal todo ,kwd))))
14620 (push (if minus `(not ,mm) mm) todomatcher))
14621 (setq term (substring term (match-end 0))))
14622 (push (if (> (length todomatcher) 1)
14623 (cons 'and todomatcher)
14624 (car todomatcher))
14625 orlist)
14626 (setq todomatcher nil))
14627 (setq todomatcher (cons 'or orlist))))
14629 ;; Return the string and function of the matcher. If no
14630 ;; tags-specific or todo-specific matcher exists, match
14631 ;; everything.
14632 (let ((matcher (if (and tagsmatcher todomatcher)
14633 `(and ,tagsmatcher ,todomatcher)
14634 (or tagsmatcher todomatcher t))))
14635 (when org--matcher-tags-todo-only
14636 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14637 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14639 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14640 "Expand group tags in MATCH.
14642 This replaces every group tag in MATCH with a regexp tag search.
14643 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14644 will be replaced like this:
14646 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14647 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14648 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14650 Replacing by a regexp preserves the structure of the match.
14651 E.g., this expansion
14653 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14655 will match anything tagged with \"Lab\" and \"Home\", or tagged
14656 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14658 A group tag in MATCH can contain regular expressions of its own.
14659 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14660 will be replaced like this:
14662 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14664 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14665 assumed to be a single group tag, and the function will return
14666 the list of tags in this group.
14668 When DOWNCASE is non-nil, expand downcased TAGS."
14669 (if org-group-tags
14670 (let* ((case-fold-search t)
14671 (stable org-mode-syntax-table)
14672 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14673 (taggroups (if downcased
14674 (mapcar (lambda (tg) (mapcar #'downcase tg))
14675 taggroups)
14676 taggroups))
14677 (taggroups-keys (mapcar #'car taggroups))
14678 (return-match (if downcased (downcase match) match))
14679 (count 0)
14680 (work-already-expanded tags-already-expanded)
14681 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14682 ;; @ and _ are allowed as word-components in tags.
14683 (modify-syntax-entry ?@ "w" stable)
14684 (modify-syntax-entry ?_ "w" stable)
14685 ;; Temporarily replace regexp-expressions in the match-expression.
14686 (while (string-match "{.+?}" return-match)
14687 (cl-incf count)
14688 (push (match-string 0 return-match) regexps-in-match)
14689 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14690 (while (and taggroups-keys
14691 (with-syntax-table stable
14692 (string-match
14693 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14694 (regexp-opt taggroups-keys) "\\>\\)")
14695 return-match)))
14696 (let* ((dir (match-string 1 return-match))
14697 (tag (match-string 2 return-match))
14698 (tag (if downcased (downcase tag) tag)))
14699 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14700 (member tag work-already-expanded))
14701 (setq tags-in-group (assoc tag taggroups))
14702 (push tag work-already-expanded)
14703 ;; Recursively expand each tag in the group, if the tag hasn't
14704 ;; already been expanded. Restore the match-data after all recursive calls.
14705 (save-match-data
14706 (let (tags-expanded)
14707 (dolist (x (cdr tags-in-group))
14708 (if (and (member x taggroups-keys)
14709 (not (member x work-already-expanded)))
14710 (setq tags-expanded
14711 (delete-dups
14712 (append
14713 (org-tags-expand x t downcased
14714 work-already-expanded)
14715 tags-expanded)))
14716 (setq tags-expanded
14717 (append (list x) tags-expanded)))
14718 (setq work-already-expanded
14719 (delete-dups
14720 (append tags-expanded
14721 work-already-expanded))))
14722 (setq tags-in-group
14723 (delete-dups (cons (car tags-in-group)
14724 tags-expanded)))))
14725 ;; Filter tag-regexps from tags.
14726 (setq regexp-in-group-escaped
14727 (delq nil (mapcar (lambda (x)
14728 (if (stringp x)
14729 (and (equal "{" (substring x 0 1))
14730 (equal "}" (substring x -1))
14733 tags-in-group))
14734 regexp-in-group
14735 (mapcar (lambda (x)
14736 (substring x 1 -1))
14737 regexp-in-group-escaped)
14738 tags-in-group
14739 (delq nil (mapcar (lambda (x)
14740 (if (stringp x)
14741 (and (not (equal "{" (substring x 0 1)))
14742 (not (equal "}" (substring x -1)))
14745 tags-in-group)))
14746 ;; If single-as-list, do no more in the while-loop.
14747 (if (not single-as-list)
14748 (progn
14749 (when regexp-in-group
14750 (setq regexp-in-group
14751 (concat "\\|"
14752 (mapconcat 'identity regexp-in-group
14753 "\\|"))))
14754 (setq tags-in-group
14755 (concat dir
14756 "{\\<"
14757 (regexp-opt tags-in-group)
14758 "\\>"
14759 regexp-in-group
14760 "}"))
14761 (when (stringp tags-in-group)
14762 (org-add-props tags-in-group '(grouptag t)))
14763 (setq return-match
14764 (replace-match tags-in-group t t return-match)))
14765 (setq tags-in-group
14766 (append regexp-in-group-escaped tags-in-group))))
14767 (setq taggroups-keys (delete tag taggroups-keys))))
14768 ;; Add the regular expressions back into the match-expression again.
14769 (while regexps-in-match
14770 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14771 (pop regexps-in-match)
14772 return-match t t))
14773 (cl-decf count))
14774 (if single-as-list
14775 (if tags-in-group tags-in-group (list return-match))
14776 return-match))
14777 (if single-as-list
14778 (list (if downcased (downcase match) match))
14779 match)))
14781 (defun org-op-to-function (op &optional stringp)
14782 "Turn an operator into the appropriate function."
14783 (setq op
14784 (cond
14785 ((equal op "<" ) '(< string< org-time<))
14786 ((equal op ">" ) '(> org-string> org-time>))
14787 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14788 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14789 ((member op '("=" "==")) '(= string= org-time=))
14790 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14791 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14793 (defun org<> (a b) (not (= a b)))
14794 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14795 (defun org-string>= (a b) (not (string< a b)))
14796 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14797 (defun org-string<> (a b) (not (string= a b)))
14798 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14799 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14800 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14801 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14802 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14803 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14804 (defun org-2ft (s)
14805 "Convert S to a floating point time.
14806 If S is already a number, just return it. If it is a string, parse
14807 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14808 (cond
14809 ((numberp s) s)
14810 ((stringp s)
14811 (condition-case nil
14812 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14813 (error 0.)))
14814 (t 0.)))
14816 (defun org-time-today ()
14817 "Time in seconds today at 0:00.
14818 Returns the float number of seconds since the beginning of the
14819 epoch to the beginning of today (00:00)."
14820 (float-time (apply 'encode-time
14821 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14823 (defun org-matcher-time (s)
14824 "Interpret a time comparison value."
14825 (save-match-data
14826 (cond
14827 ((string= s "<now>") (float-time))
14828 ((string= s "<today>") (org-time-today))
14829 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14830 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14831 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14832 (+ (org-time-today)
14833 (* (string-to-number (match-string 1 s))
14834 (cdr (assoc (match-string 2 s)
14835 '(("d" . 86400.0) ("w" . 604800.0)
14836 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14837 (t (org-2ft s)))))
14839 (defun org-match-any-p (re list)
14840 "Does re match any element of list?"
14841 (setq list (mapcar (lambda (x) (string-match re x)) list))
14842 (delq nil list))
14844 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14845 (defvar org-tags-overlay (make-overlay 1 1))
14846 (delete-overlay org-tags-overlay)
14848 (defun org-get-local-tags-at (&optional pos)
14849 "Get a list of tags defined in the current headline."
14850 (org-get-tags-at pos 'local))
14852 (defun org-get-local-tags ()
14853 "Get a list of tags defined in the current headline."
14854 (org-get-tags-at nil 'local))
14856 (defun org-get-tags-at (&optional pos local)
14857 "Get a list of all headline tags applicable at POS.
14858 POS defaults to point. If tags are inherited, the list contains
14859 the targets in the same sequence as the headlines appear, i.e.
14860 the tags of the current headline come last.
14861 When LOCAL is non-nil, only return tags from the current headline,
14862 ignore inherited ones."
14863 (interactive)
14864 (if (and org-trust-scanner-tags
14865 (or (not pos) (equal pos (point)))
14866 (not local))
14867 org-scanner-tags
14868 (let (tags ltags lastpos parent)
14869 (save-excursion
14870 (save-restriction
14871 (widen)
14872 (goto-char (or pos (point)))
14873 (save-match-data
14874 (catch 'done
14875 (condition-case nil
14876 (progn
14877 (org-back-to-heading t)
14878 (while (not (equal lastpos (point)))
14879 (setq lastpos (point))
14880 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14881 (setq ltags (org-split-string
14882 (match-string-no-properties 1) ":"))
14883 (when parent
14884 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14885 (setq tags (append
14886 (if parent
14887 (org-remove-uninherited-tags ltags)
14888 ltags)
14889 tags)))
14890 (or org-use-tag-inheritance (throw 'done t))
14891 (when local (throw 'done t))
14892 (or (org-up-heading-safe) (error nil))
14893 (setq parent t)))
14894 (error nil)))))
14895 (if local
14896 tags
14897 (reverse (delete-dups
14898 (reverse (append
14899 (org-remove-uninherited-tags
14900 org-file-tags)
14901 tags)))))))))
14903 (defun org-add-prop-inherited (s)
14904 (add-text-properties 0 (length s) '(inherited t) s)
14907 (defun org-toggle-tag (tag &optional onoff)
14908 "Toggle the tag TAG for the current line.
14909 If ONOFF is `on' or `off', don't toggle but set to this state."
14910 (let (res current)
14911 (save-excursion
14912 (org-back-to-heading t)
14913 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14914 (point-at-eol) t)
14915 (progn
14916 (setq current (match-string 1))
14917 (replace-match ""))
14918 (setq current ""))
14919 (setq current (nreverse (org-split-string current ":")))
14920 (cond
14921 ((eq onoff 'on)
14922 (setq res t)
14923 (or (member tag current) (push tag current)))
14924 ((eq onoff 'off)
14925 (or (not (member tag current)) (setq current (delete tag current))))
14926 (t (if (member tag current)
14927 (setq current (delete tag current))
14928 (setq res t)
14929 (push tag current))))
14930 (end-of-line 1)
14931 (if current
14932 (progn
14933 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14934 (org-set-tags nil t))
14935 (delete-horizontal-space))
14936 (run-hooks 'org-after-tags-change-hook))
14937 res))
14939 (defun org--align-tags-here (to-col)
14940 "Align tags on the current headline to TO-COL.
14941 Assume point is on a headline."
14942 (let ((pos (point)))
14943 (beginning-of-line)
14944 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14945 (>= pos (match-beginning 2)))
14946 ;; No tags or point within tags: do not align.
14947 (goto-char pos)
14948 (goto-char (match-beginning 1))
14949 (let ((shift (max (- (if (>= to-col 0) to-col
14950 (- (abs to-col) (string-width (match-string 2))))
14951 (current-column))
14952 1)))
14953 (replace-match (make-string shift ?\s) nil nil nil 1)
14954 ;; Preserve initial position, if possible. In any case, stop
14955 ;; before tags.
14956 (when (< pos (point)) (goto-char pos))))))
14958 (defun org-set-tags-command (&optional arg just-align)
14959 "Call the set-tags command for the current entry."
14960 (interactive "P")
14961 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14962 (org-set-tags arg just-align)
14963 (save-excursion
14964 (unless (and (org-region-active-p)
14965 org-loop-over-headlines-in-active-region)
14966 (org-back-to-heading t))
14967 (org-set-tags arg just-align))))
14969 (defun org-set-tags-to (data)
14970 "Set the tags of the current entry to DATA, replacing the current tags.
14971 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14972 If DATA is nil or the empty string, any tags will be removed."
14973 (interactive "sTags: ")
14974 (setq data
14975 (cond
14976 ((eq data nil) "")
14977 ((equal data "") "")
14978 ((stringp data)
14979 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14980 ":"))
14981 ((listp data)
14982 (concat ":" (mapconcat 'identity data ":") ":"))))
14983 (when data
14984 (save-excursion
14985 (org-back-to-heading t)
14986 (when (let ((case-fold-search nil))
14987 (looking-at org-complex-heading-regexp))
14988 (if (match-end 5)
14989 (progn
14990 (goto-char (match-beginning 5))
14991 (insert data)
14992 (delete-region (point) (point-at-eol))
14993 (org-set-tags nil 'align))
14994 (goto-char (point-at-eol))
14995 (insert " " data)
14996 (org-set-tags nil 'align)))
14997 (beginning-of-line 1)
14998 (when (looking-at ".*?\\([ \t]+\\)$")
14999 (delete-region (match-beginning 1) (match-end 1))))))
15001 (defun org-align-all-tags ()
15002 "Align the tags in all headings."
15003 (interactive)
15004 (save-excursion
15005 (or (ignore-errors (org-back-to-heading t))
15006 (outline-next-heading))
15007 (if (org-at-heading-p)
15008 (org-set-tags t)
15009 (message "No headings"))))
15011 (defvar org-indent-indentation-per-level)
15012 (defun org-set-tags (&optional arg just-align)
15013 "Set the tags for the current headline.
15014 With prefix ARG, realign all tags in headings in the current buffer.
15015 When JUST-ALIGN is non-nil, only align tags."
15016 (interactive "P")
15017 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15018 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15019 'region-start-level
15020 'region))
15021 org-loop-over-headlines-in-active-region)
15022 (org-map-entries
15023 ;; We don't use ARG and JUST-ALIGN here because these args
15024 ;; are not useful when looping over headlines.
15025 #'org-set-tags
15026 org-loop-over-headlines-in-active-region
15028 '(when (org-invisible-p) (org-end-of-subtree nil t))))
15029 (let ((org-setting-tags t))
15030 (if arg
15031 (save-excursion
15032 (goto-char (point-min))
15033 (while (re-search-forward org-outline-regexp-bol nil t)
15034 (org-set-tags nil t)
15035 (end-of-line))
15036 (message "All tags realigned to column %d" org-tags-column))
15037 (let* ((current (org-get-tags-string))
15038 (tags
15039 (if just-align current
15040 ;; Get a new set of tags from the user.
15041 (save-excursion
15042 (let* ((seen)
15043 (table
15044 (setq
15045 org-last-tags-completion-table
15046 ;; Uniquify tags in alists, yet preserve
15047 ;; structure (i.e., keywords).
15048 (delq nil
15049 (mapcar
15050 (lambda (pair)
15051 (let ((head (car pair)))
15052 (cond ((symbolp head) pair)
15053 ((member head seen) nil)
15054 (t (push head seen)
15055 pair))))
15056 (append
15057 (or org-current-tag-alist
15058 (org-get-buffer-tags))
15059 (and
15060 org-complete-tags-always-offer-all-agenda-tags
15061 (org-global-tags-completion-table
15062 (org-agenda-files))))))))
15063 (current-tags (org-split-string current ":"))
15064 (inherited-tags
15065 (nreverse (nthcdr (length current-tags)
15066 (nreverse (org-get-tags-at))))))
15067 (replace-regexp-in-string
15068 "\\([-+&]+\\|,\\)"
15070 (if (or (eq t org-use-fast-tag-selection)
15071 (and org-use-fast-tag-selection
15072 (delq nil (mapcar #'cdr table))))
15073 (org-fast-tag-selection
15074 current-tags inherited-tags table
15075 (and org-fast-tag-selection-include-todo
15076 org-todo-key-alist))
15077 (let ((org-add-colon-after-tag-completion
15078 (< 1 (length table))))
15079 (org-trim
15080 (completing-read
15081 "Tags: "
15082 #'org-tags-completion-function
15083 nil nil current 'org-tags-history))))))))))
15085 (when org-tags-sort-function
15086 (setq tags
15087 (mapconcat
15088 #'identity
15089 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15090 org-tags-sort-function)
15091 ":")))
15093 (if (or (string= ":" tags)
15094 (string= "::" tags))
15095 (setq tags ""))
15096 (if (not (org-string-nw-p tags)) (setq tags "")
15097 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15098 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15100 ;; Insert new tags at the correct column.
15101 (unless (equal current tags)
15102 (save-excursion
15103 (beginning-of-line)
15104 (let ((case-fold-search nil))
15105 (looking-at org-complex-heading-regexp))
15106 ;; Remove current tags, if any.
15107 (when (match-end 5) (replace-match "" nil nil nil 5))
15108 ;; Insert new tags, if any. Otherwise, remove trailing
15109 ;; white spaces.
15110 (end-of-line)
15111 (if (not (equal tags ""))
15112 ;; When text is being inserted on an invisible
15113 ;; region boundary, it can be inadvertently sucked
15114 ;; into invisibility.
15115 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15116 (skip-chars-backward " \t")
15117 (delete-region (point) (line-end-position)))))
15118 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15119 ;; is on.
15120 (unless (equal tags "")
15121 (let* ((level (save-excursion
15122 (beginning-of-line)
15123 (skip-chars-forward "\\*")))
15124 (offset (if (bound-and-true-p org-indent-mode)
15125 (* (1- org-indent-indentation-per-level)
15126 (1- level))
15128 (tags-column
15129 (+ org-tags-column
15130 (if (> org-tags-column 0) (- offset) offset))))
15131 (org--align-tags-here tags-column))))
15132 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15134 (defun org-change-tag-in-region (beg end tag off)
15135 "Add or remove TAG for each entry in the region.
15136 This works in the agenda, and also in an Org buffer."
15137 (interactive
15138 (list (region-beginning) (region-end)
15139 (let ((org-last-tags-completion-table
15140 (if (derived-mode-p 'org-mode)
15141 (org-uniquify
15142 (delq nil (append (org-get-buffer-tags)
15143 (org-global-tags-completion-table))))
15144 (org-global-tags-completion-table))))
15145 (completing-read
15146 "Tag: " 'org-tags-completion-function nil nil nil
15147 'org-tags-history))
15148 (progn
15149 (message "[s]et or [r]emove? ")
15150 (equal (read-char-exclusive) ?r))))
15151 (when (fboundp 'deactivate-mark) (deactivate-mark))
15152 (let ((agendap (equal major-mode 'org-agenda-mode))
15153 l1 l2 m buf pos newhead (cnt 0))
15154 (goto-char end)
15155 (setq l2 (1- (org-current-line)))
15156 (goto-char beg)
15157 (setq l1 (org-current-line))
15158 (cl-loop for l from l1 to l2 do
15159 (org-goto-line l)
15160 (setq m (get-text-property (point) 'org-hd-marker))
15161 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15162 (and agendap m))
15163 (setq buf (if agendap (marker-buffer m) (current-buffer))
15164 pos (if agendap m (point)))
15165 (with-current-buffer buf
15166 (save-excursion
15167 (save-restriction
15168 (goto-char pos)
15169 (setq cnt (1+ cnt))
15170 (org-toggle-tag tag (if off 'off 'on))
15171 (setq newhead (org-get-heading)))))
15172 (and agendap (org-agenda-change-all-lines newhead m))))
15173 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15175 (defun org-tags-completion-function (string _predicate &optional flag)
15176 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15177 (confirm (lambda (x) (stringp (car x)))))
15178 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15179 (setq s1 (match-string 1 string)
15180 s2 (match-string 2 string))
15181 (setq s1 "" s2 string))
15182 (cond
15183 ((eq flag nil)
15184 ;; try completion
15185 (setq rtn (try-completion s2 ctable confirm))
15186 (when (stringp rtn)
15187 (setq rtn
15188 (concat s1 s2 (substring rtn (length s2))
15189 (if (and org-add-colon-after-tag-completion
15190 (assoc rtn ctable))
15191 ":" ""))))
15192 rtn)
15193 ((eq flag t)
15194 ;; all-completions
15195 (all-completions s2 ctable confirm))
15196 ((eq flag 'lambda)
15197 ;; exact match?
15198 (assoc s2 ctable)))))
15200 (defun org-fast-tag-insert (kwd tags face &optional end)
15201 "Insert KDW, and the TAGS, the latter with face FACE.
15202 Also insert END."
15203 (insert (format "%-12s" (concat kwd ":"))
15204 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15205 (or end "")))
15207 (defun org-fast-tag-show-exit (flag)
15208 (save-excursion
15209 (org-goto-line 3)
15210 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15211 (replace-match ""))
15212 (when flag
15213 (end-of-line 1)
15214 (org-move-to-column (- (window-width) 19) t)
15215 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15217 (defun org-set-current-tags-overlay (current prefix)
15218 "Add an overlay to CURRENT tag with PREFIX."
15219 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15220 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15221 (org-overlay-display org-tags-overlay (concat prefix s))))
15223 (defvar org-last-tag-selection-key nil)
15224 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15225 "Fast tag selection with single keys.
15226 CURRENT is the current list of tags in the headline, INHERITED is the
15227 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15228 possibly with grouping information. TODO-TABLE is a similar table with
15229 TODO keywords, should these have keys assigned to them.
15230 If the keys are nil, a-z are automatically assigned.
15231 Returns the new tags string, or nil to not change the current settings."
15232 (let* ((fulltable (append table todo-table))
15233 (maxlen (apply 'max (mapcar
15234 (lambda (x)
15235 (if (stringp (car x)) (string-width (car x)) 0))
15236 fulltable)))
15237 (buf (current-buffer))
15238 (expert (eq org-fast-tag-selection-single-key 'expert))
15239 (buffer-tags nil)
15240 (fwidth (+ maxlen 3 1 3))
15241 (ncol (/ (- (window-width) 4) fwidth))
15242 (i-face 'org-done)
15243 (c-face 'org-todo)
15244 tg cnt e c char c1 c2 ntable tbl rtn
15245 ov-start ov-end ov-prefix
15246 (exit-after-next org-fast-tag-selection-single-key)
15247 (done-keywords org-done-keywords)
15248 groups ingroup intaggroup)
15249 (save-excursion
15250 (beginning-of-line 1)
15251 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15252 (setq ov-start (match-beginning 1)
15253 ov-end (match-end 1)
15254 ov-prefix "")
15255 (setq ov-start (1- (point-at-eol))
15256 ov-end (1+ ov-start))
15257 (skip-chars-forward "^\n\r")
15258 (setq ov-prefix
15259 (concat
15260 (buffer-substring (1- (point)) (point))
15261 (if (> (current-column) org-tags-column)
15263 (make-string (- org-tags-column (current-column)) ?\ ))))))
15264 (move-overlay org-tags-overlay ov-start ov-end)
15265 (save-window-excursion
15266 (if expert
15267 (set-buffer (get-buffer-create " *Org tags*"))
15268 (delete-other-windows)
15269 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15270 (org-switch-to-buffer-other-window " *Org tags*"))
15271 (erase-buffer)
15272 (setq-local org-done-keywords done-keywords)
15273 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15274 (org-fast-tag-insert "Current" current c-face "\n\n")
15275 (org-fast-tag-show-exit exit-after-next)
15276 (org-set-current-tags-overlay current ov-prefix)
15277 (setq tbl fulltable char ?a cnt 0)
15278 (while (setq e (pop tbl))
15279 (cond
15280 ((eq (car e) :startgroup)
15281 (push '() groups) (setq ingroup t)
15282 (unless (zerop cnt)
15283 (setq cnt 0)
15284 (insert "\n"))
15285 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15286 ((eq (car e) :endgroup)
15287 (setq ingroup nil cnt 0)
15288 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15289 ((eq (car e) :startgrouptag)
15290 (setq intaggroup t)
15291 (unless (zerop cnt)
15292 (setq cnt 0)
15293 (insert "\n"))
15294 (insert "[ "))
15295 ((eq (car e) :endgrouptag)
15296 (setq intaggroup nil cnt 0)
15297 (insert "]\n"))
15298 ((equal e '(:newline))
15299 (unless (zerop cnt)
15300 (setq cnt 0)
15301 (insert "\n")
15302 (setq e (car tbl))
15303 (while (equal (car tbl) '(:newline))
15304 (insert "\n")
15305 (setq tbl (cdr tbl)))))
15306 ((equal e '(:grouptags)) (insert " : "))
15308 (setq tg (copy-sequence (car e)) c2 nil)
15309 (if (cdr e)
15310 (setq c (cdr e))
15311 ;; automatically assign a character.
15312 (setq c1 (string-to-char
15313 (downcase (substring
15314 tg (if (= (string-to-char tg) ?@) 1 0)))))
15315 (if (or (rassoc c1 ntable) (rassoc c1 table))
15316 (while (or (rassoc char ntable) (rassoc char table))
15317 (setq char (1+ char)))
15318 (setq c2 c1))
15319 (setq c (or c2 char)))
15320 (when ingroup (push tg (car groups)))
15321 (setq tg (org-add-props tg nil 'face
15322 (cond
15323 ((not (assoc tg table))
15324 (org-get-todo-face tg))
15325 ((member tg current) c-face)
15326 ((member tg inherited) i-face))))
15327 (when (equal (caar tbl) :grouptags)
15328 (org-add-props tg nil 'face 'org-tag-group))
15329 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15330 (insert "[" c "] " tg (make-string
15331 (- fwidth 4 (length tg)) ?\ ))
15332 (push (cons tg c) ntable)
15333 (when (= (cl-incf cnt) ncol)
15334 (insert "\n")
15335 (when (or ingroup intaggroup) (insert " "))
15336 (setq cnt 0)))))
15337 (setq ntable (nreverse ntable))
15338 (insert "\n")
15339 (goto-char (point-min))
15340 (unless expert (org-fit-window-to-buffer))
15341 (setq rtn
15342 (catch 'exit
15343 (while t
15344 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15345 (if (not groups) "no " "")
15346 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15347 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15348 (setq org-last-tag-selection-key c)
15349 (cond
15350 ((= c ?\r) (throw 'exit t))
15351 ((= c ?!)
15352 (setq groups (not groups))
15353 (goto-char (point-min))
15354 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15355 ((= c ?\C-c)
15356 (if (not expert)
15357 (org-fast-tag-show-exit
15358 (setq exit-after-next (not exit-after-next)))
15359 (setq expert nil)
15360 (delete-other-windows)
15361 (set-window-buffer (split-window-vertically) " *Org tags*")
15362 (org-switch-to-buffer-other-window " *Org tags*")
15363 (org-fit-window-to-buffer)))
15364 ((or (= c ?\C-g)
15365 (and (= c ?q) (not (rassoc c ntable))))
15366 (delete-overlay org-tags-overlay)
15367 (setq quit-flag t))
15368 ((= c ?\ )
15369 (setq current nil)
15370 (when exit-after-next (setq exit-after-next 'now)))
15371 ((= c ?\t)
15372 (condition-case nil
15373 (setq tg (completing-read
15374 "Tag: "
15375 (or buffer-tags
15376 (with-current-buffer buf
15377 (setq buffer-tags
15378 (org-get-buffer-tags))))))
15379 (quit (setq tg "")))
15380 (when (string-match "\\S-" tg)
15381 (cl-pushnew (list tg) buffer-tags :test #'equal)
15382 (if (member tg current)
15383 (setq current (delete tg current))
15384 (push tg current)))
15385 (when exit-after-next (setq exit-after-next 'now)))
15386 ((setq e (rassoc c todo-table) tg (car e))
15387 (with-current-buffer buf
15388 (save-excursion (org-todo tg)))
15389 (when exit-after-next (setq exit-after-next 'now)))
15390 ((setq e (rassoc c ntable) tg (car e))
15391 (if (member tg current)
15392 (setq current (delete tg current))
15393 (cl-loop for g in groups do
15394 (when (member tg g)
15395 (dolist (x g) (setq current (delete x current)))))
15396 (push tg current))
15397 (when exit-after-next (setq exit-after-next 'now))))
15399 ;; Create a sorted list
15400 (setq current
15401 (sort current
15402 (lambda (a b)
15403 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15404 (when (eq exit-after-next 'now) (throw 'exit t))
15405 (goto-char (point-min))
15406 (beginning-of-line 2)
15407 (delete-region (point) (point-at-eol))
15408 (org-fast-tag-insert "Current" current c-face)
15409 (org-set-current-tags-overlay current ov-prefix)
15410 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15411 (setq tg (match-string 1))
15412 (add-text-properties
15413 (match-beginning 1) (match-end 1)
15414 (list 'face
15415 (cond
15416 ((member tg current) c-face)
15417 ((member tg inherited) i-face)
15418 (t (get-text-property (match-beginning 1) 'face))))))
15419 (goto-char (point-min)))))
15420 (delete-overlay org-tags-overlay)
15421 (if rtn
15422 (mapconcat 'identity current ":")
15423 nil))))
15425 (defun org-get-tags-string ()
15426 "Get the TAGS string in the current headline."
15427 (unless (org-at-heading-p t)
15428 (user-error "Not on a heading"))
15429 (save-excursion
15430 (beginning-of-line 1)
15431 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15432 (match-string-no-properties 1)
15433 "")))
15435 (defun org-get-tags ()
15436 "Get the list of tags specified in the current headline."
15437 (org-split-string (org-get-tags-string) ":"))
15439 (defun org-get-buffer-tags ()
15440 "Get a table of all tags used in the buffer, for completion."
15441 (org-with-wide-buffer
15442 (goto-char (point-min))
15443 (let ((tag-re (concat org-outline-regexp-bol
15444 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15445 tags)
15446 (while (re-search-forward tag-re nil t)
15447 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15448 (push tag tags)))
15449 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15451 ;;;; The mapping API
15453 (defvar org-agenda-skip-comment-trees)
15454 (defvar org-agenda-skip-function)
15455 (defun org-map-entries (func &optional match scope &rest skip)
15456 "Call FUNC at each headline selected by MATCH in SCOPE.
15458 FUNC is a function or a lisp form. The function will be called without
15459 arguments, with the cursor positioned at the beginning of the headline.
15460 The return values of all calls to the function will be collected and
15461 returned as a list.
15463 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15464 does not need to preserve point. After evaluation, the cursor will be
15465 moved to the end of the line (presumably of the headline of the
15466 processed entry) and search continues from there. Under some
15467 circumstances, this may not produce the wanted results. For example,
15468 if you have removed (e.g. archived) the current (sub)tree it could
15469 mean that the next entry will be skipped entirely. In such cases, you
15470 can specify the position from where search should continue by making
15471 FUNC set the variable `org-map-continue-from' to the desired buffer
15472 position.
15474 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15475 Only headlines that are matched by this query will be considered during
15476 the iteration. When MATCH is nil or t, all headlines will be
15477 visited by the iteration.
15479 SCOPE determines the scope of this command. It can be any of:
15481 nil The current buffer, respecting the restriction if any
15482 tree The subtree started with the entry at point
15483 region The entries within the active region, if any
15484 region-start-level
15485 The entries within the active region, but only those at
15486 the same level than the first one.
15487 file The current buffer, without restriction
15488 file-with-archives
15489 The current buffer, and any archives associated with it
15490 agenda All agenda files
15491 agenda-with-archives
15492 All agenda files with any archive files associated with them
15493 \(file1 file2 ...)
15494 If this is a list, all files in the list will be scanned
15496 The remaining args are treated as settings for the skipping facilities of
15497 the scanner. The following items can be given here:
15499 archive skip trees with the archive tag
15500 comment skip trees with the COMMENT keyword
15501 function or Emacs Lisp form:
15502 will be used as value for `org-agenda-skip-function', so
15503 whenever the function returns a position, FUNC will not be
15504 called for that entry and search will continue from the
15505 position returned
15507 If your function needs to retrieve the tags including inherited tags
15508 at the *current* entry, you can use the value of the variable
15509 `org-scanner-tags' which will be much faster than getting the value
15510 with `org-get-tags-at'. If your function gets properties with
15511 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15512 to t around the call to `org-entry-properties' to get the same speedup.
15513 Note that if your function moves around to retrieve tags and properties at
15514 a *different* entry, you cannot use these techniques."
15515 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15516 (not (org-region-active-p)))
15517 (let* ((org-agenda-archives-mode nil) ; just to make sure
15518 (org-agenda-skip-archived-trees (memq 'archive skip))
15519 (org-agenda-skip-comment-trees (memq 'comment skip))
15520 (org-agenda-skip-function
15521 (car (org-delete-all '(comment archive) skip)))
15522 (org-tags-match-list-sublevels t)
15523 (start-level (eq scope 'region-start-level))
15524 matcher res
15525 org-todo-keywords-for-agenda
15526 org-done-keywords-for-agenda
15527 org-todo-keyword-alist-for-agenda
15528 org-tag-alist-for-agenda
15529 org--matcher-tags-todo-only)
15531 (cond
15532 ((eq match t) (setq matcher t))
15533 ((eq match nil) (setq matcher t))
15534 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15536 (save-excursion
15537 (save-restriction
15538 (cond ((eq scope 'tree)
15539 (org-back-to-heading t)
15540 (org-narrow-to-subtree)
15541 (setq scope nil))
15542 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15543 (org-region-active-p))
15544 ;; If needed, set start-level to a string like "2"
15545 (when start-level
15546 (save-excursion
15547 (goto-char (region-beginning))
15548 (unless (org-at-heading-p) (outline-next-heading))
15549 (setq start-level (org-current-level))))
15550 (narrow-to-region (region-beginning)
15551 (save-excursion
15552 (goto-char (region-end))
15553 (unless (and (bolp) (org-at-heading-p))
15554 (outline-next-heading))
15555 (point)))
15556 (setq scope nil)))
15558 (if (not scope)
15559 (progn
15560 (org-agenda-prepare-buffers
15561 (and buffer-file-name (list buffer-file-name)))
15562 (setq res
15563 (org-scan-tags
15564 func matcher org--matcher-tags-todo-only start-level)))
15565 ;; Get the right scope
15566 (cond
15567 ((and scope (listp scope) (symbolp (car scope)))
15568 (setq scope (eval scope)))
15569 ((eq scope 'agenda)
15570 (setq scope (org-agenda-files t)))
15571 ((eq scope 'agenda-with-archives)
15572 (setq scope (org-agenda-files t))
15573 (setq scope (org-add-archive-files scope)))
15574 ((eq scope 'file)
15575 (setq scope (and buffer-file-name (list buffer-file-name))))
15576 ((eq scope 'file-with-archives)
15577 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15578 (org-agenda-prepare-buffers scope)
15579 (dolist (file scope)
15580 (with-current-buffer (org-find-base-buffer-visiting file)
15581 (org-with-wide-buffer
15582 (goto-char (point-min))
15583 (setq res
15584 (append
15586 (org-scan-tags
15587 func matcher org--matcher-tags-todo-only)))))))))
15588 res)))
15590 ;;; Properties API
15592 (defconst org-special-properties
15593 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15594 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15595 "The special properties valid in Org mode.
15596 These are properties that are not defined in the property drawer,
15597 but in some other way.")
15599 (defconst org-default-properties
15600 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15601 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15602 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15603 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15604 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15605 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15606 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15607 "Some properties that are used by Org mode for various purposes.
15608 Being in this list makes sure that they are offered for completion.")
15610 (defun org--valid-property-p (property)
15611 "Non nil when string PROPERTY is a valid property name."
15612 (not
15613 (or (equal property "")
15614 (string-match-p "\\s-" property))))
15616 (defun org--update-property-plist (key val props)
15617 "Associate KEY to VAL in alist PROPS.
15618 Modifications are made by side-effect. Return new alist."
15619 (let* ((appending (string= (substring key -1) "+"))
15620 (key (if appending (substring key 0 -1) key))
15621 (old (assoc-string key props t)))
15622 (if (not old) (cons (cons key val) props)
15623 (setcdr old (if appending (concat (cdr old) " " val) val))
15624 props)))
15626 (defun org-get-property-block (&optional beg force)
15627 "Return the (beg . end) range of the body of the property drawer.
15628 BEG is the beginning of the current subtree, or of the part
15629 before the first headline. If it is not given, it will be found.
15630 If the drawer does not exist, create it if FORCE is non-nil, or
15631 return nil."
15632 (org-with-wide-buffer
15633 (when beg (goto-char beg))
15634 (unless (org-before-first-heading-p)
15635 (let ((beg (cond (beg)
15636 ((or (not (featurep 'org-inlinetask))
15637 (org-inlinetask-in-task-p))
15638 (org-back-to-heading t))
15639 (t (org-with-limited-levels (org-back-to-heading t))))))
15640 (forward-line)
15641 (when (looking-at-p org-planning-line-re) (forward-line))
15642 (cond ((looking-at org-property-drawer-re)
15643 (forward-line)
15644 (cons (point) (progn (goto-char (match-end 0))
15645 (line-beginning-position))))
15646 (force
15647 (goto-char beg)
15648 (org-insert-property-drawer)
15649 (let ((pos (save-excursion (search-forward ":END:")
15650 (line-beginning-position))))
15651 (cons pos pos))))))))
15653 (defun org-at-property-p ()
15654 "Non-nil when point is inside a property drawer.
15655 See `org-property-re' for match data, if applicable."
15656 (save-excursion
15657 (beginning-of-line)
15658 (and (looking-at org-property-re)
15659 (let ((property-drawer (save-match-data (org-get-property-block))))
15660 (and property-drawer
15661 (>= (point) (car property-drawer))
15662 (< (point) (cdr property-drawer)))))))
15664 (defun org-property-action ()
15665 "Do an action on properties."
15666 (interactive)
15667 (unless (org-at-property-p) (user-error "Not at a property"))
15668 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15669 (let ((c (read-char-exclusive)))
15670 (cl-case c
15671 (?s (call-interactively #'org-set-property))
15672 (?d (call-interactively #'org-delete-property))
15673 (?D (call-interactively #'org-delete-property-globally))
15674 (?c (call-interactively #'org-compute-property-at-point))
15675 (otherwise (user-error "No such property action %c" c)))))
15677 (defun org-inc-effort ()
15678 "Increment the value of the effort property in the current entry."
15679 (interactive)
15680 (org-set-effort nil t))
15682 (defvar org-clock-effort) ; Defined in org-clock.el.
15683 (defvar org-clock-current-task) ; Defined in org-clock.el.
15684 (defun org-set-effort (&optional value increment)
15685 "Set the effort property of the current entry.
15686 With numerical prefix arg, use the nth allowed value, 0 stands for the
15687 10th allowed value.
15689 When INCREMENT is non-nil, set the property to the next allowed value."
15690 (interactive "P")
15691 (when (equal value 0) (setq value 10))
15692 (let* ((completion-ignore-case t)
15693 (prop org-effort-property)
15694 (cur (org-entry-get nil prop))
15695 (allowed (org-property-get-allowed-values nil prop 'table))
15696 (existing (mapcar 'list (org-property-values prop)))
15697 (heading (nth 4 (org-heading-components)))
15699 (val (cond
15700 ((stringp value) value)
15701 ((and allowed (integerp value))
15702 (or (car (nth (1- value) allowed))
15703 (car (org-last allowed))))
15704 ((and allowed increment)
15705 (or (cl-caadr (member (list cur) allowed))
15706 (user-error "Allowed effort values are not set")))
15707 (allowed
15708 (message "Select 1-9,0, [RET%s]: %s"
15709 (if cur (concat "=" cur) "")
15710 (mapconcat 'car allowed " "))
15711 (setq rpl (read-char-exclusive))
15712 (if (equal rpl ?\r)
15714 (setq rpl (- rpl ?0))
15715 (when (equal rpl 0) (setq rpl 10))
15716 (if (and (> rpl 0) (<= rpl (length allowed)))
15717 (car (nth (1- rpl) allowed))
15718 (org-completing-read "Effort: " allowed nil))))
15720 (org-completing-read
15721 (concat "Effort" (and cur (string-match "\\S-" cur)
15722 (concat " [" cur "]"))
15723 ": ")
15724 existing nil nil "" nil cur)))))
15725 (unless (equal (org-entry-get nil prop) val)
15726 (org-entry-put nil prop val))
15727 (org-refresh-property
15728 '((effort . identity)
15729 (effort-minutes . org-duration-string-to-minutes))
15730 val)
15731 (when (equal heading (bound-and-true-p org-clock-current-task))
15732 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15733 (org-clock-update-mode-line))
15734 (message "%s is now %s" prop val)))
15736 (defun org-entry-properties (&optional pom which)
15737 "Get all properties of the current entry.
15739 When POM is a buffer position, get all properties from the entry
15740 there instead.
15742 This includes the TODO keyword, the tags, time strings for
15743 deadline, scheduled, and clocking, and any additional properties
15744 defined in the entry.
15746 If WHICH is nil or `all', get all properties. If WHICH is
15747 `special' or `standard', only get that subclass. If WHICH is
15748 a string, only get that property.
15750 Return value is an alist. Keys are properties, as upcased
15751 strings."
15752 (org-with-point-at pom
15753 (when (and (derived-mode-p 'org-mode)
15754 (ignore-errors (org-back-to-heading t)))
15755 (catch 'exit
15756 (let* ((beg (point))
15757 (specific (and (stringp which) (upcase which)))
15758 (which (cond ((not specific) which)
15759 ((member specific org-special-properties) 'special)
15760 (t 'standard)))
15761 props)
15762 ;; Get the special properties, like TODO and TAGS.
15763 (when (memq which '(nil all special))
15764 (when (or (not specific) (string= specific "CLOCKSUM"))
15765 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15766 (when clocksum
15767 (push (cons "CLOCKSUM"
15768 (org-minutes-to-clocksum-string clocksum))
15769 props)))
15770 (when specific (throw 'exit props)))
15771 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15772 (let ((clocksumt (get-text-property (point)
15773 :org-clock-minutes-today)))
15774 (when clocksumt
15775 (push (cons "CLOCKSUM_T"
15776 (org-minutes-to-clocksum-string clocksumt))
15777 props)))
15778 (when specific (throw 'exit props)))
15779 (when (or (not specific) (string= specific "ITEM"))
15780 (let ((case-fold-search nil))
15781 (when (looking-at org-complex-heading-regexp)
15782 (push (cons "ITEM"
15783 (let ((title (match-string-no-properties 4)))
15784 (if (org-string-nw-p title)
15785 (org-remove-tabs title)
15786 "")))
15787 props)))
15788 (when specific (throw 'exit props)))
15789 (when (or (not specific) (string= specific "TODO"))
15790 (let ((case-fold-search nil))
15791 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15792 (push (cons "TODO" (match-string-no-properties 2)) props)))
15793 (when specific (throw 'exit props)))
15794 (when (or (not specific) (string= specific "PRIORITY"))
15795 (push (cons "PRIORITY"
15796 (if (looking-at org-priority-regexp)
15797 (match-string-no-properties 2)
15798 (char-to-string org-default-priority)))
15799 props)
15800 (when specific (throw 'exit props)))
15801 (when (or (not specific) (string= specific "FILE"))
15802 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15803 props)
15804 (when specific (throw 'exit props)))
15805 (when (or (not specific) (string= specific "TAGS"))
15806 (let ((value (org-string-nw-p (org-get-tags-string))))
15807 (when value (push (cons "TAGS" value) props)))
15808 (when specific (throw 'exit props)))
15809 (when (or (not specific) (string= specific "ALLTAGS"))
15810 (let ((value (org-get-tags-at)))
15811 (when value
15812 (push (cons "ALLTAGS"
15813 (format ":%s:" (mapconcat #'identity value ":")))
15814 props)))
15815 (when specific (throw 'exit props)))
15816 (when (or (not specific) (string= specific "BLOCKED"))
15817 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15818 (when specific (throw 'exit props)))
15819 (when (or (not specific)
15820 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15821 (forward-line)
15822 (when (looking-at-p org-planning-line-re)
15823 (end-of-line)
15824 (let ((bol (line-beginning-position))
15825 ;; Backward compatibility: time keywords used to
15826 ;; be configurable (before 8.3). Make sure we
15827 ;; get the correct keyword.
15828 (key-assoc `(("CLOSED" . ,org-closed-string)
15829 ("DEADLINE" . ,org-deadline-string)
15830 ("SCHEDULED" . ,org-scheduled-string))))
15831 (dolist (pair (if specific (list (assoc specific key-assoc))
15832 key-assoc))
15833 (save-excursion
15834 (when (search-backward (cdr pair) bol t)
15835 (goto-char (match-end 0))
15836 (skip-chars-forward " \t")
15837 (and (looking-at org-ts-regexp-both)
15838 (push (cons (car pair)
15839 (match-string-no-properties 0))
15840 props)))))))
15841 (when specific (throw 'exit props)))
15842 (when (or (not specific)
15843 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15844 (let ((find-ts
15845 (lambda (end ts)
15846 ;; Fix next time-stamp before END. TS is the
15847 ;; list of time-stamps found so far.
15848 (let ((ts ts)
15849 (regexp (cond
15850 ((string= specific "TIMESTAMP")
15851 org-ts-regexp)
15852 ((string= specific "TIMESTAMP_IA")
15853 org-ts-regexp-inactive)
15854 ((assoc "TIMESTAMP_IA" ts)
15855 org-ts-regexp)
15856 ((assoc "TIMESTAMP" ts)
15857 org-ts-regexp-inactive)
15858 (t org-ts-regexp-both))))
15859 (catch 'next
15860 (while (re-search-forward regexp end t)
15861 (backward-char)
15862 (let ((object (org-element-context)))
15863 ;; Accept to match timestamps in node
15864 ;; properties, too.
15865 (when (memq (org-element-type object)
15866 '(node-property timestamp))
15867 (let ((type
15868 (org-element-property :type object)))
15869 (cond
15870 ((and (memq type '(active active-range))
15871 (not (equal specific "TIMESTAMP_IA")))
15872 (unless (assoc "TIMESTAMP" ts)
15873 (push (cons "TIMESTAMP"
15874 (org-element-property
15875 :raw-value object))
15877 (when specific (throw 'exit ts))))
15878 ((and (memq type '(inactive inactive-range))
15879 (not (string= specific "TIMESTAMP")))
15880 (unless (assoc "TIMESTAMP_IA" ts)
15881 (push (cons "TIMESTAMP_IA"
15882 (org-element-property
15883 :raw-value object))
15885 (when specific (throw 'exit ts))))))
15886 ;; Both timestamp types are found,
15887 ;; move to next part.
15888 (when (= (length ts) 2) (throw 'next ts)))))
15889 ts)))))
15890 (goto-char beg)
15891 ;; First look for timestamps within headline.
15892 (let ((ts (funcall find-ts (line-end-position) nil)))
15893 (if (= (length ts) 2) (setq props (nconc ts props))
15894 ;; Then find timestamps in the section, skipping
15895 ;; planning line.
15896 (let ((end (save-excursion (outline-next-heading))))
15897 (forward-line)
15898 (when (looking-at-p org-planning-line-re) (forward-line))
15899 (setq props (nconc (funcall find-ts end ts) props))))))))
15900 ;; Get the standard properties, like :PROP:.
15901 (when (memq which '(nil all standard))
15902 ;; If we are looking after a specific property, delegate
15903 ;; to `org-entry-get', which is faster. However, make an
15904 ;; exception for "CATEGORY", since it can be also set
15905 ;; through keywords (i.e. #+CATEGORY).
15906 (if (and specific (not (equal specific "CATEGORY")))
15907 (let ((value (org-entry-get beg specific nil t)))
15908 (throw 'exit (and value (list (cons specific value)))))
15909 (let ((range (org-get-property-block beg)))
15910 (when range
15911 (let ((end (cdr range)) seen-base)
15912 (goto-char (car range))
15913 ;; Unlike to `org--update-property-plist', we
15914 ;; handle the case where base values is found
15915 ;; after its extension. We also forbid standard
15916 ;; properties to be named as special properties.
15917 (while (re-search-forward org-property-re end t)
15918 (let* ((key (upcase (match-string-no-properties 2)))
15919 (extendp (string-match-p "\\+\\'" key))
15920 (key-base (if extendp (substring key 0 -1) key))
15921 (value (match-string-no-properties 3)))
15922 (cond
15923 ((member-ignore-case key-base org-special-properties))
15924 (extendp
15925 (setq props
15926 (org--update-property-plist key value props)))
15927 ((member key seen-base))
15928 (t (push key seen-base)
15929 (let ((p (assoc-string key props t)))
15930 (if p (setcdr p (concat value " " (cdr p)))
15931 (push (cons key value) props))))))))))))
15932 (unless (assoc "CATEGORY" props)
15933 (push (cons "CATEGORY" (org-get-category beg)) props)
15934 (when (string= specific "CATEGORY") (throw 'exit props)))
15935 ;; Return value.
15936 props)))))
15938 (defun org--property-local-values (property literal-nil)
15939 "Return value for PROPERTY in current entry.
15940 Value is a list whose car is the base value for PROPERTY and cdr
15941 a list of accumulated values. Return nil if neither is found in
15942 the entry. Also return nil when PROPERTY is set to \"nil\",
15943 unless LITERAL-NIL is non-nil."
15944 (let ((range (org-get-property-block)))
15945 (when range
15946 (goto-char (car range))
15947 (let* ((case-fold-search t)
15948 (end (cdr range))
15949 (value
15950 ;; Base value.
15951 (save-excursion
15952 (let ((v (and (re-search-forward
15953 (org-re-property property nil t) end t)
15954 (match-string-no-properties 3))))
15955 (list (if literal-nil v (org-not-nil v)))))))
15956 ;; Find additional values.
15957 (let* ((property+ (org-re-property (concat property "+") nil t)))
15958 (while (re-search-forward property+ end t)
15959 (push (match-string-no-properties 3) value)))
15960 ;; Return final values.
15961 (and (not (equal value '(nil))) (nreverse value))))))
15963 (defun org--property-global-value (property literal-nil)
15964 "Return value for PROPERTY in current buffer.
15965 Return value is a string. Return nil if property is not set
15966 globally. Also return nil when PROPERTY is set to \"nil\",
15967 unless LITERAL-NIL is non-nil."
15968 (let ((global
15969 (cdr (or (assoc-string property org-file-properties t)
15970 (assoc-string property org-global-properties t)
15971 (assoc-string property org-global-properties-fixed t)))))
15972 (if literal-nil global (org-not-nil global))))
15974 (defun org-entry-get (pom property &optional inherit literal-nil)
15975 "Get value of PROPERTY for entry or content at point-or-marker POM.
15977 If INHERIT is non-nil and the entry does not have the property,
15978 then also check higher levels of the hierarchy. If INHERIT is
15979 the symbol `selective', use inheritance only if the setting in
15980 `org-use-property-inheritance' selects PROPERTY for inheritance.
15982 If the property is present but empty, the return value is the
15983 empty string. If the property is not present at all, nil is
15984 returned. In any other case, return the value as a string.
15985 Search is case-insensitive.
15987 If LITERAL-NIL is set, return the string value \"nil\" as
15988 a string, do not interpret it as the list atom nil. This is used
15989 for inheritance when a \"nil\" value can supersede a non-nil
15990 value higher up the hierarchy."
15991 (org-with-point-at pom
15992 (cond
15993 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15994 ;; We need a special property. Use `org-entry-properties' to
15995 ;; retrieve it, but specify the wanted property.
15996 (cdr (assoc-string property (org-entry-properties nil property))))
15997 ((and inherit
15998 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15999 (org-entry-get-with-inheritance property literal-nil))
16001 (let* ((local (org--property-local-values property literal-nil))
16002 (value (and local (mapconcat #'identity (delq nil local) " "))))
16003 (if literal-nil value (org-not-nil value)))))))
16005 (defun org-property-or-variable-value (var &optional inherit)
16006 "Check if there is a property fixing the value of VAR.
16007 If yes, return this value. If not, return the current value of the variable."
16008 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16009 (if (and prop (stringp prop) (string-match "\\S-" prop))
16010 (read prop)
16011 (symbol-value var))))
16013 (defun org-entry-delete (pom property)
16014 "Delete PROPERTY from entry at point-or-marker POM.
16015 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16016 non-nil when a property was removed."
16017 (org-with-point-at pom
16018 (pcase (org-get-property-block)
16019 (`(,begin . ,origin)
16020 (let* ((end (copy-marker origin))
16021 (re (org-re-property
16022 (concat (regexp-quote property) "\\+?") t t)))
16023 (goto-char begin)
16024 (while (re-search-forward re end t)
16025 (delete-region (match-beginning 0) (line-beginning-position 2)))
16026 ;; If drawer is empty, remove it altogether.
16027 (when (= begin end)
16028 (delete-region (line-beginning-position 0)
16029 (line-beginning-position 2)))
16030 ;; Return non-nil if some property was removed.
16031 (prog1 (/= end origin) (set-marker end nil))))
16032 (_ nil))))
16034 ;; Multi-values properties are properties that contain multiple values
16035 ;; These values are assumed to be single words, separated by whitespace.
16036 (defun org-entry-add-to-multivalued-property (pom property value)
16037 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16038 (let* ((old (org-entry-get pom property))
16039 (values (and old (org-split-string old "[ \t]"))))
16040 (setq value (org-entry-protect-space value))
16041 (unless (member value values)
16042 (setq values (append values (list value)))
16043 (org-entry-put pom property
16044 (mapconcat 'identity values " ")))))
16046 (defun org-entry-remove-from-multivalued-property (pom property value)
16047 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16048 (let* ((old (org-entry-get pom property))
16049 (values (and old (org-split-string old "[ \t]"))))
16050 (setq value (org-entry-protect-space value))
16051 (when (member value values)
16052 (setq values (delete value values))
16053 (org-entry-put pom property
16054 (mapconcat 'identity values " ")))))
16056 (defun org-entry-member-in-multivalued-property (pom property value)
16057 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16058 (let* ((old (org-entry-get pom property))
16059 (values (and old (org-split-string old "[ \t]"))))
16060 (setq value (org-entry-protect-space value))
16061 (member value values)))
16063 (defun org-entry-get-multivalued-property (pom property)
16064 "Return a list of values in a multivalued property."
16065 (let* ((value (org-entry-get pom property))
16066 (values (and value (org-split-string value "[ \t]"))))
16067 (mapcar 'org-entry-restore-space values)))
16069 (defun org-entry-put-multivalued-property (pom property &rest values)
16070 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16071 VALUES should be a list of strings. Spaces will be protected."
16072 (org-entry-put pom property
16073 (mapconcat 'org-entry-protect-space values " "))
16074 (let* ((value (org-entry-get pom property))
16075 (values (and value (org-split-string value "[ \t]"))))
16076 (mapcar 'org-entry-restore-space values)))
16078 (defun org-entry-protect-space (s)
16079 "Protect spaces and newline in string S."
16080 (while (string-match " " s)
16081 (setq s (replace-match "%20" t t s)))
16082 (while (string-match "\n" s)
16083 (setq s (replace-match "%0A" t t s)))
16086 (defun org-entry-restore-space (s)
16087 "Restore spaces and newline in string S."
16088 (while (string-match "%20" s)
16089 (setq s (replace-match " " t t s)))
16090 (while (string-match "%0A" s)
16091 (setq s (replace-match "\n" t t s)))
16094 (defvar org-entry-property-inherited-from (make-marker)
16095 "Marker pointing to the entry from where a property was inherited.
16096 Each call to `org-entry-get-with-inheritance' will set this marker to the
16097 location of the entry where the inheritance search matched. If there was
16098 no match, the marker will point nowhere.
16099 Note that also `org-entry-get' calls this function, if the INHERIT flag
16100 is set.")
16102 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16103 "Get PROPERTY of entry or content at point, search higher levels if needed.
16104 The search will stop at the first ancestor which has the property defined.
16105 If the value found is \"nil\", return nil to show that the property
16106 should be considered as undefined (this is the meaning of nil here).
16107 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16108 (move-marker org-entry-property-inherited-from nil)
16109 (org-with-wide-buffer
16110 (let (value)
16111 (catch 'exit
16112 (while t
16113 (let ((v (org--property-local-values property literal-nil)))
16114 (when v
16115 (setq value
16116 (concat (mapconcat #'identity (delq nil v) " ")
16117 (and value " ")
16118 value)))
16119 (cond
16120 ((car v)
16121 (org-back-to-heading t)
16122 (move-marker org-entry-property-inherited-from (point))
16123 (throw 'exit nil))
16124 ((org-up-heading-safe))
16126 (let ((global (org--property-global-value property literal-nil)))
16127 (cond ((not global))
16128 (value (setq value (concat global " " value)))
16129 (t (setq value global))))
16130 (throw 'exit nil))))))
16131 (if literal-nil value (org-not-nil value)))))
16133 (defvar org-property-changed-functions nil
16134 "Hook called when the value of a property has changed.
16135 Each hook function should accept two arguments, the name of the property
16136 and the new value.")
16138 (defun org-entry-put (pom property value)
16139 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16141 If the value is nil, it is converted to the empty string. If it
16142 is not a string, an error is raised. Also raise an error on
16143 invalid property names.
16145 PROPERTY can be any regular property (see
16146 `org-special-properties'). It can also be \"TODO\",
16147 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16149 For the last two properties, VALUE may have any of the special
16150 values \"earlier\" and \"later\". The function then increases or
16151 decreases scheduled or deadline date by one day."
16152 (cond ((null value) (setq value ""))
16153 ((not (stringp value)) (error "Properties values should be strings"))
16154 ((not (org--valid-property-p property))
16155 (user-error "Invalid property name: \"%s\"" property)))
16156 (org-with-point-at pom
16157 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16158 (org-back-to-heading t)
16159 (org-with-limited-levels (org-back-to-heading t)))
16160 (let ((beg (point)))
16161 (cond
16162 ((equal property "TODO")
16163 (cond ((not (org-string-nw-p value)) (setq value 'none))
16164 ((not (member value org-todo-keywords-1))
16165 (user-error "\"%s\" is not a valid TODO state" value)))
16166 (org-todo value)
16167 (org-set-tags nil 'align))
16168 ((equal property "PRIORITY")
16169 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16170 (org-set-tags nil 'align))
16171 ((equal property "SCHEDULED")
16172 (forward-line)
16173 (if (and (looking-at-p org-planning-line-re)
16174 (re-search-forward
16175 org-scheduled-time-regexp (line-end-position) t))
16176 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16177 ((string= value "later") (org-timestamp-change 1 'day))
16178 ((string= value "") (org-schedule '(4)))
16179 (t (org-schedule nil value)))
16180 (if (member value '("earlier" "later" ""))
16181 (call-interactively #'org-schedule)
16182 (org-schedule nil value))))
16183 ((equal property "DEADLINE")
16184 (forward-line)
16185 (if (and (looking-at-p org-planning-line-re)
16186 (re-search-forward
16187 org-deadline-time-regexp (line-end-position) t))
16188 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16189 ((string= value "later") (org-timestamp-change 1 'day))
16190 ((string= value "") (org-deadline '(4)))
16191 (t (org-deadline nil value)))
16192 (if (member value '("earlier" "later" ""))
16193 (call-interactively #'org-deadline)
16194 (org-deadline nil value))))
16195 ((member property org-special-properties)
16196 (error "The %s property cannot be set with `org-entry-put'" property))
16198 (let* ((range (org-get-property-block beg 'force))
16199 (end (cdr range))
16200 (case-fold-search t))
16201 (goto-char (car range))
16202 (if (re-search-forward (org-re-property property nil t) end t)
16203 (progn (delete-region (match-beginning 0) (match-end 0))
16204 (goto-char (match-beginning 0)))
16205 (goto-char end)
16206 (insert "\n")
16207 (backward-char))
16208 (insert ":" property ":")
16209 (when value (insert " " value))
16210 (org-indent-line)))))
16211 (run-hook-with-args 'org-property-changed-functions property value)))
16213 (defun org-buffer-property-keys
16214 (&optional specials defaults columns ignore-malformed)
16215 "Get all property keys in the current buffer.
16217 When SPECIALS is non-nil, also list the special properties that
16218 reflect things like tags and TODO state.
16220 When DEFAULTS is non-nil, also include properties that has
16221 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16222 DESCRIPTION, LOCATION, and LOGGING and others.
16224 When COLUMNS in non-nil, also include property names given in
16225 COLUMN formats in the current buffer.
16227 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16228 automatically performed, such drawers will be silently ignored."
16229 (let ((case-fold-search t)
16230 (props (append
16231 (and specials org-special-properties)
16232 (and defaults (cons org-effort-property org-default-properties))
16233 nil)))
16234 (org-with-wide-buffer
16235 (goto-char (point-min))
16236 (while (re-search-forward org-property-start-re nil t)
16237 (let ((range (org-get-property-block)))
16238 (catch 'skip
16239 (unless range
16240 (when (and (not ignore-malformed)
16241 (not (org-before-first-heading-p))
16242 (y-or-n-p (format "Malformed drawer at %d, repair?"
16243 (line-beginning-position))))
16244 (org-get-property-block nil t))
16245 (throw 'skip nil))
16246 (goto-char (car range))
16247 (let ((begin (car range))
16248 (end (cdr range)))
16249 ;; Make sure that found property block is not located
16250 ;; before current point, as it would generate an infloop.
16251 ;; It can happen, for example, in the following
16252 ;; situation:
16254 ;; * Headline
16255 ;; :PROPERTIES:
16256 ;; ...
16257 ;; :END:
16258 ;; *************** Inlinetask
16259 ;; #+BEGIN_EXAMPLE
16260 ;; :PROPERTIES:
16261 ;; #+END_EXAMPLE
16263 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16264 (while (< (point) end)
16265 (let ((p (progn (looking-at org-property-re)
16266 (match-string-no-properties 2))))
16267 ;; Only add true property name, not extension symbol.
16268 (push (if (not (string-match-p "\\+\\'" p)) p
16269 (substring p 0 -1))
16270 props))
16271 (forward-line))))
16272 (outline-next-heading)))
16273 (when columns
16274 (goto-char (point-min))
16275 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16276 (let ((element (org-element-at-point)))
16277 (when (memq (org-element-type element) '(keyword node-property))
16278 (let ((value (org-element-property :value element))
16279 (start 0))
16280 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16281 (setq start (match-end 0))
16282 (let ((p (match-string-no-properties 1 value)))
16283 (unless (member-ignore-case p org-special-properties)
16284 (push p props))))))))))
16285 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16287 (defun org-property-values (key)
16288 "List all non-nil values of property KEY in current buffer."
16289 (org-with-wide-buffer
16290 (goto-char (point-min))
16291 (let ((case-fold-search t)
16292 (re (org-re-property key))
16293 values)
16294 (while (re-search-forward re nil t)
16295 (push (org-entry-get (point) key) values))
16296 (delete-dups values))))
16298 (defun org-insert-property-drawer ()
16299 "Insert a property drawer into the current entry."
16300 (org-with-wide-buffer
16301 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16302 (org-back-to-heading t)
16303 (org-with-limited-levels (org-back-to-heading t)))
16304 (forward-line)
16305 (when (looking-at-p org-planning-line-re) (forward-line))
16306 (unless (looking-at-p org-property-drawer-re)
16307 ;; Make sure we start editing a line from current entry, not from
16308 ;; next one. It prevents extending text properties or overlays
16309 ;; belonging to the latter.
16310 (when (bolp) (backward-char))
16311 (let ((begin (1+ (point)))
16312 (inhibit-read-only t))
16313 (insert "\n:PROPERTIES:\n:END:")
16314 (when (eobp) (insert "\n"))
16315 (org-indent-region begin (point))))))
16317 (defun org-insert-drawer (&optional arg drawer)
16318 "Insert a drawer at point.
16320 When optional argument ARG is non-nil, insert a property drawer.
16322 Optional argument DRAWER, when non-nil, is a string representing
16323 drawer's name. Otherwise, the user is prompted for a name.
16325 If a region is active, insert the drawer around that region
16326 instead.
16328 Point is left between drawer's boundaries."
16329 (interactive "P")
16330 (let* ((drawer (if arg "PROPERTIES"
16331 (or drawer (read-from-minibuffer "Drawer: ")))))
16332 (cond
16333 ;; With C-u, fall back on `org-insert-property-drawer'
16334 (arg (org-insert-property-drawer))
16335 ;; Check validity of suggested drawer's name.
16336 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16337 (user-error "Invalid drawer name"))
16338 ;; With an active region, insert a drawer at point.
16339 ((not (org-region-active-p))
16340 (progn
16341 (unless (bolp) (insert "\n"))
16342 (insert (format ":%s:\n\n:END:\n" drawer))
16343 (forward-line -2)))
16344 ;; Otherwise, insert the drawer at point
16346 (let ((rbeg (region-beginning))
16347 (rend (copy-marker (region-end))))
16348 (unwind-protect
16349 (progn
16350 (goto-char rbeg)
16351 (beginning-of-line)
16352 (when (save-excursion
16353 (re-search-forward org-outline-regexp-bol rend t))
16354 (user-error "Drawers cannot contain headlines"))
16355 ;; Position point at the beginning of the first
16356 ;; non-blank line in region. Insert drawer's opening
16357 ;; there, then indent it.
16358 (org-skip-whitespace)
16359 (beginning-of-line)
16360 (insert ":" drawer ":\n")
16361 (forward-line -1)
16362 (indent-for-tab-command)
16363 ;; Move point to the beginning of the first blank line
16364 ;; after the last non-blank line in region. Insert
16365 ;; drawer's closing, then indent it.
16366 (goto-char rend)
16367 (skip-chars-backward " \r\t\n")
16368 (insert "\n:END:")
16369 (deactivate-mark t)
16370 (indent-for-tab-command)
16371 (unless (eolp) (insert "\n")))
16372 ;; Clear marker, whatever the outcome of insertion is.
16373 (set-marker rend nil)))))))
16375 (defvar org-property-set-functions-alist nil
16376 "Property set function alist.
16377 Each entry should have the following format:
16379 (PROPERTY . READ-FUNCTION)
16381 The read function will be called with the same argument as
16382 `org-completing-read'.")
16384 (defun org-set-property-function (property)
16385 "Get the function that should be used to set PROPERTY.
16386 This is computed according to `org-property-set-functions-alist'."
16387 (or (cdr (assoc property org-property-set-functions-alist))
16388 'org-completing-read))
16390 (defun org-read-property-value (property)
16391 "Read PROPERTY value from user."
16392 (let* ((completion-ignore-case t)
16393 (allowed (org-property-get-allowed-values nil property 'table))
16394 (cur (org-entry-get nil property))
16395 (prompt (concat property " value"
16396 (if (and cur (string-match "\\S-" cur))
16397 (concat " [" cur "]") "") ": "))
16398 (set-function (org-set-property-function property))
16399 (val (if allowed
16400 (funcall set-function prompt allowed nil
16401 (not (get-text-property 0 'org-unrestricted
16402 (caar allowed))))
16403 (funcall set-function prompt
16404 (mapcar 'list (org-property-values property))
16405 nil nil "" nil cur))))
16406 (org-trim val)))
16408 (defvar org-last-set-property nil)
16409 (defvar org-last-set-property-value nil)
16410 (defun org-read-property-name ()
16411 "Read a property name."
16412 (let ((completion-ignore-case t)
16413 (default-prop (or (and (org-at-property-p)
16414 (match-string-no-properties 2))
16415 org-last-set-property)))
16416 (org-completing-read
16417 (concat "Property"
16418 (if default-prop (concat " [" default-prop "]") "")
16419 ": ")
16420 (mapcar #'list (org-buffer-property-keys nil t t))
16421 nil nil nil nil default-prop)))
16423 (defun org-set-property-and-value (use-last)
16424 "Allow to set [PROPERTY]: [value] direction from prompt.
16425 When use-default, don't even ask, just use the last
16426 \"[PROPERTY]: [value]\" string from the history."
16427 (interactive "P")
16428 (let* ((completion-ignore-case t)
16429 (pv (or (and use-last org-last-set-property-value)
16430 (org-completing-read
16431 "Enter a \"[Property]: [value]\" pair: "
16432 nil nil nil nil nil
16433 org-last-set-property-value)))
16434 prop val)
16435 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16436 (setq prop (match-string 1 pv)
16437 val (match-string 2 pv))
16438 (org-set-property prop val))))
16440 (defun org-set-property (property value)
16441 "In the current entry, set PROPERTY to VALUE.
16443 When called interactively, this will prompt for a property name, offering
16444 completion on existing and default properties. And then it will prompt
16445 for a value, offering completion either on allowed values (via an inherited
16446 xxx_ALL property) or on existing values in other instances of this property
16447 in the current file.
16449 Throw an error when trying to set a property with an invalid name."
16450 (interactive (list nil nil))
16451 (let ((property (or property (org-read-property-name))))
16452 ;; `org-entry-put' also makes the following check, but this one
16453 ;; avoids polluting `org-last-set-property' and
16454 ;; `org-last-set-property-value' needlessly.
16455 (unless (org--valid-property-p property)
16456 (user-error "Invalid property name: \"%s\"" property))
16457 (let ((value (or value (org-read-property-value property)))
16458 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16459 (setq org-last-set-property property)
16460 (setq org-last-set-property-value (concat property ": " value))
16461 ;; Possibly postprocess the inserted value:
16462 (when fn (setq value (funcall fn value)))
16463 (unless (equal (org-entry-get nil property) value)
16464 (org-entry-put nil property value)))))
16466 (defun org-find-property (property &optional value)
16467 "Find first entry in buffer that sets PROPERTY.
16469 When optional argument VALUE is non-nil, only consider an entry
16470 if it contains PROPERTY set to this value. If PROPERTY should be
16471 explicitly set to nil, use string \"nil\" for VALUE.
16473 Return position where the entry begins, or nil if there is no
16474 such entry. If narrowing is in effect, only search the visible
16475 part of the buffer."
16476 (save-excursion
16477 (goto-char (point-min))
16478 (let ((case-fold-search t)
16479 (re (org-re-property property nil (not value) value)))
16480 (catch 'exit
16481 (while (re-search-forward re nil t)
16482 (when (if value (org-at-property-p)
16483 (org-entry-get (point) property nil t))
16484 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16486 (defun org-delete-property (property)
16487 "In the current entry, delete PROPERTY."
16488 (interactive
16489 (let* ((completion-ignore-case t)
16490 (cat (org-entry-get (point) "CATEGORY"))
16491 (props0 (org-entry-properties nil 'standard))
16492 (props (if cat props0
16493 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16494 (prop (if (< 1 (length props))
16495 (completing-read "Property: " props nil t)
16496 (caar props))))
16497 (list prop)))
16498 (if (not property)
16499 (message "No property to delete in this entry")
16500 (org-entry-delete nil property)
16501 (message "Property \"%s\" deleted" property)))
16503 (defun org-delete-property-globally (property)
16504 "Remove PROPERTY globally, from all entries.
16505 This function ignores narrowing, if any."
16506 (interactive
16507 (let* ((completion-ignore-case t)
16508 (prop (completing-read
16509 "Globally remove property: "
16510 (mapcar #'list (org-buffer-property-keys)))))
16511 (list prop)))
16512 (org-with-wide-buffer
16513 (goto-char (point-min))
16514 (let ((count 0)
16515 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16516 (while (re-search-forward re nil t)
16517 (when (org-entry-delete (point) property) (cl-incf count)))
16518 (message "Property \"%s\" removed from %d entries" property count))))
16520 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16522 (defun org-compute-property-at-point ()
16523 "Compute the property at point.
16524 This looks for an enclosing column format, extracts the operator and
16525 then applies it to the property in the column format's scope."
16526 (interactive)
16527 (unless (org-at-property-p)
16528 (user-error "Not at a property"))
16529 (let ((prop (match-string-no-properties 2)))
16530 (org-columns-get-format-and-top-level)
16531 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16532 (user-error "No operator defined for property %s" prop))
16533 (org-columns-compute prop)))
16535 (defvar org-property-allowed-value-functions nil
16536 "Hook for functions supplying allowed values for a specific property.
16537 The functions must take a single argument, the name of the property, and
16538 return a flat list of allowed values. If \":ETC\" is one of
16539 the values, this means that these values are intended as defaults for
16540 completion, but that other values should be allowed too.
16541 The functions must return nil if they are not responsible for this
16542 property.")
16544 (defun org-property-get-allowed-values (pom property &optional table)
16545 "Get allowed values for the property PROPERTY.
16546 When TABLE is non-nil, return an alist that can directly be used for
16547 completion."
16548 (let (vals)
16549 (cond
16550 ((equal property "TODO")
16551 (setq vals (org-with-point-at pom
16552 (append org-todo-keywords-1 '("")))))
16553 ((equal property "PRIORITY")
16554 (let ((n org-lowest-priority))
16555 (while (>= n org-highest-priority)
16556 (push (char-to-string n) vals)
16557 (setq n (1- n)))))
16558 ((equal property "CATEGORY"))
16559 ((member property org-special-properties))
16560 ((setq vals (run-hook-with-args-until-success
16561 'org-property-allowed-value-functions property)))
16563 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16564 (when (and vals (string-match "\\S-" vals))
16565 (setq vals (car (read-from-string (concat "(" vals ")"))))
16566 (setq vals (mapcar (lambda (x)
16567 (cond ((stringp x) x)
16568 ((numberp x) (number-to-string x))
16569 ((symbolp x) (symbol-name x))
16570 (t "???")))
16571 vals)))))
16572 (when (member ":ETC" vals)
16573 (setq vals (remove ":ETC" vals))
16574 (org-add-props (car vals) '(org-unrestricted t)))
16575 (if table (mapcar 'list vals) vals)))
16577 (defun org-property-previous-allowed-value (&optional _previous)
16578 "Switch to the next allowed value for this property."
16579 (interactive)
16580 (org-property-next-allowed-value t))
16582 (defun org-property-next-allowed-value (&optional previous)
16583 "Switch to the next allowed value for this property."
16584 (interactive)
16585 (unless (org-at-property-p)
16586 (user-error "Not at a property"))
16587 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16588 (key (match-string 2))
16589 (value (match-string 3))
16590 (allowed (or (org-property-get-allowed-values (point) key)
16591 (and (member value '("[ ]" "[-]" "[X]"))
16592 '("[ ]" "[X]"))))
16593 (heading (save-match-data (nth 4 (org-heading-components))))
16594 nval)
16595 (unless allowed
16596 (user-error "Allowed values for this property have not been defined"))
16597 (when previous (setq allowed (reverse allowed)))
16598 (when (member value allowed)
16599 (setq nval (car (cdr (member value allowed)))))
16600 (setq nval (or nval (car allowed)))
16601 (when (equal nval value)
16602 (user-error "Only one allowed value for this property"))
16603 (org-at-property-p)
16604 (replace-match (concat " :" key ": " nval) t t)
16605 (org-indent-line)
16606 (beginning-of-line 1)
16607 (skip-chars-forward " \t")
16608 (when (equal prop org-effort-property)
16609 (org-refresh-property
16610 '((effort . identity)
16611 (effort-minutes . org-duration-string-to-minutes))
16612 nval)
16613 (when (string= org-clock-current-task heading)
16614 (setq org-clock-effort nval)
16615 (org-clock-update-mode-line)))
16616 (run-hook-with-args 'org-property-changed-functions key nval)))
16618 (defun org-find-olp (path &optional this-buffer)
16619 "Return a marker pointing to the entry at outline path OLP.
16620 If anything goes wrong, throw an error.
16621 You can wrap this call to catch the error like this:
16623 (condition-case msg
16624 (org-mobile-locate-entry (match-string 4))
16625 (error (nth 1 msg)))
16627 The return value will then be either a string with the error message,
16628 or a marker if everything is OK.
16630 If THIS-BUFFER is set, the outline path does not contain a file,
16631 only headings."
16632 (let* ((file (if this-buffer buffer-file-name (pop path)))
16633 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16634 (level 1)
16635 (lmin 1)
16636 (lmax 1)
16637 end found flevel)
16638 (unless buffer (error "File not found :%s" file))
16639 (with-current-buffer buffer
16640 (org-with-wide-buffer
16641 (goto-char (point-min))
16642 (dolist (heading path)
16643 (let ((re (format org-complex-heading-regexp-format
16644 (regexp-quote heading)))
16645 (cnt 0))
16646 (while (re-search-forward re end t)
16647 (setq level (- (match-end 1) (match-beginning 1)))
16648 (when (and (>= level lmin) (<= level lmax))
16649 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16650 (when (= cnt 0)
16651 (error "Heading not found on level %d: %s" lmax heading))
16652 (when (> cnt 1)
16653 (error "Heading not unique on level %d: %s" lmax heading))
16654 (goto-char found)
16655 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16656 (setq end (save-excursion (org-end-of-subtree t t)))))
16657 (when (org-at-heading-p)
16658 (point-marker))))))
16660 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16661 "Find node HEADING in BUFFER.
16662 Return a marker to the heading if it was found, or nil if not.
16663 If POS-ONLY is set, return just the position instead of a marker.
16665 The heading text must match exact, but it may have a TODO keyword,
16666 a priority cookie and tags in the standard locations."
16667 (with-current-buffer (or buffer (current-buffer))
16668 (org-with-wide-buffer
16669 (goto-char (point-min))
16670 (let (case-fold-search)
16671 (when (re-search-forward
16672 (format org-complex-heading-regexp-format
16673 (regexp-quote heading)) nil t)
16674 (if pos-only
16675 (match-beginning 0)
16676 (move-marker (make-marker) (match-beginning 0))))))))
16678 (defun org-find-exact-heading-in-directory (heading &optional dir)
16679 "Find Org node headline HEADING in all .org files in directory DIR.
16680 When the target headline is found, return a marker to this location."
16681 (let ((files (directory-files (or dir default-directory)
16682 t "\\`[^.#].*\\.org\\'"))
16683 visiting m buffer)
16684 (catch 'found
16685 (dolist (file files)
16686 (message "trying %s" file)
16687 (setq visiting (org-find-base-buffer-visiting file))
16688 (setq buffer (or visiting (find-file-noselect file)))
16689 (setq m (org-find-exact-headline-in-buffer
16690 heading buffer))
16691 (when (and (not m) (not visiting)) (kill-buffer buffer))
16692 (and m (throw 'found m))))))
16694 (defun org-find-entry-with-id (ident)
16695 "Locate the entry that contains the ID property with exact value IDENT.
16696 IDENT can be a string, a symbol or a number, this function will search for
16697 the string representation of it.
16698 Return the position where this entry starts, or nil if there is no such entry."
16699 (interactive "sID: ")
16700 (let ((id (cond
16701 ((stringp ident) ident)
16702 ((symbolp ident) (symbol-name ident))
16703 ((numberp ident) (number-to-string ident))
16704 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16705 (org-with-wide-buffer (org-find-property "ID" id))))
16707 ;;;; Timestamps
16709 (defvar org-last-changed-timestamp nil)
16710 (defvar org-last-inserted-timestamp nil
16711 "The last time stamp inserted with `org-insert-time-stamp'.")
16712 (defvar org-ts-what) ; dynamically scoped parameter
16714 (defun org-time-stamp (arg &optional inactive)
16715 "Prompt for a date/time and insert a time stamp.
16717 If the user specifies a time like HH:MM or if this command is
16718 called with at least one prefix argument, the time stamp contains
16719 the date and the time. Otherwise, only the date is included.
16721 All parts of a date not specified by the user are filled in from
16722 the timestamp at point, if any, or the current date/time
16723 otherwise.
16725 If there is already a timestamp at the cursor, it is replaced.
16727 With two universal prefix arguments, insert an active timestamp
16728 with the current time without prompting the user.
16730 When called from lisp, the timestamp is inactive if INACTIVE is
16731 non-nil."
16732 (interactive "P")
16733 (let* ((ts (cond
16734 ((org-at-date-range-p t)
16735 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16736 ((org-at-timestamp-p t) (match-string 0))))
16737 ;; Default time is either the timestamp at point or today.
16738 ;; When entering a range, only the range start is considered.
16739 (default-time (if (not ts) (current-time)
16740 (apply #'encode-time (org-parse-time-string ts))))
16741 (default-input (and ts (org-get-compact-tod ts)))
16742 (repeater (and ts
16743 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16744 (match-string 0 ts)))
16745 org-time-was-given
16746 org-end-time-was-given
16747 (time
16748 (and (if (equal arg '(16)) (current-time)
16749 ;; Preserve `this-command' and `last-command'.
16750 (let ((this-command this-command)
16751 (last-command last-command))
16752 (org-read-date
16753 arg 'totime nil nil default-time default-input
16754 inactive))))))
16755 (cond
16756 ((and ts
16757 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16758 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16759 (insert "--")
16760 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16762 ;; Make sure we're on a timestamp. When in the middle of a date
16763 ;; range, move arbitrarily to range end.
16764 (unless (org-at-timestamp-p t)
16765 (skip-chars-forward "-")
16766 (org-at-timestamp-p t))
16767 (replace-match "")
16768 (setq org-last-changed-timestamp
16769 (org-insert-time-stamp
16770 time (or org-time-was-given arg)
16771 inactive nil nil (list org-end-time-was-given)))
16772 (when repeater
16773 (backward-char)
16774 (insert " " repeater)
16775 (setq org-last-changed-timestamp
16776 (concat (substring org-last-inserted-timestamp 0 -1)
16777 " " repeater ">")))
16778 (message "Timestamp updated"))
16779 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16780 (t (org-insert-time-stamp
16781 time (or org-time-was-given arg) inactive nil nil
16782 (list org-end-time-was-given))))))
16784 ;; FIXME: can we use this for something else, like computing time differences?
16785 (defun org-get-compact-tod (s)
16786 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16787 (let* ((t1 (match-string 1 s))
16788 (h1 (string-to-number (match-string 2 s)))
16789 (m1 (string-to-number (match-string 3 s)))
16790 (t2 (and (match-end 4) (match-string 5 s)))
16791 (h2 (and t2 (string-to-number (match-string 6 s))))
16792 (m2 (and t2 (string-to-number (match-string 7 s))))
16793 dh dm)
16794 (if (not t2)
16796 (setq dh (- h2 h1) dm (- m2 m1))
16797 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16798 (concat t1 "+" (number-to-string dh)
16799 (and (/= 0 dm) (format ":%02d" dm)))))))
16801 (defun org-time-stamp-inactive (&optional arg)
16802 "Insert an inactive time stamp.
16803 An inactive time stamp is enclosed in square brackets instead of angle
16804 brackets. It is inactive in the sense that it does not trigger agenda entries,
16805 does not link to the calendar and cannot be changed with the S-cursor keys.
16806 So these are more for recording a certain time/date."
16807 (interactive "P")
16808 (org-time-stamp arg 'inactive))
16810 (defvar org-date-ovl (make-overlay 1 1))
16811 (overlay-put org-date-ovl 'face 'org-date-selected)
16812 (delete-overlay org-date-ovl)
16814 (defvar org-ans1) ; dynamically scoped parameter
16815 (defvar org-ans2) ; dynamically scoped parameter
16817 (defvar org-plain-time-of-day-regexp) ; defined below
16819 (defvar org-overriding-default-time nil) ; dynamically scoped
16820 (defvar org-read-date-overlay nil)
16821 (defvar org-dcst nil) ; dynamically scoped
16822 (defvar org-read-date-history nil)
16823 (defvar org-read-date-final-answer nil)
16824 (defvar org-read-date-analyze-futurep nil)
16825 (defvar org-read-date-analyze-forced-year nil)
16826 (defvar org-read-date-inactive)
16828 (defvar org-read-date-minibuffer-local-map
16829 (let* ((map (make-sparse-keymap)))
16830 (set-keymap-parent map minibuffer-local-map)
16831 (org-defkey map (kbd ".")
16832 (lambda () (interactive)
16833 ;; Are we at the beginning of the prompt?
16834 (if (looking-back "^[^:]+: "
16835 (let ((inhibit-field-text-motion t))
16836 (line-beginning-position)))
16837 (org-eval-in-calendar '(calendar-goto-today))
16838 (insert "."))))
16839 (org-defkey map (kbd "C-.")
16840 (lambda () (interactive)
16841 (org-eval-in-calendar '(calendar-goto-today))))
16842 (org-defkey map [(meta shift left)]
16843 (lambda () (interactive)
16844 (org-eval-in-calendar '(calendar-backward-month 1))))
16845 (org-defkey map [(meta shift right)]
16846 (lambda () (interactive)
16847 (org-eval-in-calendar '(calendar-forward-month 1))))
16848 (org-defkey map [(meta shift up)]
16849 (lambda () (interactive)
16850 (org-eval-in-calendar '(calendar-backward-year 1))))
16851 (org-defkey map [(meta shift down)]
16852 (lambda () (interactive)
16853 (org-eval-in-calendar '(calendar-forward-year 1))))
16854 (org-defkey map [?\e (shift left)]
16855 (lambda () (interactive)
16856 (org-eval-in-calendar '(calendar-backward-month 1))))
16857 (org-defkey map [?\e (shift right)]
16858 (lambda () (interactive)
16859 (org-eval-in-calendar '(calendar-forward-month 1))))
16860 (org-defkey map [?\e (shift up)]
16861 (lambda () (interactive)
16862 (org-eval-in-calendar '(calendar-backward-year 1))))
16863 (org-defkey map [?\e (shift down)]
16864 (lambda () (interactive)
16865 (org-eval-in-calendar '(calendar-forward-year 1))))
16866 (org-defkey map [(shift up)]
16867 (lambda () (interactive)
16868 (org-eval-in-calendar '(calendar-backward-week 1))))
16869 (org-defkey map [(shift down)]
16870 (lambda () (interactive)
16871 (org-eval-in-calendar '(calendar-forward-week 1))))
16872 (org-defkey map [(shift left)]
16873 (lambda () (interactive)
16874 (org-eval-in-calendar '(calendar-backward-day 1))))
16875 (org-defkey map [(shift right)]
16876 (lambda () (interactive)
16877 (org-eval-in-calendar '(calendar-forward-day 1))))
16878 (org-defkey map "!"
16879 (lambda () (interactive)
16880 (org-eval-in-calendar '(diary-view-entries))
16881 (message "")))
16882 (org-defkey map ">"
16883 (lambda () (interactive)
16884 (org-eval-in-calendar '(calendar-scroll-left 1))))
16885 (org-defkey map "<"
16886 (lambda () (interactive)
16887 (org-eval-in-calendar '(calendar-scroll-right 1))))
16888 (org-defkey map "\C-v"
16889 (lambda () (interactive)
16890 (org-eval-in-calendar
16891 '(calendar-scroll-left-three-months 1))))
16892 (org-defkey map "\M-v"
16893 (lambda () (interactive)
16894 (org-eval-in-calendar
16895 '(calendar-scroll-right-three-months 1))))
16896 map)
16897 "Keymap for minibuffer commands when using `org-read-date'.")
16899 (defvar org-def)
16900 (defvar org-defdecode)
16901 (defvar org-with-time)
16903 (defvar calendar-setup) ; Dynamically scoped.
16904 (defun org-read-date (&optional with-time to-time from-string prompt
16905 default-time default-input inactive)
16906 "Read a date, possibly a time, and make things smooth for the user.
16907 The prompt will suggest to enter an ISO date, but you can also enter anything
16908 which will at least partially be understood by `parse-time-string'.
16909 Unrecognized parts of the date will default to the current day, month, year,
16910 hour and minute. If this command is called to replace a timestamp at point,
16911 or to enter the second timestamp of a range, the default time is taken
16912 from the existing stamp. Furthermore, the command prefers the future,
16913 so if you are giving a date where the year is not given, and the day-month
16914 combination is already past in the current year, it will assume you
16915 mean next year. For details, see the manual. A few examples:
16917 3-2-5 --> 2003-02-05
16918 feb 15 --> currentyear-02-15
16919 2/15 --> currentyear-02-15
16920 sep 12 9 --> 2009-09-12
16921 12:45 --> today 12:45
16922 22 sept 0:34 --> currentyear-09-22 0:34
16923 12 --> currentyear-currentmonth-12
16924 Fri --> nearest Friday after today
16925 -Tue --> last Tuesday
16926 etc.
16928 Furthermore you can specify a relative date by giving, as the *first* thing
16929 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16930 change in days weeks, months, years.
16931 With a single plus or minus, the date is relative to today. With a double
16932 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16933 +4d --> four days from today
16934 +4 --> same as above
16935 +2w --> two weeks from today
16936 ++5 --> five days from default date
16938 The function understands only English month and weekday abbreviations.
16940 While prompting, a calendar is popped up - you can also select the
16941 date with the mouse (button 1). The calendar shows a period of three
16942 months. To scroll it to other months, use the keys `>' and `<'.
16943 If you don't like the calendar, turn it off with
16944 (setq org-read-date-popup-calendar nil)
16946 With optional argument TO-TIME, the date will immediately be converted
16947 to an internal time.
16948 With an optional argument WITH-TIME, the prompt will suggest to
16949 also insert a time. Note that when WITH-TIME is not set, you can
16950 still enter a time, and this function will inform the calling routine
16951 about this change. The calling routine may then choose to change the
16952 format used to insert the time stamp into the buffer to include the time.
16953 With optional argument FROM-STRING, read from this string instead from
16954 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16955 the time/date that is used for everything that is not specified by the
16956 user."
16957 (require 'parse-time)
16958 (let* ((org-with-time with-time)
16959 (org-time-stamp-rounding-minutes
16960 (if (equal org-with-time '(16))
16961 '(0 0)
16962 org-time-stamp-rounding-minutes))
16963 (org-dcst org-display-custom-times)
16964 (ct (org-current-time))
16965 (org-def (or org-overriding-default-time default-time ct))
16966 (org-defdecode (decode-time org-def))
16967 (cur-frame (selected-frame))
16968 (mouse-autoselect-window nil) ; Don't let the mouse jump
16969 (calendar-setup
16970 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16971 (calendar-move-hook nil)
16972 (calendar-view-diary-initially-flag nil)
16973 (calendar-view-holidays-initially-flag nil)
16974 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16975 ;; Rationalize `org-def' and `org-defdecode', if required.
16976 (when (< (nth 2 org-defdecode) org-extend-today-until)
16977 (setf (nth 2 org-defdecode) -1)
16978 (setf (nth 1 org-defdecode) 59)
16979 (setq org-def (apply #'encode-time org-defdecode))
16980 (setq org-defdecode (decode-time org-def)))
16981 (let* ((timestr (format-time-string
16982 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16983 org-def))
16984 (prompt (concat (if prompt (concat prompt " ") "")
16985 (format "Date+time [%s]: " timestr))))
16986 (cond
16987 (from-string (setq ans from-string))
16988 (org-read-date-popup-calendar
16989 (save-excursion
16990 (save-window-excursion
16991 (calendar)
16992 (when (eq calendar-setup 'calendar-only)
16993 (setq cal-frame
16994 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16995 (select-frame cal-frame))
16996 (org-eval-in-calendar '(setq cursor-type nil) t)
16997 (unwind-protect
16998 (progn
16999 (calendar-forward-day (- (time-to-days org-def)
17000 (calendar-absolute-from-gregorian
17001 (calendar-current-date))))
17002 (org-eval-in-calendar nil t)
17003 (let* ((old-map (current-local-map))
17004 (map (copy-keymap calendar-mode-map))
17005 (minibuffer-local-map
17006 (copy-keymap org-read-date-minibuffer-local-map)))
17007 (org-defkey map (kbd "RET") 'org-calendar-select)
17008 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17009 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17010 (unwind-protect
17011 (progn
17012 (use-local-map map)
17013 (setq org-read-date-inactive inactive)
17014 (add-hook 'post-command-hook 'org-read-date-display)
17015 (setq org-ans0
17016 (read-string prompt
17017 default-input
17018 'org-read-date-history
17019 nil))
17020 ;; org-ans0: from prompt
17021 ;; org-ans1: from mouse click
17022 ;; org-ans2: from calendar motion
17023 (setq ans
17024 (concat org-ans0 " " (or org-ans1 org-ans2))))
17025 (remove-hook 'post-command-hook 'org-read-date-display)
17026 (use-local-map old-map)
17027 (when org-read-date-overlay
17028 (delete-overlay org-read-date-overlay)
17029 (setq org-read-date-overlay nil)))))
17030 (bury-buffer "*Calendar*")
17031 (when cal-frame
17032 (delete-frame cal-frame)
17033 (select-frame-set-input-focus cur-frame))))))
17035 (t ; Naked prompt only
17036 (unwind-protect
17037 (setq ans (read-string prompt default-input
17038 'org-read-date-history timestr))
17039 (when org-read-date-overlay
17040 (delete-overlay org-read-date-overlay)
17041 (setq org-read-date-overlay nil))))))
17043 (setq final (org-read-date-analyze ans org-def org-defdecode))
17045 (when org-read-date-analyze-forced-year
17046 (message "Year was forced into %s"
17047 (if org-read-date-force-compatible-dates
17048 "compatible range (1970-2037)"
17049 "range representable on this machine"))
17050 (ding))
17052 ;; One round trip to get rid of 34th of August and stuff like that....
17053 (setq final (decode-time (apply 'encode-time final)))
17055 (setq org-read-date-final-answer ans)
17057 (if to-time
17058 (apply 'encode-time final)
17059 (if (and (boundp 'org-time-was-given) org-time-was-given)
17060 (format "%04d-%02d-%02d %02d:%02d"
17061 (nth 5 final) (nth 4 final) (nth 3 final)
17062 (nth 2 final) (nth 1 final))
17063 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17065 (defun org-read-date-display ()
17066 "Display the current date prompt interpretation in the minibuffer."
17067 (when org-read-date-display-live
17068 (when org-read-date-overlay
17069 (delete-overlay org-read-date-overlay))
17070 (when (minibufferp (current-buffer))
17071 (save-excursion
17072 (end-of-line 1)
17073 (while (not (equal (buffer-substring
17074 (max (point-min) (- (point) 4)) (point))
17075 " "))
17076 (insert " ")))
17077 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17078 " " (or org-ans1 org-ans2)))
17079 (org-end-time-was-given nil)
17080 (f (org-read-date-analyze ans org-def org-defdecode))
17081 (fmts (if org-dcst
17082 org-time-stamp-custom-formats
17083 org-time-stamp-formats))
17084 (fmt (if (or org-with-time
17085 (and (boundp 'org-time-was-given) org-time-was-given))
17086 (cdr fmts)
17087 (car fmts)))
17088 (txt (format-time-string fmt (apply 'encode-time f)))
17089 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17090 (txt (concat "=> " txt)))
17091 (when (and org-end-time-was-given
17092 (string-match org-plain-time-of-day-regexp txt))
17093 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17094 org-end-time-was-given
17095 (substring txt (match-end 0)))))
17096 (when org-read-date-analyze-futurep
17097 (setq txt (concat txt " (=>F)")))
17098 (setq org-read-date-overlay
17099 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17100 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17102 (defun org-read-date-analyze (ans def defdecode)
17103 "Analyze the combined answer of the date prompt."
17104 ;; FIXME: cleanup and comment
17105 ;; Pass `current-time' result to `decode-time' (instead of calling
17106 ;; without arguments) so that only `current-time' has to be
17107 ;; overriden in tests.
17108 (let ((org-def def)
17109 (org-defdecode defdecode)
17110 (nowdecode (decode-time (current-time)))
17111 delta deltan deltaw deltadef year month day
17112 hour minute second wday pm h2 m2 tl wday1
17113 iso-year iso-weekday iso-week iso-date futurep kill-year)
17114 (setq org-read-date-analyze-futurep nil
17115 org-read-date-analyze-forced-year nil)
17116 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17117 (setq ans "+0"))
17119 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17120 (setq ans (replace-match "" t t ans)
17121 deltan (car delta)
17122 deltaw (nth 1 delta)
17123 deltadef (nth 2 delta)))
17125 ;; Check if there is an iso week date in there. If yes, store the
17126 ;; info and postpone interpreting it until the rest of the parsing
17127 ;; is done.
17128 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17129 (setq iso-year (when (match-end 1)
17130 (org-small-year-to-year
17131 (string-to-number (match-string 1 ans))))
17132 iso-weekday (when (match-end 3)
17133 (string-to-number (match-string 3 ans)))
17134 iso-week (string-to-number (match-string 2 ans)))
17135 (setq ans (replace-match "" t t ans)))
17137 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17138 (when (string-match
17139 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17140 (setq year (if (match-end 2)
17141 (string-to-number (match-string 2 ans))
17142 (progn (setq kill-year t)
17143 (string-to-number (format-time-string "%Y"))))
17144 month (string-to-number (match-string 3 ans))
17145 day (string-to-number (match-string 4 ans)))
17146 (setq year (org-small-year-to-year year))
17147 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17148 t nil ans)))
17150 ;; Help matching dotted european dates
17151 (when (string-match
17152 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17153 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17154 (setq kill-year t)
17155 (string-to-number (format-time-string "%Y")))
17156 day (string-to-number (match-string 1 ans))
17157 month (string-to-number (match-string 2 ans))
17158 ans (replace-match (format "%04d-%02d-%02d" year month day)
17159 t nil ans)))
17161 ;; Help matching american dates, like 5/30 or 5/30/7
17162 (when (string-match
17163 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17164 (setq year (if (match-end 4)
17165 (string-to-number (match-string 4 ans))
17166 (progn (setq kill-year t)
17167 (string-to-number (format-time-string "%Y"))))
17168 month (string-to-number (match-string 1 ans))
17169 day (string-to-number (match-string 2 ans)))
17170 (setq year (org-small-year-to-year year))
17171 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17172 t nil ans)))
17173 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17174 ;; If there is a time with am/pm, and *no* time without it, we convert
17175 ;; so that matching will be successful.
17176 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17177 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17178 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17179 (setq hour (string-to-number (match-string 1 ans))
17180 minute (if (match-end 3)
17181 (string-to-number (match-string 3 ans))
17183 pm (equal ?p
17184 (string-to-char (downcase (match-string 4 ans)))))
17185 (if (and (= hour 12) (not pm))
17186 (setq hour 0)
17187 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17188 (setq ans (replace-match (format "%02d:%02d" hour minute)
17189 t t ans))))
17191 ;; Check if a time range is given as a duration
17192 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17193 (setq hour (string-to-number (match-string 1 ans))
17194 h2 (+ hour (string-to-number (match-string 3 ans)))
17195 minute (string-to-number (match-string 2 ans))
17196 m2 (+ minute (if (match-end 5) (string-to-number
17197 (match-string 5 ans))0)))
17198 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17199 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17200 t t ans)))
17202 ;; Check if there is a time range
17203 (when (boundp 'org-end-time-was-given)
17204 (setq org-time-was-given nil)
17205 (when (and (string-match org-plain-time-of-day-regexp ans)
17206 (match-end 8))
17207 (setq org-end-time-was-given (match-string 8 ans))
17208 (setq ans (concat (substring ans 0 (match-beginning 7))
17209 (substring ans (match-end 7))))))
17211 (setq tl (parse-time-string ans)
17212 day (or (nth 3 tl) (nth 3 org-defdecode))
17213 month
17214 (cond ((nth 4 tl))
17215 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17216 ;; Day was specified. Make sure DAY+MONTH
17217 ;; combination happens in the future.
17218 ((nth 3 tl)
17219 (setq futurep t)
17220 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17221 (nth 4 nowdecode)))
17222 (t (nth 4 org-defdecode)))
17223 year
17224 (cond ((and (not kill-year) (nth 5 tl)))
17225 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17226 ;; Month was guessed in the future and is at least
17227 ;; equal to NOWDECODE's. Fix year accordingly.
17228 (futurep
17229 (if (or (> month (nth 4 nowdecode))
17230 (>= day (nth 3 nowdecode)))
17231 (nth 5 nowdecode)
17232 (1+ (nth 5 nowdecode))))
17233 ;; Month was specified. Make sure MONTH+YEAR
17234 ;; combination happens in the future.
17235 ((nth 4 tl)
17236 (setq futurep t)
17237 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17238 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17239 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17240 (t (nth 5 nowdecode))))
17241 (t (nth 5 org-defdecode)))
17242 hour (or (nth 2 tl) (nth 2 org-defdecode))
17243 minute (or (nth 1 tl) (nth 1 org-defdecode))
17244 second (or (nth 0 tl) 0)
17245 wday (nth 6 tl))
17247 (when (and (eq org-read-date-prefer-future 'time)
17248 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17249 (equal day (nth 3 nowdecode))
17250 (equal month (nth 4 nowdecode))
17251 (equal year (nth 5 nowdecode))
17252 (nth 2 tl)
17253 (or (< (nth 2 tl) (nth 2 nowdecode))
17254 (and (= (nth 2 tl) (nth 2 nowdecode))
17255 (nth 1 tl)
17256 (< (nth 1 tl) (nth 1 nowdecode)))))
17257 (setq day (1+ day)
17258 futurep t))
17260 ;; Special date definitions below
17261 (cond
17262 (iso-week
17263 ;; There was an iso week
17264 (require 'cal-iso)
17265 (setq futurep nil)
17266 (setq year (or iso-year year)
17267 day (or iso-weekday wday 1)
17268 wday nil ; to make sure that the trigger below does not match
17269 iso-date (calendar-gregorian-from-absolute
17270 (calendar-iso-to-absolute
17271 (list iso-week day year))))
17272 ; FIXME: Should we also push ISO weeks into the future?
17273 ; (when (and org-read-date-prefer-future
17274 ; (not iso-year)
17275 ; (< (calendar-absolute-from-gregorian iso-date)
17276 ; (time-to-days (current-time))))
17277 ; (setq year (1+ year)
17278 ; iso-date (calendar-gregorian-from-absolute
17279 ; (calendar-iso-to-absolute
17280 ; (list iso-week day year)))))
17281 (setq month (car iso-date)
17282 year (nth 2 iso-date)
17283 day (nth 1 iso-date)))
17284 (deltan
17285 (setq futurep nil)
17286 (unless deltadef
17287 ;; Pass `current-time' result to `decode-time' (instead of
17288 ;; calling without arguments) so that only `current-time' has
17289 ;; to be overriden in tests.
17290 (let ((now (decode-time (current-time))))
17291 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17292 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17293 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17294 ((equal deltaw "m") (setq month (+ month deltan)))
17295 ((equal deltaw "y") (setq year (+ year deltan)))))
17296 ((and wday (not (nth 3 tl)))
17297 ;; Weekday was given, but no day, so pick that day in the week
17298 ;; on or after the derived date.
17299 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17300 (unless (equal wday wday1)
17301 (setq day (+ day (% (- wday wday1 -7) 7))))))
17302 (when (and (boundp 'org-time-was-given)
17303 (nth 2 tl))
17304 (setq org-time-was-given t))
17305 (when (< year 100) (setq year (+ 2000 year)))
17306 ;; Check of the date is representable
17307 (if org-read-date-force-compatible-dates
17308 (progn
17309 (when (< year 1970)
17310 (setq year 1970 org-read-date-analyze-forced-year t))
17311 (when (> year 2037)
17312 (setq year 2037 org-read-date-analyze-forced-year t)))
17313 (condition-case nil
17314 (ignore (encode-time second minute hour day month year))
17315 (error
17316 (setq year (nth 5 org-defdecode))
17317 (setq org-read-date-analyze-forced-year t))))
17318 (setq org-read-date-analyze-futurep futurep)
17319 (list second minute hour day month year)))
17321 (defvar parse-time-weekdays)
17322 (defun org-read-date-get-relative (s today default)
17323 "Check string S for special relative date string.
17324 TODAY and DEFAULT are internal times, for today and for a default.
17325 Return shift list (N what def-flag)
17326 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17327 N is the number of WHATs to shift.
17328 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17329 the DEFAULT date rather than TODAY."
17330 (require 'parse-time)
17331 (when (and
17332 (string-match
17333 (concat
17334 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17335 "\\([0-9]+\\)?"
17336 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17337 "\\([ \t]\\|$\\)") s)
17338 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17339 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17340 (string-to-char (substring (match-string 1 s) -1))
17341 ?+))
17342 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17343 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17344 (what (if (match-end 3) (match-string 3 s) "d"))
17345 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17346 (date (if rel default today))
17347 (wday (nth 6 (decode-time date)))
17348 delta)
17349 (if wday1
17350 (progn
17351 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17352 (when (= delta 0) (setq delta 7))
17353 (when (= dir ?-)
17354 (setq delta (- delta 7))
17355 (when (= delta 0) (setq delta -7)))
17356 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17357 (list delta "d" rel))
17358 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17360 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17361 "Turn a user-specified date into the internal representation.
17362 The internal representation needed by the calendar is (month day year).
17363 This is a wrapper to handle the brain-dead convention in calendar that
17364 user function argument order change dependent on argument order."
17365 (pcase calendar-date-style
17366 (`american (list arg1 arg2 arg3))
17367 (`european (list arg2 arg1 arg3))
17368 (`iso (list arg2 arg3 arg1))))
17370 (defun org-eval-in-calendar (form &optional keepdate)
17371 "Eval FORM in the calendar window and return to current window.
17372 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17373 (let ((sf (selected-frame))
17374 (sw (selected-window)))
17375 (select-window (get-buffer-window "*Calendar*" t))
17376 (eval form)
17377 (when (and (not keepdate) (calendar-cursor-to-date))
17378 (let* ((date (calendar-cursor-to-date))
17379 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17380 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17381 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17382 (select-window sw)
17383 (select-frame-set-input-focus sf)))
17385 (defun org-calendar-select ()
17386 "Return to `org-read-date' with the date currently selected.
17387 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17388 (interactive)
17389 (when (calendar-cursor-to-date)
17390 (let* ((date (calendar-cursor-to-date))
17391 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17392 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17393 (when (active-minibuffer-window) (exit-minibuffer))))
17395 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17396 "Insert a date stamp for the date given by the internal TIME.
17397 See `format-time-string' for the format of TIME.
17398 WITH-HM means use the stamp format that includes the time of the day.
17399 INACTIVE means use square brackets instead of angular ones, so that the
17400 stamp will not contribute to the agenda.
17401 PRE and POST are optional strings to be inserted before and after the
17402 stamp.
17403 The command returns the inserted time stamp."
17404 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17405 stamp)
17406 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17407 (insert-before-markers (or pre ""))
17408 (when (listp extra)
17409 (setq extra (car extra))
17410 (if (and (stringp extra)
17411 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17412 (setq extra (format "-%02d:%02d"
17413 (string-to-number (match-string 1 extra))
17414 (string-to-number (match-string 2 extra))))
17415 (setq extra nil)))
17416 (when extra
17417 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17418 (insert-before-markers (setq stamp (format-time-string fmt time)))
17419 (insert-before-markers (or post ""))
17420 (setq org-last-inserted-timestamp stamp)))
17422 (defun org-toggle-time-stamp-overlays ()
17423 "Toggle the use of custom time stamp formats."
17424 (interactive)
17425 (setq org-display-custom-times (not org-display-custom-times))
17426 (unless org-display-custom-times
17427 (let ((p (point-min)) (bmp (buffer-modified-p)))
17428 (while (setq p (next-single-property-change p 'display))
17429 (when (and (get-text-property p 'display)
17430 (eq (get-text-property p 'face) 'org-date))
17431 (remove-text-properties
17432 p (setq p (next-single-property-change p 'display))
17433 '(display t))))
17434 (set-buffer-modified-p bmp)))
17435 (org-restart-font-lock)
17436 (setq org-table-may-need-update t)
17437 (if org-display-custom-times
17438 (message "Time stamps are overlaid with custom format")
17439 (message "Time stamp overlays removed")))
17441 (defun org-display-custom-time (beg end)
17442 "Overlay modified time stamp format over timestamp between BEG and END."
17443 (let* ((ts (buffer-substring beg end))
17444 t1 w1 with-hm tf time str w2 (off 0))
17445 (save-match-data
17446 (setq t1 (org-parse-time-string ts t))
17447 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17448 (setq off (- (match-end 0) (match-beginning 0)))))
17449 (setq end (- end off))
17450 (setq w1 (- end beg)
17451 with-hm (and (nth 1 t1) (nth 2 t1))
17452 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17453 time (org-fix-decoded-time t1)
17454 str (org-add-props
17455 (format-time-string
17456 (substring tf 1 -1) (apply 'encode-time time))
17457 nil 'mouse-face 'highlight)
17458 w2 (length str))
17459 (unless (= w2 w1)
17460 (add-text-properties (1+ beg) (+ 2 beg)
17461 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17462 (put-text-property beg end 'display str)))
17464 (defun org-fix-decoded-time (time)
17465 "Set 0 instead of nil for the first 6 elements of time.
17466 Don't touch the rest."
17467 (let ((n 0))
17468 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17470 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17471 "Difference between TIMESTAMP-STRING and now in days.
17472 If SECONDS is non-nil, return the difference in seconds."
17473 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17474 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17475 (funcall fdiff (current-time)))))
17477 (defun org-deadline-close-p (timestamp-string &optional ndays)
17478 "Is the time in TIMESTAMP-STRING close to the current date?"
17479 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17480 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17481 (not (org-entry-is-done-p))))
17483 (defun org-get-wdays (ts &optional delay zero-delay)
17484 "Get the deadline lead time appropriate for timestring TS.
17485 When DELAY is non-nil, get the delay time for scheduled items
17486 instead of the deadline lead time. When ZERO-DELAY is non-nil
17487 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17488 don't try to find the delay cookie in the scheduled timestamp."
17489 (let ((tv (if delay org-scheduled-delay-days
17490 org-deadline-warning-days)))
17491 (cond
17492 ((or (and delay (< tv 0))
17493 (and delay zero-delay (<= tv 0))
17494 (and (not delay) (<= tv 0)))
17495 ;; Enforce this value no matter what
17496 (- tv))
17497 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17498 ;; lead time is specified.
17499 (floor (* (string-to-number (match-string 1 ts))
17500 (cdr (assoc (match-string 2 ts)
17501 '(("d" . 1) ("w" . 7)
17502 ("m" . 30.4) ("y" . 365.25)
17503 ("h" . 0.041667)))))))
17504 ;; go for the default.
17505 (t tv))))
17507 (defun org-calendar-select-mouse (ev)
17508 "Return to `org-read-date' with the date currently selected.
17509 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17510 (interactive "e")
17511 (mouse-set-point ev)
17512 (when (calendar-cursor-to-date)
17513 (let* ((date (calendar-cursor-to-date))
17514 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17515 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17516 (when (active-minibuffer-window) (exit-minibuffer))))
17518 (defun org-check-deadlines (ndays)
17519 "Check if there are any deadlines due or past due.
17520 A deadline is considered due if it happens within `org-deadline-warning-days'
17521 days from today's date. If the deadline appears in an entry marked DONE,
17522 it is not shown. A numeric prefix argument NDAYS can be used to test that
17523 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17524 are shown."
17525 (interactive "P")
17526 (let* ((org-warn-days
17527 (cond
17528 ((equal ndays '(4)) 100000)
17529 (ndays (prefix-numeric-value ndays))
17530 (t (abs org-deadline-warning-days))))
17531 (case-fold-search nil)
17532 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17533 (callback
17534 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17535 (message "%d deadlines past-due or due within %d days"
17536 (org-occur regexp nil callback)
17537 org-warn-days)))
17539 (defsubst org-re-timestamp (type)
17540 "Return a regexp for timestamp TYPE.
17541 Allowed values for TYPE are:
17543 all: all timestamps
17544 active: only active timestamps (<...>)
17545 inactive: only inactive timestamps ([...])
17546 scheduled: only scheduled timestamps
17547 deadline: only deadline timestamps
17548 closed: only closed time-stamps
17550 When TYPE is nil, fall back on returning a regexp that matches
17551 both scheduled and deadline timestamps."
17552 (cl-case type
17553 (all org-ts-regexp-both)
17554 (active org-ts-regexp)
17555 (inactive org-ts-regexp-inactive)
17556 (scheduled org-scheduled-time-regexp)
17557 (deadline org-deadline-time-regexp)
17558 (closed org-closed-time-regexp)
17559 (otherwise
17560 (concat "\\<"
17561 (regexp-opt (list org-deadline-string org-scheduled-string))
17562 " *<\\([^>]+\\)>"))))
17564 (defun org-check-before-date (d)
17565 "Check if there are deadlines or scheduled entries before date D."
17566 (interactive (list (org-read-date)))
17567 (let* ((case-fold-search nil)
17568 (regexp (org-re-timestamp org-ts-type))
17569 (ts-type org-ts-type)
17570 (callback
17571 (lambda ()
17572 (let ((match (match-string 1)))
17573 (and (if (memq ts-type '(active inactive all))
17574 (eq (org-element-type (save-excursion
17575 (backward-char)
17576 (org-element-context)))
17577 'timestamp)
17578 (org-at-planning-p))
17579 (time-less-p
17580 (org-time-string-to-time match)
17581 (org-time-string-to-time d)))))))
17582 (message "%d entries before %s"
17583 (org-occur regexp nil callback)
17584 d)))
17586 (defun org-check-after-date (d)
17587 "Check if there are deadlines or scheduled entries after date D."
17588 (interactive (list (org-read-date)))
17589 (let* ((case-fold-search nil)
17590 (regexp (org-re-timestamp org-ts-type))
17591 (ts-type org-ts-type)
17592 (callback
17593 (lambda ()
17594 (let ((match (match-string 1)))
17595 (and (if (memq ts-type '(active inactive all))
17596 (eq (org-element-type (save-excursion
17597 (backward-char)
17598 (org-element-context)))
17599 'timestamp)
17600 (org-at-planning-p))
17601 (not (time-less-p
17602 (org-time-string-to-time match)
17603 (org-time-string-to-time d))))))))
17604 (message "%d entries after %s"
17605 (org-occur regexp nil callback)
17606 d)))
17608 (defun org-check-dates-range (start-date end-date)
17609 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17610 (interactive (list (org-read-date nil nil nil "Range starts")
17611 (org-read-date nil nil nil "Range end")))
17612 (let ((case-fold-search nil)
17613 (regexp (org-re-timestamp org-ts-type))
17614 (callback
17615 (let ((type org-ts-type))
17616 (lambda ()
17617 (let ((match (match-string 1)))
17618 (and
17619 (if (memq type '(active inactive all))
17620 (eq (org-element-type (save-excursion
17621 (backward-char)
17622 (org-element-context)))
17623 'timestamp)
17624 (org-at-planning-p))
17625 (not (time-less-p
17626 (org-time-string-to-time match)
17627 (org-time-string-to-time start-date)))
17628 (time-less-p
17629 (org-time-string-to-time match)
17630 (org-time-string-to-time end-date))))))))
17631 (message "%d entries between %s and %s"
17632 (org-occur regexp nil callback) start-date end-date)))
17634 (defun org-evaluate-time-range (&optional to-buffer)
17635 "Evaluate a time range by computing the difference between start and end.
17636 Normally the result is just printed in the echo area, but with prefix arg
17637 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17638 If the time range is actually in a table, the result is inserted into the
17639 next column.
17640 For time difference computation, a year is assumed to be exactly 365
17641 days in order to avoid rounding problems."
17642 (interactive "P")
17644 (org-clock-update-time-maybe)
17645 (save-excursion
17646 (unless (org-at-date-range-p t)
17647 (goto-char (point-at-bol))
17648 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17649 (unless (org-at-date-range-p t)
17650 (user-error "Not at a time-stamp range, and none found in current line")))
17651 (let* ((ts1 (match-string 1))
17652 (ts2 (match-string 2))
17653 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17654 (match-end (match-end 0))
17655 (time1 (org-time-string-to-time ts1))
17656 (time2 (org-time-string-to-time ts2))
17657 (t1 (float-time time1))
17658 (t2 (float-time time2))
17659 (diff (abs (- t2 t1)))
17660 (negative (< (- t2 t1) 0))
17661 ;; (ys (floor (* 365 24 60 60)))
17662 (ds (* 24 60 60))
17663 (hs (* 60 60))
17664 (fy "%dy %dd %02d:%02d")
17665 (fy1 "%dy %dd")
17666 (fd "%dd %02d:%02d")
17667 (fd1 "%dd")
17668 (fh "%02d:%02d")
17669 y d h m align)
17670 (if havetime
17671 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17673 d (floor (/ diff ds)) diff (mod diff ds)
17674 h (floor (/ diff hs)) diff (mod diff hs)
17675 m (floor (/ diff 60)))
17676 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17678 d (floor (+ (/ diff ds) 0.5))
17679 h 0 m 0))
17680 (if (not to-buffer)
17681 (message "%s" (org-make-tdiff-string y d h m))
17682 (if (org-at-table-p)
17683 (progn
17684 (goto-char match-end)
17685 (setq align t)
17686 (and (looking-at " *|") (goto-char (match-end 0))))
17687 (goto-char match-end))
17688 (when (looking-at
17689 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17690 (replace-match ""))
17691 (when negative (insert " -"))
17692 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17693 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17694 (insert " " (format fh h m))))
17695 (when align (org-table-align))
17696 (message "Time difference inserted")))))
17698 (defun org-make-tdiff-string (y d h m)
17699 (let ((fmt "")
17700 (l nil))
17701 (when (> y 0)
17702 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17703 (push y l))
17704 (when (> d 0)
17705 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17706 (push d l))
17707 (when (> h 0)
17708 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17709 (push h l))
17710 (when (> m 0)
17711 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17712 (push m l))
17713 (apply 'format fmt (nreverse l))))
17715 (defun org-time-string-to-time (s &optional buffer pos)
17716 "Convert a timestamp string into internal time."
17717 (condition-case errdata
17718 (apply 'encode-time (org-parse-time-string s))
17719 (error (error "Bad timestamp `%s'%s\nError was: %s"
17720 s (if (not (and buffer pos))
17722 (format-message " at %d in buffer `%s'" pos buffer))
17723 (cdr errdata)))))
17725 (defun org-time-string-to-seconds (s)
17726 "Convert a timestamp string to a number of seconds."
17727 (float-time (org-time-string-to-time s)))
17729 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17731 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17732 "Convert time stamp S to an absolute day number.
17734 If DAYNR in non-nil, and there is a specifier for a cyclic time
17735 stamp, get the closest date to DAYNR. If PREFER is
17736 `past' (respectively `future') return a date past (respectively
17737 after) or equal to DAYNR.
17739 POS is the location of time stamp S, as a buffer position in
17740 BUFFER.
17742 Diary sexp timestamps are matched against DAYNR, when non-nil.
17743 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17744 signalled."
17745 (cond
17746 ((string-match "\\`%%\\((.*)\\)" s)
17747 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17748 ;; only able to match individual dates. If it fails, raise an
17749 ;; error.
17750 (if (and daynr
17751 (org-diary-sexp-entry
17752 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17753 daynr
17754 (signal 'org-diary-sexp-no-match (list s))))
17755 (daynr (org-closest-date s daynr prefer))
17756 (t (time-to-days
17757 (condition-case errdata
17758 (apply #'encode-time (org-parse-time-string s))
17759 (error (error "Bad timestamp `%s'%s\nError was: %s"
17761 (if (not (and buffer pos)) ""
17762 (format-message " at %d in buffer `%s'" pos buffer))
17763 (cdr errdata))))))))
17765 (defun org-days-to-iso-week (days)
17766 "Return the iso week number."
17767 (require 'cal-iso)
17768 (car (calendar-iso-from-absolute days)))
17770 (defun org-small-year-to-year (year)
17771 "Convert 2-digit years into 4-digit years.
17772 YEAR is expanded into one of the 30 next years, if possible, or
17773 into a past one. Any year larger than 99 is returned unchanged."
17774 (if (>= year 100) year
17775 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17776 (century (/ current 100))
17777 (offset (- year (% current 100))))
17778 (cond ((> offset 30) (+ (* (1- century) 100) year))
17779 ((> offset -70) (+ (* century 100) year))
17780 (t (+ (* (1+ century) 100) year))))))
17782 (defun org-time-from-absolute (d)
17783 "Return the time corresponding to date D.
17784 D may be an absolute day number, or a calendar-type list (month day year)."
17785 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17786 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17788 (defvar org-agenda-current-date)
17789 (defun org-calendar-holiday ()
17790 "List of holidays, for Diary display in Org mode."
17791 (require 'holidays)
17792 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17793 (and hl (mapconcat #'identity hl "; "))))
17795 (defun org-diary-sexp-entry (sexp entry d)
17796 "Process a SEXP diary ENTRY for date D."
17797 (require 'diary-lib)
17798 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17799 ;; dynamically.
17800 (let* ((sexp `(let ((entry ,entry)
17801 (date ',d))
17802 ,(car (read-from-string sexp))))
17803 (result (if calendar-debug-sexp (eval sexp)
17804 (condition-case nil
17805 (eval sexp)
17806 (error
17807 (beep)
17808 (message "Bad sexp at line %d in %s: %s"
17809 (org-current-line)
17810 (buffer-file-name) sexp)
17811 (sleep-for 2))))))
17812 (cond ((stringp result) (split-string result "; "))
17813 ((and (consp result)
17814 (not (consp (cdr result)))
17815 (stringp (cdr result))) (cdr result))
17816 ((and (consp result)
17817 (stringp (car result))) result)
17818 (result entry))))
17820 (defun org-diary-to-ical-string (frombuf)
17821 "Get iCalendar entries from diary entries in buffer FROMBUF.
17822 This uses the icalendar.el library."
17823 (let* ((tmpdir temporary-file-directory)
17824 (tmpfile (make-temp-name
17825 (expand-file-name "orgics" tmpdir)))
17826 buf rtn b e)
17827 (with-current-buffer frombuf
17828 (icalendar-export-region (point-min) (point-max) tmpfile)
17829 (setq buf (find-buffer-visiting tmpfile))
17830 (set-buffer buf)
17831 (goto-char (point-min))
17832 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17833 (setq b (match-beginning 0)))
17834 (goto-char (point-max))
17835 (when (re-search-backward "^END:VEVENT" nil t)
17836 (setq e (match-end 0)))
17837 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17838 (kill-buffer buf)
17839 (delete-file tmpfile)
17840 rtn))
17842 (defun org-closest-date (start current prefer)
17843 "Return closest date to CURRENT starting from START.
17845 CURRENT and START are both time stamps.
17847 When PREFER is `past', return a date that is either CURRENT or
17848 past. When PREFER is `future', return a date that is either
17849 CURRENT or future.
17851 Only time stamps with a repeater are modified. Any other time
17852 stamp stay unchanged. In any case, return value is an absolute
17853 day number."
17854 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17855 ;; No repeater. Do not shift time stamp.
17856 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17857 (let ((value (string-to-number (match-string 1 start)))
17858 (type (match-string 2 start)))
17859 (if (= 0 value)
17860 ;; Repeater with a 0-value is considered as void.
17861 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17862 (let* ((base (org-date-to-gregorian start))
17863 (target (org-date-to-gregorian current))
17864 (sday (calendar-absolute-from-gregorian base))
17865 (cday (calendar-absolute-from-gregorian target))
17866 n1 n2)
17867 ;; If START is already past CURRENT, just return START.
17868 (if (<= cday sday) sday
17869 ;; Compute closest date before (N1) and closest date past
17870 ;; (N2) CURRENT.
17871 (pcase type
17872 ("h"
17873 (let ((missing-hours
17874 (mod (+ (- (* 24 (- cday sday))
17875 (nth 2 (org-parse-time-string start)))
17876 org-extend-today-until)
17877 value)))
17878 (setf n1 (if (= missing-hours 0) cday
17879 (- cday (1+ (/ missing-hours 24)))))
17880 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17881 ((or "d" "w")
17882 (let ((value (if (equal type "w") (* 7 value) value)))
17883 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17884 (setf n2 (+ n1 value))))
17885 ("m"
17886 (let* ((add-months
17887 (lambda (d n)
17888 ;; Add N months to gregorian date D, i.e.,
17889 ;; a list (MONTH DAY YEAR). Return a valid
17890 ;; gregorian date.
17891 (let ((m (+ (nth 0 d) n)))
17892 (list (mod m 12)
17893 (nth 1 d)
17894 (+ (/ m 12) (nth 2 d))))))
17895 (months ; Complete months to TARGET.
17896 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17897 (- (nth 0 target) (nth 0 base))
17898 ;; If START's day is greater than
17899 ;; TARGET's, remove incomplete month.
17900 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17901 value)
17902 value))
17903 (before (funcall add-months base months)))
17904 (setf n1 (calendar-absolute-from-gregorian before))
17905 (setf n2
17906 (calendar-absolute-from-gregorian
17907 (funcall add-months before value)))))
17909 (let* ((d (nth 1 base))
17910 (m (nth 0 base))
17911 (y (nth 2 base))
17912 (years ; Complete years to TARGET.
17913 (* (/ (- (nth 2 target)
17915 ;; If START's month and day are
17916 ;; greater than TARGET's, remove
17917 ;; incomplete year.
17918 (if (or (> (nth 0 target) m)
17919 (and (= (nth 0 target) m)
17920 (> (nth 1 target) d)))
17923 value)
17924 value))
17925 (before (list m d (+ y years))))
17926 (setf n1 (calendar-absolute-from-gregorian before))
17927 (setf n2 (calendar-absolute-from-gregorian
17928 (list m d (+ (nth 2 before) value)))))))
17929 ;; Handle PREFER parameter, if any.
17930 (cond
17931 ((eq prefer 'past) (if (= cday n2) n2 n1))
17932 ((eq prefer 'future) (if (= cday n1) n1 n2))
17933 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17935 (defun org-date-to-gregorian (d)
17936 "Turn any specification of date D into a Gregorian date for the calendar."
17937 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17938 ((and (listp d) (= (length d) 3)) d)
17939 ((stringp d)
17940 (let ((d (org-parse-time-string d)))
17941 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17942 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17944 (defun org-parse-time-string (s &optional nodefault zone)
17945 "Parse the standard Org time string.
17947 This should be a lot faster than the normal `parse-time-string'.
17949 If time is not given, defaults to 0:00. However, with optional
17950 NODEFAULT, hour and minute fields will be nil if not given.
17952 The optional ZONE is omitted or nil for Emacs local time, t for
17953 Universal Time, ‘wall’ for system wall clock time, or a string as
17954 in the TZ environment variable."
17955 (cond ((string-match org-ts-regexp0 s)
17956 (list 0
17957 (when (or (match-beginning 8) (not nodefault))
17958 (string-to-number (or (match-string 8 s) "0")))
17959 (when (or (match-beginning 7) (not nodefault))
17960 (string-to-number (or (match-string 7 s) "0")))
17961 (string-to-number (match-string 4 s))
17962 (string-to-number (match-string 3 s))
17963 (string-to-number (match-string 2 s))
17964 nil nil zone))
17965 ((string-match "^<[^>]+>$" s)
17966 ;; FIXME: `decode-time' needs to be called with ZONE as its
17967 ;; second argument. However, this requires at least Emacs
17968 ;; 25.1. We can do it when we switch to this version as our
17969 ;; minimal requirement.
17970 (decode-time (seconds-to-time (org-matcher-time s))))
17971 (t (error "Not a standard Org time string: %s" s))))
17973 (defun org-timestamp-up (&optional arg)
17974 "Increase the date item at the cursor by one.
17975 If the cursor is on the year, change the year. If it is on the month,
17976 the day or the time, change that.
17977 With prefix ARG, change by that many units."
17978 (interactive "p")
17979 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17981 (defun org-timestamp-down (&optional arg)
17982 "Decrease the date item at the cursor by one.
17983 If the cursor is on the year, change the year. If it is on the month,
17984 the day or the time, change that.
17985 With prefix ARG, change by that many units."
17986 (interactive "p")
17987 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17989 (defun org-timestamp-up-day (&optional arg)
17990 "Increase the date in the time stamp by one day.
17991 With prefix ARG, change that many days."
17992 (interactive "p")
17993 (if (and (not (org-at-timestamp-p t))
17994 (org-at-heading-p))
17995 (org-todo 'up)
17996 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17998 (defun org-timestamp-down-day (&optional arg)
17999 "Decrease the date in the time stamp by one day.
18000 With prefix ARG, change that many days."
18001 (interactive "p")
18002 (if (and (not (org-at-timestamp-p t))
18003 (org-at-heading-p))
18004 (org-todo 'down)
18005 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18007 (defun org-at-timestamp-p (&optional inactive-ok)
18008 "Non-nil if point is inside a timestamp.
18010 When optional argument INACTIVE-OK is non-nil, also consider
18011 inactive timestamps.
18013 When this function returns a non-nil value, match data is set
18014 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18015 INACTIVE-OK."
18016 (interactive)
18017 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18018 (pos (point))
18019 (ans (or (looking-at tsr)
18020 (save-excursion
18021 (skip-chars-backward "^[<\n\r\t")
18022 (when (> (point) (point-min)) (backward-char 1))
18023 (and (looking-at tsr)
18024 (> (- (match-end 0) pos) -1))))))
18025 (and ans
18026 (boundp 'org-ts-what)
18027 (setq org-ts-what
18028 (cond
18029 ((= pos (match-beginning 0)) 'bracket)
18030 ;; Point is considered to be "on the bracket" whether
18031 ;; it's really on it or right after it.
18032 ((= pos (1- (match-end 0))) 'bracket)
18033 ((= pos (match-end 0)) 'after)
18034 ((org-pos-in-match-range pos 2) 'year)
18035 ((org-pos-in-match-range pos 3) 'month)
18036 ((org-pos-in-match-range pos 7) 'hour)
18037 ((org-pos-in-match-range pos 8) 'minute)
18038 ((or (org-pos-in-match-range pos 4)
18039 (org-pos-in-match-range pos 5)) 'day)
18040 ((and (> pos (or (match-end 8) (match-end 5)))
18041 (< pos (match-end 0)))
18042 (- pos (or (match-end 8) (match-end 5))))
18043 (t 'day))))
18044 ans))
18046 (defun org-toggle-timestamp-type ()
18047 "Toggle the type (<active> or [inactive]) of a time stamp."
18048 (interactive)
18049 (when (org-at-timestamp-p t)
18050 (let ((beg (match-beginning 0)) (end (match-end 0))
18051 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18052 (save-excursion
18053 (goto-char beg)
18054 (while (re-search-forward "[][<>]" end t)
18055 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18056 t t)))
18057 (message "Timestamp is now %sactive"
18058 (if (equal (char-after beg) ?<) "" "in")))))
18060 (defun org-at-clock-log-p nil
18061 "Is the cursor on the clock log line?"
18062 (save-excursion
18063 (beginning-of-line)
18064 (looking-at org-clock-line-re)))
18066 (defvar org-clock-history) ; defined in org-clock.el
18067 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18068 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18069 "Change the date in the time stamp at point.
18070 The date will be changed by N times WHAT. WHAT can be `day', `month',
18071 `year', `minute', `second'. If WHAT is not given, the cursor position
18072 in the timestamp determines what will be changed.
18073 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18074 (let ((origin (point)) origin-cat
18075 with-hm inactive
18076 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18077 org-ts-what
18078 extra rem
18079 ts time time0 fixnext clrgx)
18080 (unless (org-at-timestamp-p t)
18081 (user-error "Not at a timestamp"))
18082 (if (and (not what) (eq org-ts-what 'bracket))
18083 (org-toggle-timestamp-type)
18084 ;; Point isn't on brackets. Remember the part of the time-stamp
18085 ;; the point was in. Indeed, size of time-stamps may change,
18086 ;; but point must be kept in the same category nonetheless.
18087 (setq origin-cat org-ts-what)
18088 (when (and (not what) (not (eq org-ts-what 'day))
18089 org-display-custom-times
18090 (get-text-property (point) 'display)
18091 (not (get-text-property (1- (point)) 'display)))
18092 (setq org-ts-what 'day))
18093 (setq org-ts-what (or what org-ts-what)
18094 inactive (= (char-after (match-beginning 0)) ?\[)
18095 ts (match-string 0))
18096 (replace-match "")
18097 (when (string-match
18098 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18100 (setq extra (match-string 1 ts))
18101 (when suppress-tmp-delay
18102 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18103 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18104 (setq with-hm t))
18105 (setq time0 (org-parse-time-string ts))
18106 (when (and updown
18107 (eq org-ts-what 'minute)
18108 (not current-prefix-arg))
18109 ;; This looks like s-up and s-down. Change by one rounding step.
18110 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18111 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18112 (setcar (cdr time0) (+ (nth 1 time0)
18113 (if (> n 0) (- rem) (- dm rem))))))
18114 (setq time
18115 (apply #'encode-time
18116 (or (car time0) 0)
18117 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18118 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18119 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18120 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18121 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18122 (nthcdr 6 time0)))
18123 (when (and (member org-ts-what '(hour minute))
18124 extra
18125 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18126 (setq extra (org-modify-ts-extra
18127 extra
18128 (if (eq org-ts-what 'hour) 2 5)
18129 n dm)))
18130 (when (integerp org-ts-what)
18131 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18132 (when (eq what 'calendar)
18133 (let ((cal-date (org-get-date-from-calendar)))
18134 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18135 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18136 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18137 (setcar time0 (or (car time0) 0))
18138 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18139 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18140 (setq time (apply 'encode-time time0))))
18141 ;; Insert the new time-stamp, and ensure point stays in the same
18142 ;; category as before (i.e. not after the last position in that
18143 ;; category).
18144 (let ((pos (point)))
18145 ;; Stay before inserted string. `save-excursion' is of no use.
18146 (setq org-last-changed-timestamp
18147 (org-insert-time-stamp time with-hm inactive nil nil extra))
18148 (goto-char pos))
18149 (save-match-data
18150 (looking-at org-ts-regexp3)
18151 (goto-char
18152 (pcase origin-cat
18153 ;; `day' category ends before `hour' if any, or at the end
18154 ;; of the day name.
18155 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18156 (`hour (min (match-end 7) origin))
18157 (`minute (min (1- (match-end 8)) origin))
18158 ((pred integerp) (min (1- (match-end 0)) origin))
18159 ;; Point was right after the time-stamp. However, the
18160 ;; time-stamp length might have changed, so refer to
18161 ;; (match-end 0) instead.
18162 (`after (match-end 0))
18163 ;; `year' and `month' have both fixed size: point couldn't
18164 ;; have moved into another part.
18165 (_ origin))))
18166 ;; Update clock if on a CLOCK line.
18167 (org-clock-update-time-maybe)
18168 ;; Maybe adjust the closest clock in `org-clock-history'
18169 (when org-clock-adjust-closest
18170 (if (not (and (org-at-clock-log-p)
18171 (< 1 (length (delq nil (mapcar 'marker-position
18172 org-clock-history))))))
18173 (message "No clock to adjust")
18174 (cond ((save-excursion ; fix previous clock?
18175 (re-search-backward org-ts-regexp0 nil t)
18176 (looking-back (concat org-clock-string " \\[")
18177 (line-beginning-position)))
18178 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18179 ((save-excursion ; fix next clock?
18180 (re-search-backward org-ts-regexp0 nil t)
18181 (looking-at (concat org-ts-regexp0 "\\] =>")))
18182 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18183 (save-window-excursion
18184 ;; Find closest clock to point, adjust the previous/next one in history
18185 (let* ((p (save-excursion (org-back-to-heading t)))
18186 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18187 (clfixnth
18188 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18189 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18190 (if (not clfixpos)
18191 (message "No clock to adjust")
18192 (save-excursion
18193 (org-goto-marker-or-bmk clfixpos)
18194 (org-show-subtree)
18195 (when (re-search-forward clrgx nil t)
18196 (goto-char (match-beginning 1))
18197 (let (org-clock-adjust-closest)
18198 (org-timestamp-change n org-ts-what updown))
18199 (message "Clock adjusted in %s for heading: %s"
18200 (file-name-nondirectory (buffer-file-name))
18201 (org-get-heading t t)))))))))
18202 ;; Try to recenter the calendar window, if any.
18203 (when (and org-calendar-follow-timestamp-change
18204 (get-buffer-window "*Calendar*" t)
18205 (memq org-ts-what '(day month year)))
18206 (org-recenter-calendar (time-to-days time))))))
18208 (defun org-modify-ts-extra (s pos n dm)
18209 "Change the different parts of the lead-time and repeat fields in timestamp."
18210 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18211 ng h m new rem)
18212 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18213 (cond
18214 ((or (org-pos-in-match-range pos 2)
18215 (org-pos-in-match-range pos 3))
18216 (setq m (string-to-number (match-string 3 s))
18217 h (string-to-number (match-string 2 s)))
18218 (if (org-pos-in-match-range pos 2)
18219 (setq h (+ h n))
18220 (setq n (* dm (with-no-warnings (signum n))))
18221 (unless (= 0 (setq rem (% m dm)))
18222 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18223 (setq m (+ m n)))
18224 (when (< m 0) (setq m (+ m 60) h (1- h)))
18225 (when (> m 59) (setq m (- m 60) h (1+ h)))
18226 (setq h (mod h 24))
18227 (setq ng 1 new (format "-%02d:%02d" h m)))
18228 ((org-pos-in-match-range pos 6)
18229 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18230 ((org-pos-in-match-range pos 5)
18231 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18233 ((org-pos-in-match-range pos 9)
18234 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18235 ((org-pos-in-match-range pos 8)
18236 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18238 (when ng
18239 (setq s (concat
18240 (substring s 0 (match-beginning ng))
18242 (substring s (match-end ng))))))
18245 (defun org-recenter-calendar (d)
18246 "If the calendar is visible, recenter it to date D."
18247 (let ((cwin (get-buffer-window "*Calendar*" t)))
18248 (when cwin
18249 (let ((calendar-move-hook nil))
18250 (with-selected-window cwin
18251 (calendar-goto-date
18252 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18254 (defun org-goto-calendar (&optional arg)
18255 "Go to the Emacs calendar at the current date.
18256 If there is a time stamp in the current line, go to that date.
18257 A prefix ARG can be used to force the current date."
18258 (interactive "P")
18259 (let ((tsr org-ts-regexp) diff
18260 (calendar-move-hook nil)
18261 (calendar-view-holidays-initially-flag nil)
18262 (calendar-view-diary-initially-flag nil))
18263 (when (or (org-at-timestamp-p)
18264 (save-excursion
18265 (beginning-of-line 1)
18266 (looking-at (concat ".*" tsr))))
18267 (let ((d1 (time-to-days (current-time)))
18268 (d2 (time-to-days
18269 (org-time-string-to-time (match-string 1)))))
18270 (setq diff (- d2 d1))))
18271 (calendar)
18272 (calendar-goto-today)
18273 (when (and diff (not arg)) (calendar-forward-day diff))))
18275 (defun org-get-date-from-calendar ()
18276 "Return a list (month day year) of date at point in calendar."
18277 (with-current-buffer "*Calendar*"
18278 (save-match-data
18279 (calendar-cursor-to-date))))
18281 (defun org-date-from-calendar ()
18282 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18283 If there is already a time stamp at the cursor position, update it."
18284 (interactive)
18285 (if (org-at-timestamp-p t)
18286 (org-timestamp-change 0 'calendar)
18287 (let ((cal-date (org-get-date-from-calendar)))
18288 (org-insert-time-stamp
18289 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18291 (defcustom org-effort-durations
18292 `(("min" . 1)
18293 ("h" . 60)
18294 ("d" . ,(* 60 8))
18295 ("w" . ,(* 60 8 5))
18296 ("m" . ,(* 60 8 5 4))
18297 ("y" . ,(* 60 8 5 40)))
18298 "Conversion factor to minutes for an effort modifier.
18300 Each entry has the form (MODIFIER . MINUTES).
18302 In an effort string, a number followed by MODIFIER is multiplied
18303 by the specified number of MINUTES to obtain an effort in
18304 minutes.
18306 For example, if the value of this variable is ((\"hours\" . 60)), then an
18307 effort string \"2hours\" is equivalent to 120 minutes."
18308 :group 'org-agenda
18309 :version "26.1"
18310 :package-version '(Org . "8.3")
18311 :type '(alist :key-type (string :tag "Modifier")
18312 :value-type (number :tag "Minutes")))
18314 (defun org-minutes-to-clocksum-string (m)
18315 "Format number of minutes as a clocksum string.
18316 The format is determined by `org-time-clocksum-format',
18317 `org-time-clocksum-use-fractional' and
18318 `org-time-clocksum-fractional-format' and
18319 `org-time-clocksum-use-effort-durations'."
18320 (let ((clocksum "")
18321 (m (round m)) ; Don't allow fractions of minutes
18322 h d w mo y fmt n)
18323 (setq h (if org-time-clocksum-use-effort-durations
18324 (cdr (assoc "h" org-effort-durations)) 60)
18325 d (if org-time-clocksum-use-effort-durations
18326 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18327 w (if org-time-clocksum-use-effort-durations
18328 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18329 mo (if org-time-clocksum-use-effort-durations
18330 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18331 y (if org-time-clocksum-use-effort-durations
18332 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18333 ;; fractional format
18334 (if org-time-clocksum-use-fractional
18335 (cond
18336 ;; single format string
18337 ((stringp org-time-clocksum-fractional-format)
18338 (format org-time-clocksum-fractional-format (/ m (float h))))
18339 ;; choice of fractional formats for different time units
18340 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18341 (> (/ (truncate m) (* y d h)) 0))
18342 (format fmt (/ m (* y d (float h)))))
18343 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18344 (> (/ (truncate m) (* mo d h)) 0))
18345 (format fmt (/ m (* mo d (float h)))))
18346 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18347 (> (/ (truncate m) (* w d h)) 0))
18348 (format fmt (/ m (* w d (float h)))))
18349 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18350 (> (/ (truncate m) (* d h)) 0))
18351 (format fmt (/ m (* d (float h)))))
18352 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18353 (> (/ (truncate m) h) 0))
18354 (format fmt (/ m (float h))))
18355 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18356 (format fmt m))
18357 ;; fall back to smallest time unit with a format
18358 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18359 (format fmt (/ m (float h))))
18360 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18361 (format fmt (/ m (* d (float h)))))
18362 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18363 (format fmt (/ m (* w d (float h)))))
18364 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18365 (format fmt (/ m (* mo d (float h)))))
18366 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18367 (format fmt (/ m (* y d (float h))))))
18368 ;; standard (non-fractional) format, with single format string
18369 (if (stringp org-time-clocksum-format)
18370 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18371 ;; separate formats components
18372 (and (setq fmt (plist-get org-time-clocksum-format :years))
18373 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18374 (plist-get org-time-clocksum-format :require-years))
18375 (setq clocksum (concat clocksum (format fmt n))
18376 m (- m (* n y d h))))
18377 (and (setq fmt (plist-get org-time-clocksum-format :months))
18378 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18379 (plist-get org-time-clocksum-format :require-months))
18380 (setq clocksum (concat clocksum (format fmt n))
18381 m (- m (* n mo d h))))
18382 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18383 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18384 (plist-get org-time-clocksum-format :require-weeks))
18385 (setq clocksum (concat clocksum (format fmt n))
18386 m (- m (* n w d h))))
18387 (and (setq fmt (plist-get org-time-clocksum-format :days))
18388 (or (> (setq n (/ (truncate m) (* d h))) 0)
18389 (plist-get org-time-clocksum-format :require-days))
18390 (setq clocksum (concat clocksum (format fmt n))
18391 m (- m (* n d h))))
18392 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18393 (or (> (setq n (/ (truncate m) h)) 0)
18394 (plist-get org-time-clocksum-format :require-hours))
18395 (setq clocksum (concat clocksum (format fmt n))
18396 m (- m (* n h))))
18397 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18398 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18399 (setq clocksum (concat clocksum (format fmt m))))
18400 ;; return formatted time duration
18401 clocksum))))
18403 (defun org-hours-to-clocksum-string (n)
18404 (org-minutes-to-clocksum-string (* n 60)))
18406 (defun org-hh:mm-string-to-minutes (s)
18407 "Convert a string H:MM to a number of minutes.
18408 If the string is just a number, interpret it as minutes.
18409 In fact, the first hh:mm or number in the string will be taken,
18410 there can be extra stuff in the string.
18411 If no number is found, the return value is 0."
18412 (cond
18413 ((integerp s) s)
18414 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18415 (+ (* (string-to-number (match-string 1 s)) 60)
18416 (string-to-number (match-string 2 s))))
18417 ((string-match "\\([0-9]+\\)" s)
18418 (string-to-number (match-string 1 s)))
18419 (t 0)))
18421 (defcustom org-image-actual-width t
18422 "Should we use the actual width of images when inlining them?
18424 When set to t, always use the image width.
18426 When set to a number, use imagemagick (when available) to set
18427 the image's width to this value.
18429 When set to a number in a list, try to get the width from any
18430 #+ATTR.* keyword if it matches a width specification like
18432 #+ATTR_HTML: :width 300px
18434 and fall back on that number if none is found.
18436 When set to nil, try to get the width from an #+ATTR.* keyword
18437 and fall back on the original width if none is found.
18439 This requires Emacs >= 24.1, build with imagemagick support."
18440 :group 'org-appearance
18441 :version "24.4"
18442 :package-version '(Org . "8.0")
18443 :type '(choice
18444 (const :tag "Use the image width" t)
18445 (integer :tag "Use a number of pixels")
18446 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18447 (const :tag "Use #+ATTR* or don't resize" nil)))
18449 (defcustom org-agenda-inhibit-startup nil
18450 "Inhibit startup when preparing agenda buffers.
18451 When this variable is t, the initialization of the Org agenda
18452 buffers is inhibited: e.g. the visibility state is not set, the
18453 tables are not re-aligned, etc."
18454 :type 'boolean
18455 :version "24.3"
18456 :group 'org-agenda)
18458 (defcustom org-agenda-ignore-properties nil
18459 "Avoid updating text properties when building the agenda.
18460 Properties are used to prepare buffers for effort estimates,
18461 appointments, statistics and subtree-local categories.
18462 If you don't use these in the agenda, you can add them to this
18463 list and agenda building will be a bit faster.
18464 The value is a list, with zero or more of the symbols `effort', `appt',
18465 `stats' or `category'."
18466 :type '(set :greedy t
18467 (const effort)
18468 (const appt)
18469 (const stats)
18470 (const category))
18471 :version "26.1"
18472 :package-version '(Org . "8.3")
18473 :group 'org-agenda)
18475 (defun org-duration-string-to-minutes (s &optional output-to-string)
18476 "Convert a duration string S to minutes.
18478 A bare number is interpreted as minutes, modifiers can be set by
18479 customizing `org-effort-durations' (which see).
18481 Entries containing a colon are interpreted as H:MM by
18482 `org-hh:mm-string-to-minutes'."
18483 (let ((result 0)
18484 (re (concat "\\([0-9.]+\\) *\\("
18485 (regexp-opt (mapcar 'car org-effort-durations))
18486 "\\)")))
18487 (while (string-match re s)
18488 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18489 (string-to-number (match-string 1 s))))
18490 (setq s (replace-match "" nil t s)))
18491 (setq result (floor result))
18492 (cl-incf result (org-hh:mm-string-to-minutes s))
18493 (if output-to-string (number-to-string result) result)))
18495 ;;;; Files
18497 (defun org-save-all-org-buffers ()
18498 "Save all Org buffers without user confirmation."
18499 (interactive)
18500 (message "Saving all Org buffers...")
18501 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18502 (when (featurep 'org-id) (org-id-locations-save))
18503 (message "Saving all Org buffers... done"))
18505 (defun org-revert-all-org-buffers ()
18506 "Revert all Org buffers.
18507 Prompt for confirmation when there are unsaved changes.
18508 Be sure you know what you are doing before letting this function
18509 overwrite your changes.
18511 This function is useful in a setup where one tracks org files
18512 with a version control system, to revert on one machine after pulling
18513 changes from another. I believe the procedure must be like this:
18515 1. M-x org-save-all-org-buffers
18516 2. Pull changes from the other machine, resolve conflicts
18517 3. M-x org-revert-all-org-buffers"
18518 (interactive)
18519 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18520 (user-error "Abort"))
18521 (save-excursion
18522 (save-window-excursion
18523 (dolist (b (buffer-list))
18524 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18525 (with-current-buffer b buffer-file-name))
18526 (pop-to-buffer-same-window b)
18527 (revert-buffer t 'no-confirm)))
18528 (when (and (featurep 'org-id) org-id-track-globally)
18529 (org-id-locations-load)))))
18531 ;;;; Agenda files
18533 ;;;###autoload
18534 (defun org-switchb (&optional arg)
18535 "Switch between Org buffers.
18537 With `\\[universal-argument]' prefix, restrict available buffers to files.
18539 With `\\[universal-argument] \\[universal-argument]' \
18540 prefix, restrict available buffers to agenda files."
18541 (interactive "P")
18542 (let ((blist (org-buffer-list
18543 (cond ((equal arg '(4)) 'files)
18544 ((equal arg '(16)) 'agenda)))))
18545 (pop-to-buffer-same-window
18546 (completing-read "Org buffer: "
18547 (mapcar #'list (mapcar #'buffer-name blist))
18548 nil t))))
18550 (defun org-buffer-list (&optional predicate exclude-tmp)
18551 "Return a list of Org buffers.
18552 PREDICATE can be `export', `files' or `agenda'.
18554 export restrict the list to Export buffers.
18555 files restrict the list to buffers visiting Org files.
18556 agenda restrict the list to buffers visiting agenda files.
18558 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18559 (let* ((bfn nil)
18560 (agenda-files (and (eq predicate 'agenda)
18561 (mapcar 'file-truename (org-agenda-files t))))
18562 (filter
18563 (cond
18564 ((eq predicate 'files)
18565 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18566 ((eq predicate 'export)
18567 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18568 ((eq predicate 'agenda)
18569 (lambda (b)
18570 (with-current-buffer b
18571 (and (derived-mode-p 'org-mode)
18572 (setq bfn (buffer-file-name b))
18573 (member (file-truename bfn) agenda-files)))))
18574 (t (lambda (b) (with-current-buffer b
18575 (or (derived-mode-p 'org-mode)
18576 (string-match "\\*Org .*Export"
18577 (buffer-name b)))))))))
18578 (delq nil
18579 (mapcar
18580 (lambda(b)
18581 (if (and (funcall filter b)
18582 (or (not exclude-tmp)
18583 (not (string-match "tmp" (buffer-name b)))))
18585 nil))
18586 (buffer-list)))))
18588 (defun org-agenda-files (&optional unrestricted archives)
18589 "Get the list of agenda files.
18590 Optional UNRESTRICTED means return the full list even if a restriction
18591 is currently in place.
18592 When ARCHIVES is t, include all archive files that are really being
18593 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18594 `org-agenda-archives-mode' is t."
18595 (let ((files
18596 (cond
18597 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18598 ((stringp org-agenda-files) (org-read-agenda-file-list))
18599 ((listp org-agenda-files) org-agenda-files)
18600 (t (error "Invalid value of `org-agenda-files'")))))
18601 (setq files (apply 'append
18602 (mapcar (lambda (f)
18603 (if (file-directory-p f)
18604 (directory-files
18605 f t org-agenda-file-regexp)
18606 (list f)))
18607 files)))
18608 (when org-agenda-skip-unavailable-files
18609 (setq files (delq nil
18610 (mapcar (function
18611 (lambda (file)
18612 (and (file-readable-p file) file)))
18613 files))))
18614 (when (or (eq archives t)
18615 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18616 (setq files (org-add-archive-files files)))
18617 files))
18619 (defun org-agenda-file-p (&optional file)
18620 "Return non-nil, if FILE is an agenda file.
18621 If FILE is omitted, use the file associated with the current
18622 buffer."
18623 (let ((fname (or file (buffer-file-name))))
18624 (and fname
18625 (member (file-truename fname)
18626 (mapcar #'file-truename (org-agenda-files t))))))
18628 (defun org-edit-agenda-file-list ()
18629 "Edit the list of agenda files.
18630 Depending on setup, this either uses customize to edit the variable
18631 `org-agenda-files', or it visits the file that is holding the list. In the
18632 latter case, the buffer is set up in a way that saving it automatically kills
18633 the buffer and restores the previous window configuration."
18634 (interactive)
18635 (if (stringp org-agenda-files)
18636 (let ((cw (current-window-configuration)))
18637 (find-file org-agenda-files)
18638 (setq-local org-window-configuration cw)
18639 (add-hook 'after-save-hook
18640 (lambda ()
18641 (set-window-configuration
18642 (prog1 org-window-configuration
18643 (kill-buffer (current-buffer))))
18644 (org-install-agenda-files-menu)
18645 (message "New agenda file list installed"))
18646 nil 'local)
18647 (message "%s" (substitute-command-keys
18648 "Edit list and finish with \\[save-buffer]")))
18649 (customize-variable 'org-agenda-files)))
18651 (defun org-store-new-agenda-file-list (list)
18652 "Set new value for the agenda file list and save it correctly."
18653 (if (stringp org-agenda-files)
18654 (let ((fe (org-read-agenda-file-list t)) b u)
18655 (while (setq b (find-buffer-visiting org-agenda-files))
18656 (kill-buffer b))
18657 (with-temp-file org-agenda-files
18658 (insert
18659 (mapconcat
18660 (lambda (f) ;; Keep un-expanded entries.
18661 (if (setq u (assoc f fe))
18662 (cdr u)
18664 list "\n")
18665 "\n")))
18666 (let ((org-mode-hook nil) (org-inhibit-startup t)
18667 (org-insert-mode-line-in-empty-file nil))
18668 (setq org-agenda-files list)
18669 (customize-save-variable 'org-agenda-files org-agenda-files))))
18671 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18672 "Read the list of agenda files from a file.
18673 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18674 filenames, used by `org-store-new-agenda-file-list' to write back
18675 un-expanded file names."
18676 (when (file-directory-p org-agenda-files)
18677 (error "`org-agenda-files' cannot be a single directory"))
18678 (when (stringp org-agenda-files)
18679 (with-temp-buffer
18680 (insert-file-contents org-agenda-files)
18681 (mapcar
18682 (lambda (f)
18683 (let ((e (expand-file-name (substitute-in-file-name f)
18684 org-directory)))
18685 (if pair-with-expansion
18686 (cons e f)
18687 e)))
18688 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18690 ;;;###autoload
18691 (defun org-cycle-agenda-files ()
18692 "Cycle through the files in `org-agenda-files'.
18693 If the current buffer visits an agenda file, find the next one in the list.
18694 If the current buffer does not, find the first agenda file."
18695 (interactive)
18696 (let* ((fs (or (org-agenda-files t)
18697 (user-error "No agenda files")))
18698 (files (copy-sequence fs))
18699 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18700 file)
18701 (when tcf
18702 (while (and (setq file (pop files))
18703 (not (equal (file-truename file) tcf)))))
18704 (find-file (car (or files fs)))
18705 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18707 (defun org-agenda-file-to-front (&optional to-end)
18708 "Move/add the current file to the top of the agenda file list.
18709 If the file is not present in the list, it is added to the front. If it is
18710 present, it is moved there. With optional argument TO-END, add/move to the
18711 end of the list."
18712 (interactive "P")
18713 (let ((org-agenda-skip-unavailable-files nil)
18714 (file-alist (mapcar (lambda (x)
18715 (cons (file-truename x) x))
18716 (org-agenda-files t)))
18717 (ctf (file-truename
18718 (or buffer-file-name
18719 (user-error "Please save the current buffer to a file"))))
18720 x had)
18721 (setq x (assoc ctf file-alist) had x)
18723 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18724 (if to-end
18725 (setq file-alist (append (delq x file-alist) (list x)))
18726 (setq file-alist (cons x (delq x file-alist))))
18727 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18728 (org-install-agenda-files-menu)
18729 (message "File %s to %s of agenda file list"
18730 (if had "moved" "added") (if to-end "end" "front"))))
18732 (defun org-remove-file (&optional file)
18733 "Remove current file from the list of files in variable `org-agenda-files'.
18734 These are the files which are being checked for agenda entries.
18735 Optional argument FILE means use this file instead of the current."
18736 (interactive)
18737 (let* ((org-agenda-skip-unavailable-files nil)
18738 (file (or file buffer-file-name
18739 (user-error "Current buffer does not visit a file")))
18740 (true-file (file-truename file))
18741 (afile (abbreviate-file-name file))
18742 (files (delq nil (mapcar
18743 (lambda (x)
18744 (unless (equal true-file
18745 (file-truename x))
18747 (org-agenda-files t)))))
18748 (if (not (= (length files) (length (org-agenda-files t))))
18749 (progn
18750 (org-store-new-agenda-file-list files)
18751 (org-install-agenda-files-menu)
18752 (message "Removed from Org Agenda list: %s" afile))
18753 (message "File was not in list: %s (not removed)" afile))))
18755 (defun org-file-menu-entry (file)
18756 (vector file (list 'find-file file) t))
18758 (defun org-check-agenda-file (file)
18759 "Make sure FILE exists. If not, ask user what to do."
18760 (unless (file-exists-p file)
18761 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18762 (abbreviate-file-name file))
18763 (let ((r (downcase (read-char-exclusive))))
18764 (cond
18765 ((equal r ?r)
18766 (org-remove-file file)
18767 (throw 'nextfile t))
18768 (t (user-error "Abort"))))))
18770 (defun org-get-agenda-file-buffer (file)
18771 "Get an agenda buffer visiting FILE.
18772 If the buffer needs to be created, add it to the list of buffers
18773 which might be released later."
18774 (let ((buf (org-find-base-buffer-visiting file)))
18775 (if buf
18776 buf ; just return it
18777 ;; Make a new buffer and remember it
18778 (setq buf (find-file-noselect file))
18779 (when buf (push buf org-agenda-new-buffers))
18780 buf)))
18782 (defun org-release-buffers (blist)
18783 "Release all buffers in list, asking the user for confirmation when needed.
18784 When a buffer is unmodified, it is just killed. When modified, it is saved
18785 \(if the user agrees) and then killed."
18786 (let (file)
18787 (dolist (buf blist)
18788 (setq file (buffer-file-name buf))
18789 (when (and (buffer-modified-p buf)
18790 file
18791 (y-or-n-p (format "Save file %s? " file)))
18792 (with-current-buffer buf (save-buffer)))
18793 (kill-buffer buf))))
18795 (defun org-agenda-prepare-buffers (files)
18796 "Create buffers for all agenda files, protect archived trees and comments."
18797 (interactive)
18798 (let ((pa '(:org-archived t))
18799 (pc '(:org-comment t))
18800 (pall '(:org-archived t :org-comment t))
18801 (inhibit-read-only t)
18802 (org-inhibit-startup org-agenda-inhibit-startup)
18803 (rea (concat ":" org-archive-tag ":"))
18804 re pos)
18805 (setq org-tag-alist-for-agenda nil
18806 org-tag-groups-alist-for-agenda nil)
18807 (save-excursion
18808 (save-restriction
18809 (dolist (file files)
18810 (catch 'nextfile
18811 (if (bufferp file)
18812 (set-buffer file)
18813 (org-check-agenda-file file)
18814 (set-buffer (org-get-agenda-file-buffer file)))
18815 (widen)
18816 (org-set-regexps-and-options 'tags-only)
18817 (setq pos (point))
18818 (or (memq 'category org-agenda-ignore-properties)
18819 (org-refresh-category-properties))
18820 (or (memq 'stats org-agenda-ignore-properties)
18821 (org-refresh-stats-properties))
18822 (or (memq 'effort org-agenda-ignore-properties)
18823 (org-refresh-effort-properties))
18824 (or (memq 'appt org-agenda-ignore-properties)
18825 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18826 (setq org-todo-keywords-for-agenda
18827 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18828 (setq org-done-keywords-for-agenda
18829 (append org-done-keywords-for-agenda org-done-keywords))
18830 (setq org-todo-keyword-alist-for-agenda
18831 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18832 (setq org-tag-alist-for-agenda
18833 (org-uniquify
18834 (append org-tag-alist-for-agenda
18835 org-current-tag-alist)))
18836 ;; Merge current file's tag groups into global
18837 ;; `org-tag-groups-alist-for-agenda'.
18838 (when org-group-tags
18839 (dolist (alist org-tag-groups-alist)
18840 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18841 (if old
18842 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18843 (push alist org-tag-groups-alist-for-agenda)))))
18844 (org-with-silent-modifications
18845 (save-excursion
18846 (remove-text-properties (point-min) (point-max) pall)
18847 (when org-agenda-skip-archived-trees
18848 (goto-char (point-min))
18849 (while (re-search-forward rea nil t)
18850 (when (org-at-heading-p t)
18851 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18852 (goto-char (point-min))
18853 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18854 (while (re-search-forward re nil t)
18855 (when (save-match-data (org-in-commented-heading-p t))
18856 (add-text-properties
18857 (match-beginning 0) (org-end-of-subtree t) pc)))))
18858 (goto-char pos)))))
18859 (setq org-todo-keywords-for-agenda
18860 (org-uniquify org-todo-keywords-for-agenda))
18861 (setq org-todo-keyword-alist-for-agenda
18862 (org-uniquify org-todo-keyword-alist-for-agenda))))
18865 ;;;; CDLaTeX minor mode
18867 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18868 "Keymap for the minor `org-cdlatex-mode'.")
18870 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18871 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18872 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18873 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18874 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18876 (defvar org-cdlatex-texmathp-advice-is-done nil
18877 "Flag remembering if we have applied the advice to texmathp already.")
18879 (define-minor-mode org-cdlatex-mode
18880 "Toggle the minor `org-cdlatex-mode'.
18881 This mode supports entering LaTeX environment and math in LaTeX fragments
18882 in Org mode.
18883 \\{org-cdlatex-mode-map}"
18884 nil " OCDL" nil
18885 (when org-cdlatex-mode
18886 (require 'cdlatex)
18887 (run-hooks 'cdlatex-mode-hook)
18888 (cdlatex-compute-tables))
18889 (unless org-cdlatex-texmathp-advice-is-done
18890 (setq org-cdlatex-texmathp-advice-is-done t)
18891 (defadvice texmathp (around org-math-always-on activate)
18892 "Always return t in Org buffers.
18893 This is because we want to insert math symbols without dollars even outside
18894 the LaTeX math segments. If Org mode thinks that point is actually inside
18895 an embedded LaTeX fragment, let `texmathp' do its job.
18896 `\\[org-cdlatex-mode-map]'"
18897 (interactive)
18898 (let (p)
18899 (cond
18900 ((not (derived-mode-p 'org-mode)) ad-do-it)
18901 ((eq this-command 'cdlatex-math-symbol)
18902 (setq ad-return-value t
18903 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18905 (let ((p (org-inside-LaTeX-fragment-p)))
18906 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18907 (setq ad-return-value t
18908 texmathp-why '("Org mode embedded math" . 0))
18909 (when p ad-do-it)))))))))
18911 (defun turn-on-org-cdlatex ()
18912 "Unconditionally turn on `org-cdlatex-mode'."
18913 (org-cdlatex-mode 1))
18915 (defun org-try-cdlatex-tab ()
18916 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18917 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18918 - inside a LaTeX fragment, or
18919 - after the first word in a line, where an abbreviation expansion could
18920 insert a LaTeX environment."
18921 (when org-cdlatex-mode
18922 (cond
18923 ;; Before any word on the line: No expansion possible.
18924 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18925 ;; Just after first word on the line: Expand it. Make sure it
18926 ;; cannot happen on headlines, though.
18927 ((save-excursion
18928 (skip-chars-backward "a-zA-Z0-9*")
18929 (skip-chars-backward " \t")
18930 (and (bolp) (not (org-at-heading-p))))
18931 (cdlatex-tab) t)
18932 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18934 (defun org-cdlatex-underscore-caret (&optional _arg)
18935 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18936 Revert to the normal definition outside of these fragments."
18937 (interactive "P")
18938 (if (org-inside-LaTeX-fragment-p)
18939 (call-interactively 'cdlatex-sub-superscript)
18940 (let (org-cdlatex-mode)
18941 (call-interactively (key-binding (vector last-input-event))))))
18943 (defun org-cdlatex-math-modify (&optional _arg)
18944 "Execute `cdlatex-math-modify' in LaTeX fragments.
18945 Revert to the normal definition outside of these fragments."
18946 (interactive "P")
18947 (if (org-inside-LaTeX-fragment-p)
18948 (call-interactively 'cdlatex-math-modify)
18949 (let (org-cdlatex-mode)
18950 (call-interactively (key-binding (vector last-input-event))))))
18952 (defun org-cdlatex-environment-indent (&optional environment item)
18953 "Execute `cdlatex-environment' and indent the inserted environment.
18955 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18957 The inserted environment is indented to current indentation
18958 unless point is at the beginning of the line, in which the
18959 environment remains unintended."
18960 (interactive)
18961 ;; cdlatex-environment always return nil. Therefore, capture output
18962 ;; first and determine if an environment was selected.
18963 (let* ((beg (point-marker))
18964 (end (copy-marker (point) t))
18965 (inserted (progn
18966 (ignore-errors (cdlatex-environment environment item))
18967 (< beg end)))
18968 ;; Figure out how many lines to move forward after the
18969 ;; environment has been inserted.
18970 (lines (when inserted
18971 (save-excursion
18972 (- (cl-loop while (< beg (point))
18973 with x = 0
18974 do (forward-line -1)
18975 (cl-incf x)
18976 finally return x)
18977 (if (progn (goto-char beg)
18978 (and (progn (skip-chars-forward " \t") (eolp))
18979 (progn (skip-chars-backward " \t") (bolp))))
18980 1 0)))))
18981 (env (org-trim (delete-and-extract-region beg end))))
18982 (when inserted
18983 ;; Get indentation of next line unless at column 0.
18984 (let ((ind (if (bolp) 0
18985 (save-excursion
18986 (org-return-indent)
18987 (prog1 (org-get-indentation)
18988 (when (progn (skip-chars-forward " \t") (eolp))
18989 (delete-region beg (point)))))))
18990 (bol (progn (skip-chars-backward " \t") (bolp))))
18991 ;; Insert a newline before environment unless at column zero
18992 ;; to "escape" the current line. Insert a newline if
18993 ;; something is one the same line as \end{ENVIRONMENT}.
18994 (insert
18995 (concat (unless bol "\n") env
18996 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18997 (unless (zerop ind)
18998 (save-excursion
18999 (goto-char beg)
19000 (while (< (point) end)
19001 (unless (eolp) (indent-line-to ind))
19002 (forward-line))))
19003 (goto-char beg)
19004 (forward-line lines)
19005 (indent-line-to ind)))
19006 (set-marker beg nil)
19007 (set-marker end nil)))
19010 ;;;; LaTeX fragments
19012 (defun org-inside-LaTeX-fragment-p ()
19013 "Test if point is inside a LaTeX fragment.
19014 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19015 sequence appearing also before point.
19016 Even though the matchers for math are configurable, this function assumes
19017 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19018 delimiters are skipped when they have been removed by customization.
19019 The return value is nil, or a cons cell with the delimiter and the
19020 position of this delimiter.
19022 This function does a reasonably good job, but can locally be fooled by
19023 for example currency specifications. For example it will assume being in
19024 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19025 fragments that are properly closed, but during editing, we have to live
19026 with the uncertainty caused by missing closing delimiters. This function
19027 looks only before point, not after."
19028 (catch 'exit
19029 (let ((pos (point))
19030 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19031 (lim (save-excursion (org-backward-paragraph) (point)))
19032 dd-on str (start 0) m re)
19033 (goto-char pos)
19034 (when dodollar
19035 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19036 re (nth 1 (assoc "$" org-latex-regexps)))
19037 (while (string-match re str start)
19038 (cond
19039 ((= (match-end 0) (length str))
19040 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19041 ((= (match-end 0) (- (length str) 5))
19042 (throw 'exit nil))
19043 (t (setq start (match-end 0))))))
19044 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19045 (goto-char pos)
19046 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19047 (and (match-beginning 2) (throw 'exit nil))
19048 ;; count $$
19049 (while (re-search-backward "\\$\\$" lim t)
19050 (setq dd-on (not dd-on)))
19051 (goto-char pos)
19052 (when dd-on (cons "$$" m))))))
19054 (defun org-inside-latex-macro-p ()
19055 "Is point inside a LaTeX macro or its arguments?"
19056 (save-match-data
19057 (org-in-regexp
19058 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19060 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19061 "Build an overlay between BEG and END using IMAGE file.
19062 Argument IMAGETYPE is the extension of the displayed image,
19063 as a string. It defaults to \"png\"."
19064 (let ((ov (make-overlay beg end))
19065 (imagetype (or (intern imagetype) 'png)))
19066 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19067 (overlay-put ov 'evaporate t)
19068 (overlay-put ov
19069 'modification-hooks
19070 (list (lambda (o _flag _beg _end &optional _l)
19071 (delete-overlay o))))
19072 (overlay-put ov
19073 'display
19074 (list 'image :type imagetype :file image :ascent 'center))))
19076 (defun org--list-latex-overlays (&optional beg end)
19077 "List all Org LaTeX overlays in current buffer.
19078 Limit to overlays between BEG and END when those are provided."
19079 (cl-remove-if-not
19080 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19081 (overlays-in (or beg (point-min)) (or end (point-max)))))
19083 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19084 "Remove all overlays with LaTeX fragment images in current buffer.
19085 When optional arguments BEG and END are non-nil, remove all
19086 overlays between them instead. Return a non-nil value when some
19087 overlays were removed, nil otherwise."
19088 (let ((overlays (org--list-latex-overlays beg end)))
19089 (mapc #'delete-overlay overlays)
19090 overlays))
19092 (defun org-toggle-latex-fragment (&optional arg)
19093 "Preview the LaTeX fragment at point, or all locally or globally.
19095 If the cursor is on a LaTeX fragment, create the image and overlay
19096 it over the source code, if there is none. Remove it otherwise.
19097 If there is no fragment at point, display all fragments in the
19098 current section.
19100 With prefix ARG, preview or clear image for all fragments in the
19101 current subtree or in the whole buffer when used before the first
19102 headline. With a prefix ARG `\\[universal-argument] \
19103 \\[universal-argument]' preview or clear images
19104 for all fragments in the buffer."
19105 (interactive "P")
19106 (when (display-graphic-p)
19107 (catch 'exit
19108 (save-excursion
19109 (let (beg end msg)
19110 (cond
19111 ((or (equal arg '(16))
19112 (and (equal arg '(4))
19113 (org-with-limited-levels (org-before-first-heading-p))))
19114 (if (org-remove-latex-fragment-image-overlays)
19115 (progn (message "LaTeX fragments images removed from buffer")
19116 (throw 'exit nil))
19117 (setq msg "Creating images for buffer...")))
19118 ((equal arg '(4))
19119 (org-with-limited-levels (org-back-to-heading t))
19120 (setq beg (point))
19121 (setq end (progn (org-end-of-subtree t) (point)))
19122 (if (org-remove-latex-fragment-image-overlays beg end)
19123 (progn
19124 (message "LaTeX fragment images removed from subtree")
19125 (throw 'exit nil))
19126 (setq msg "Creating images for subtree...")))
19127 ((let ((datum (org-element-context)))
19128 (when (memq (org-element-type datum)
19129 '(latex-environment latex-fragment))
19130 (setq beg (org-element-property :begin datum))
19131 (setq end (org-element-property :end datum))
19132 (if (org-remove-latex-fragment-image-overlays beg end)
19133 (progn (message "LaTeX fragment image removed")
19134 (throw 'exit nil))
19135 (setq msg "Creating image...")))))
19137 (org-with-limited-levels
19138 (setq beg (if (org-at-heading-p) (line-beginning-position)
19139 (outline-previous-heading)
19140 (point)))
19141 (setq end (progn (outline-next-heading) (point)))
19142 (if (org-remove-latex-fragment-image-overlays beg end)
19143 (progn
19144 (message "LaTeX fragment images removed from section")
19145 (throw 'exit nil))
19146 (setq msg "Creating images for section...")))))
19147 (let ((file (buffer-file-name (buffer-base-buffer))))
19148 (org-format-latex
19149 (concat org-preview-latex-image-directory "org-ltximg")
19150 beg end
19151 ;; Emacs cannot overlay images from remote hosts. Create
19152 ;; it in `temporary-file-directory' instead.
19153 (if (or (not file) (file-remote-p file))
19154 temporary-file-directory
19155 default-directory)
19156 'overlays msg 'forbuffer org-preview-latex-default-process))
19157 (message (concat msg "done")))))))
19159 (defun org-format-latex
19160 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19161 "Replace LaTeX fragments with links to an image.
19163 The function takes care of creating the replacement image.
19165 Only consider fragments between BEG and END when those are
19166 provided.
19168 When optional argument OVERLAYS is non-nil, display the image on
19169 top of the fragment instead of replacing it.
19171 PROCESSING-TYPE is the conversion method to use, as a symbol.
19173 Some of the options can be changed using the variable
19174 `org-format-latex-options', which see."
19175 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19176 (unless (eq processing-type 'verbatim)
19177 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19178 (cnt 0)
19179 checkdir-flag)
19180 (goto-char (or beg (point-min)))
19181 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19182 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19183 (overlay-recenter (or end (point-max))))
19184 (while (re-search-forward math-regexp end t)
19185 (unless (and overlays
19186 (eq (get-char-property (point) 'org-overlay-type)
19187 'org-latex-overlay))
19188 (let* ((context (org-element-context))
19189 (type (org-element-type context)))
19190 (when (memq type '(latex-environment latex-fragment))
19191 (let ((block-type (eq type 'latex-environment))
19192 (value (org-element-property :value context))
19193 (beg (org-element-property :begin context))
19194 (end (save-excursion
19195 (goto-char (org-element-property :end context))
19196 (skip-chars-backward " \r\t\n")
19197 (point))))
19198 (cond
19199 ((eq processing-type 'mathjax)
19200 ;; Prepare for MathJax processing.
19201 (if (not (string-match "\\`\\$\\$?" value))
19202 (goto-char end)
19203 (delete-region beg end)
19204 (if (string= (match-string 0 value) "$$")
19205 (insert "\\[" (substring value 2 -2) "\\]")
19206 (insert "\\(" (substring value 1 -1) "\\)"))))
19207 ((assq processing-type org-preview-latex-process-alist)
19208 ;; Process to an image.
19209 (cl-incf cnt)
19210 (goto-char beg)
19211 (let* ((processing-info
19212 (cdr (assq processing-type org-preview-latex-process-alist)))
19213 (face (face-at-point))
19214 ;; Get the colors from the face at point.
19216 (let ((color (plist-get org-format-latex-options
19217 :foreground)))
19218 (if (and forbuffer (eq color 'auto))
19219 (face-attribute face :foreground nil 'default)
19220 color)))
19222 (let ((color (plist-get org-format-latex-options
19223 :background)))
19224 (if (and forbuffer (eq color 'auto))
19225 (face-attribute face :background nil 'default)
19226 color)))
19227 (hash (sha1 (prin1-to-string
19228 (list org-format-latex-header
19229 org-latex-default-packages-alist
19230 org-latex-packages-alist
19231 org-format-latex-options
19232 forbuffer value fg bg))))
19233 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19234 (absprefix (expand-file-name prefix dir))
19235 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19236 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19237 (sep (and block-type "\n\n"))
19238 (link (concat sep "[[file:" linkfile "]]" sep))
19239 (options
19240 (org-combine-plists
19241 org-format-latex-options
19242 `(:foreground ,fg :background ,bg))))
19243 (when msg (message msg cnt))
19244 (unless checkdir-flag ; Ensure the directory exists.
19245 (setq checkdir-flag t)
19246 (let ((todir (file-name-directory absprefix)))
19247 (unless (file-directory-p todir)
19248 (make-directory todir t))))
19249 (unless (file-exists-p movefile)
19250 (org-create-formula-image
19251 value movefile options forbuffer processing-type))
19252 (if overlays
19253 (progn
19254 (dolist (o (overlays-in beg end))
19255 (when (eq (overlay-get o 'org-overlay-type)
19256 'org-latex-overlay)
19257 (delete-overlay o)))
19258 (org--format-latex-make-overlay beg end movefile imagetype)
19259 (goto-char end))
19260 (delete-region beg end)
19261 (insert
19262 (org-add-props link
19263 (list 'org-latex-src
19264 (replace-regexp-in-string "\"" "" value)
19265 'org-latex-src-embed-type
19266 (if block-type 'paragraph 'character)))))))
19267 ((eq processing-type 'mathml)
19268 ;; Process to MathML.
19269 (unless (org-format-latex-mathml-available-p)
19270 (user-error "LaTeX to MathML converter not configured"))
19271 (cl-incf cnt)
19272 (when msg (message msg cnt))
19273 (goto-char beg)
19274 (delete-region beg end)
19275 (insert (org-format-latex-as-mathml
19276 value block-type prefix dir)))
19278 (error "Unknown conversion process %s for LaTeX fragments"
19279 processing-type)))))))))))
19281 (defun org-create-math-formula (latex-frag &optional mathml-file)
19282 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19283 Use `org-latex-to-mathml-convert-command'. If the conversion is
19284 sucessful, return the portion between \"<math...> </math>\"
19285 elements otherwise return nil. When MATHML-FILE is specified,
19286 write the results in to that file. When invoked as an
19287 interactive command, prompt for LATEX-FRAG, with initial value
19288 set to the current active region and echo the results for user
19289 inspection."
19290 (interactive (list (let ((frag (when (org-region-active-p)
19291 (buffer-substring-no-properties
19292 (region-beginning) (region-end)))))
19293 (read-string "LaTeX Fragment: " frag nil frag))))
19294 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19295 (let* ((tmp-in-file
19296 (let ((file (file-relative-name
19297 (make-temp-name (expand-file-name "ltxmathml-in")))))
19298 (write-region latex-frag nil file)
19299 file))
19300 (tmp-out-file (file-relative-name
19301 (make-temp-name (expand-file-name "ltxmathml-out"))))
19302 (cmd (format-spec
19303 org-latex-to-mathml-convert-command
19304 `((?j . ,(and org-latex-to-mathml-jar-file
19305 (shell-quote-argument
19306 (expand-file-name
19307 org-latex-to-mathml-jar-file))))
19308 (?I . ,(shell-quote-argument tmp-in-file))
19309 (?i . ,latex-frag)
19310 (?o . ,(shell-quote-argument tmp-out-file)))))
19311 mathml shell-command-output)
19312 (when (called-interactively-p 'any)
19313 (unless (org-format-latex-mathml-available-p)
19314 (user-error "LaTeX to MathML converter not configured")))
19315 (message "Running %s" cmd)
19316 (setq shell-command-output (shell-command-to-string cmd))
19317 (setq mathml
19318 (when (file-readable-p tmp-out-file)
19319 (with-current-buffer (find-file-noselect tmp-out-file t)
19320 (goto-char (point-min))
19321 (when (re-search-forward
19322 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19323 (regexp-quote
19324 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19325 nil t)
19326 (prog1 (match-string 0) (kill-buffer))))))
19327 (cond
19328 (mathml
19329 (setq mathml
19330 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19331 (when mathml-file
19332 (write-region mathml nil mathml-file))
19333 (when (called-interactively-p 'any)
19334 (message mathml)))
19335 ((message "LaTeX to MathML conversion failed")
19336 (message shell-command-output)))
19337 (delete-file tmp-in-file)
19338 (when (file-exists-p tmp-out-file)
19339 (delete-file tmp-out-file))
19340 mathml))
19342 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19343 prefix &optional dir)
19344 "Use `org-create-math-formula' but check local cache first."
19345 (let* ((absprefix (expand-file-name prefix dir))
19346 (print-length nil) (print-level nil)
19347 (formula-id (concat
19348 "formula-"
19349 (sha1
19350 (prin1-to-string
19351 (list latex-frag
19352 org-latex-to-mathml-convert-command)))))
19353 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19354 (formula-cache-dir (file-name-directory formula-cache)))
19356 (unless (file-directory-p formula-cache-dir)
19357 (make-directory formula-cache-dir t))
19359 (unless (file-exists-p formula-cache)
19360 (org-create-math-formula latex-frag formula-cache))
19362 (if (file-exists-p formula-cache)
19363 ;; Successful conversion. Return the link to MathML file.
19364 (org-add-props
19365 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19366 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19367 'org-latex-src-embed-type (if latex-frag-type
19368 'paragraph 'character)))
19369 ;; Failed conversion. Return the LaTeX fragment verbatim
19370 latex-frag)))
19372 (defun org--get-display-dpi ()
19373 "Get the DPI of the display.
19374 The function assumes that the display has the same pixel width in
19375 the horizontal and vertical directions."
19376 (if (display-graphic-p)
19377 (round (/ (display-pixel-height)
19378 (/ (display-mm-height) 25.4)))
19379 (error "Attempt to calculate the dpi of a non-graphic display")))
19381 (defun org-create-formula-image
19382 (string tofile options buffer &optional processing-type)
19383 "Create an image from LaTeX source using external processes.
19385 The LaTeX STRING is saved to a temporary LaTeX file, then
19386 converted to an image file by process PROCESSING-TYPE defined in
19387 `org-preview-latex-process-alist'. A nil value defaults to
19388 `org-preview-latex-default-process'.
19390 The generated image file is eventually moved to TOFILE.
19392 The OPTIONS argument controls the size, foreground color and
19393 background color of the generated image.
19395 When BUFFER non-nil, this function is used for LaTeX previewing.
19396 Otherwise, it is used to deal with LaTeX snippets showed in
19397 a HTML file."
19398 (let* ((processing-type (or processing-type
19399 org-preview-latex-default-process))
19400 (processing-info
19401 (cdr (assq processing-type org-preview-latex-process-alist)))
19402 (programs (plist-get processing-info :programs))
19403 (error-message (or (plist-get processing-info :message) ""))
19404 (use-xcolor (plist-get processing-info :use-xcolor))
19405 (image-input-type (plist-get processing-info :image-input-type))
19406 (image-output-type (plist-get processing-info :image-output-type))
19407 (post-clean (or (plist-get processing-info :post-clean)
19408 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19409 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19410 (latex-header
19411 (or (plist-get processing-info :latex-header)
19412 (org-latex-make-preamble
19413 (org-export-get-environment (org-export-get-backend 'latex))
19414 org-format-latex-header
19415 'snippet)))
19416 (latex-compiler (plist-get processing-info :latex-compiler))
19417 (image-converter (plist-get processing-info :image-converter))
19418 (tmpdir temporary-file-directory)
19419 (texfilebase (make-temp-name
19420 (expand-file-name "orgtex" tmpdir)))
19421 (texfile (concat texfilebase ".tex"))
19422 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19423 '(1.0 . 1.0)))
19424 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19425 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19426 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19427 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19428 "Black"))
19429 (bg (or (plist-get options (if buffer :background :html-background))
19430 "Transparent"))
19431 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19432 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19433 (dolist (program programs)
19434 (org-check-external-command program error-message))
19435 (if use-xcolor
19436 (progn (if (eq fg 'default)
19437 (setq fg (org-latex-color :foreground))
19438 (setq fg (org-latex-color-format fg)))
19439 (if (eq bg 'default)
19440 (setq bg (org-latex-color :background))
19441 (setq bg (org-latex-color-format
19442 (if (string= bg "Transparent") "white" bg))))
19443 (with-temp-file texfile
19444 (insert latex-header)
19445 (insert "\n\\begin{document}\n"
19446 "\\definecolor{fg}{rgb}{" fg "}\n"
19447 "\\definecolor{bg}{rgb}{" bg "}\n"
19448 "\n\\pagecolor{bg}\n"
19449 "\n{\\color{fg}\n"
19450 string
19451 "\n}\n"
19452 "\n\\end{document}\n")))
19453 (if (eq fg 'default)
19454 (setq fg (org-dvipng-color :foreground))
19455 (unless (string= fg "Transparent")
19456 (setq fg (org-dvipng-color-format fg))))
19457 (if (eq bg 'default)
19458 (setq bg (org-dvipng-color :background))
19459 (unless (string= bg "Transparent")
19460 (setq bg (org-dvipng-color-format bg))))
19461 (with-temp-file texfile
19462 (insert latex-header)
19463 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19465 (let* ((err-msg (format "Please adjust `%s' part of \
19466 `org-preview-latex-process-alist'."
19467 processing-type))
19468 (image-input-file
19469 (org-compile-file
19470 texfile latex-compiler image-input-type err-msg log-buf))
19471 (image-output-file
19472 (org-compile-file
19473 image-input-file image-converter image-output-type err-msg log-buf
19474 `((?F . ,(shell-quote-argument fg))
19475 (?B . ,(shell-quote-argument bg))
19476 (?D . ,(shell-quote-argument (format "%s" dpi)))
19477 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19478 (copy-file image-output-file tofile 'replace)
19479 (dolist (e post-clean)
19480 (when (file-exists-p (concat texfilebase e))
19481 (delete-file (concat texfilebase e))))
19482 image-output-file)))
19484 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19485 "Fill a LaTeX header template TPL.
19486 In the template, the following place holders will be recognized:
19488 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19489 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19490 [PACKAGES] \\usepackage statements for PKG
19491 [NO-PACKAGES] do not include PKG
19492 [EXTRA] the string EXTRA
19493 [NO-EXTRA] do not include EXTRA
19495 For backward compatibility, if both the positive and the negative place
19496 holder is missing, the positive one (without the \"NO-\") will be
19497 assumed to be present at the end of the template.
19498 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19499 EXTRA is a string.
19500 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19501 (let (rpl (end ""))
19502 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19503 (setq rpl (if (or (match-end 1) (not def-pkg))
19504 "" (org-latex-packages-to-string def-pkg snippets-p t))
19505 tpl (replace-match rpl t t tpl))
19506 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19508 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19509 (setq rpl (if (or (match-end 1) (not pkg))
19510 "" (org-latex-packages-to-string pkg snippets-p t))
19511 tpl (replace-match rpl t t tpl))
19512 (when pkg (setq end
19513 (concat end "\n"
19514 (org-latex-packages-to-string pkg snippets-p)))))
19516 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19517 (setq rpl (if (or (match-end 1) (not extra))
19518 "" (concat extra "\n"))
19519 tpl (replace-match rpl t t tpl))
19520 (when (and extra (string-match "\\S-" extra))
19521 (setq end (concat end "\n" extra))))
19523 (if (string-match "\\S-" end)
19524 (concat tpl "\n" end)
19525 tpl)))
19527 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19528 "Turn an alist of packages into a string with the \\usepackage macros."
19529 (setq pkg (mapconcat (lambda(p)
19530 (cond
19531 ((stringp p) p)
19532 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19533 (format "%% Package %s omitted" (cadr p)))
19534 ((equal "" (car p))
19535 (format "\\usepackage{%s}" (cadr p)))
19537 (format "\\usepackage[%s]{%s}"
19538 (car p) (cadr p)))))
19540 "\n"))
19541 (if newline (concat pkg "\n") pkg))
19543 (defun org-dvipng-color (attr)
19544 "Return a RGB color specification for dvipng."
19545 (org-dvipng-color-format (face-attribute 'default attr nil)))
19547 (defun org-dvipng-color-format (color-name)
19548 "Convert COLOR-NAME to a RGB color value for dvipng."
19549 (apply #'format "rgb %s %s %s"
19550 (mapcar 'org-normalize-color
19551 (color-values color-name))))
19553 (defun org-latex-color (attr)
19554 "Return a RGB color for the LaTeX color package."
19555 (org-latex-color-format (face-attribute 'default attr nil)))
19557 (defun org-latex-color-format (color-name)
19558 "Convert COLOR-NAME to a RGB color value."
19559 (apply #'format "%s,%s,%s"
19560 (mapcar 'org-normalize-color
19561 (color-values color-name))))
19563 (defun org-normalize-color (value)
19564 "Return string to be used as color value for an RGB component."
19565 (format "%g" (/ value 65535.0)))
19569 ;; Image display
19571 (defvar-local org-inline-image-overlays nil)
19573 (defun org-toggle-inline-images (&optional include-linked)
19574 "Toggle the display of inline images.
19575 INCLUDE-LINKED is passed to `org-display-inline-images'."
19576 (interactive "P")
19577 (if org-inline-image-overlays
19578 (progn
19579 (org-remove-inline-images)
19580 (when (called-interactively-p 'interactive)
19581 (message "Inline image display turned off")))
19582 (org-display-inline-images include-linked)
19583 (when (called-interactively-p 'interactive)
19584 (message (if org-inline-image-overlays
19585 (format "%d images displayed inline"
19586 (length org-inline-image-overlays))
19587 "No images to display inline")))))
19589 (defun org-redisplay-inline-images ()
19590 "Refresh the display of inline images."
19591 (interactive)
19592 (if (not org-inline-image-overlays)
19593 (org-toggle-inline-images)
19594 (org-toggle-inline-images)
19595 (org-toggle-inline-images)))
19597 (defun org-display-inline-images (&optional include-linked refresh beg end)
19598 "Display inline images.
19600 An inline image is a link which follows either of these
19601 conventions:
19603 1. Its path is a file with an extension matching return value
19604 from `image-file-name-regexp' and it has no contents.
19606 2. Its description consists in a single link of the previous
19607 type.
19609 When optional argument INCLUDE-LINKED is non-nil, also links with
19610 a text description part will be inlined. This can be nice for
19611 a quick look at those images, but it does not reflect what
19612 exported files will look like.
19614 When optional argument REFRESH is non-nil, refresh existing
19615 images between BEG and END. This will create new image displays
19616 only if necessary. BEG and END default to the buffer
19617 boundaries."
19618 (interactive "P")
19619 (when (display-graphic-p)
19620 (unless refresh
19621 (org-remove-inline-images)
19622 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19623 (org-with-wide-buffer
19624 (goto-char (or beg (point-min)))
19625 (let ((case-fold-search t)
19626 (file-extension-re (image-file-name-regexp)))
19627 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19628 (let ((link (save-match-data (org-element-context))))
19629 ;; Check if we're at an inline image.
19630 (when (and (equal (org-element-property :type link) "file")
19631 (or include-linked
19632 (not (org-element-property :contents-begin link)))
19633 (let ((parent (org-element-property :parent link)))
19634 (or (not (eq (org-element-type parent) 'link))
19635 (not (cdr (org-element-contents parent)))))
19636 (string-match-p file-extension-re
19637 (org-element-property :path link)))
19638 (let ((file (expand-file-name
19639 (org-link-unescape
19640 (org-element-property :path link)))))
19641 (when (file-exists-p file)
19642 (let ((width
19643 ;; Apply `org-image-actual-width' specifications.
19644 (cond
19645 ((not (image-type-available-p 'imagemagick)) nil)
19646 ((eq org-image-actual-width t) nil)
19647 ((listp org-image-actual-width)
19649 ;; First try to find a width among
19650 ;; attributes associated to the paragraph
19651 ;; containing link.
19652 (let ((paragraph
19653 (let ((e link))
19654 (while (and (setq e (org-element-property
19655 :parent e))
19656 (not (eq (org-element-type e)
19657 'paragraph))))
19658 e)))
19659 (when paragraph
19660 (save-excursion
19661 (goto-char (org-element-property :begin paragraph))
19662 (when
19663 (re-search-forward
19664 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19665 (org-element-property
19666 :post-affiliated paragraph)
19668 (string-to-number (match-string 1))))))
19669 ;; Otherwise, fall-back to provided number.
19670 (car org-image-actual-width)))
19671 ((numberp org-image-actual-width)
19672 org-image-actual-width)))
19673 (old (get-char-property-and-overlay
19674 (org-element-property :begin link)
19675 'org-image-overlay)))
19676 (if (and (car-safe old) refresh)
19677 (image-refresh (overlay-get (cdr old) 'display))
19678 (let ((image (create-image file
19679 (and width 'imagemagick)
19681 :width width)))
19682 (when image
19683 (let* ((link
19684 ;; If inline image is the description
19685 ;; of another link, be sure to
19686 ;; consider the latter as the one to
19687 ;; apply the overlay on.
19688 (let ((parent
19689 (org-element-property :parent link)))
19690 (if (eq (org-element-type parent) 'link)
19691 parent
19692 link)))
19693 (ov (make-overlay
19694 (org-element-property :begin link)
19695 (progn
19696 (goto-char
19697 (org-element-property :end link))
19698 (skip-chars-backward " \t")
19699 (point)))))
19700 (overlay-put ov 'display image)
19701 (overlay-put ov 'face 'default)
19702 (overlay-put ov 'org-image-overlay t)
19703 (overlay-put
19704 ov 'modification-hooks
19705 (list 'org-display-inline-remove-overlay))
19706 (push ov org-inline-image-overlays)))))))))))))))
19708 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19709 "Remove inline-display overlay if a corresponding region is modified."
19710 (let ((inhibit-modification-hooks t))
19711 (when (and ov after)
19712 (delete ov org-inline-image-overlays)
19713 (delete-overlay ov))))
19715 (defun org-remove-inline-images ()
19716 "Remove inline display of images."
19717 (interactive)
19718 (mapc #'delete-overlay org-inline-image-overlays)
19719 (setq org-inline-image-overlays nil))
19721 ;;;; Key bindings
19723 ;; Outline functions from `outline-mode-prefix-map'
19724 ;; that can be remapped in Org:
19725 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19726 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19727 (define-key org-mode-map [remap outline-forward-same-level]
19728 'org-forward-heading-same-level)
19729 (define-key org-mode-map [remap outline-backward-same-level]
19730 'org-backward-heading-same-level)
19731 (define-key org-mode-map [remap outline-show-branches]
19732 'org-kill-note-or-show-branches)
19733 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19734 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19735 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19736 (define-key org-mode-map [remap outline-next-visible-heading]
19737 'org-next-visible-heading)
19738 (define-key org-mode-map [remap outline-previous-visible-heading]
19739 'org-previous-visible-heading)
19740 (define-key org-mode-map [remap show-children] 'org-show-children)
19742 ;; Outline functions from `outline-mode-prefix-map' that can not
19743 ;; be remapped in Org:
19745 ;; - the column "key binding" shows whether the Outline function is still
19746 ;; available in Org mode on the same key that it has been bound to in
19747 ;; Outline mode:
19748 ;; - "overridden": key used for a different functionality in Org mode
19749 ;; - else: key still bound to the same Outline function in Org mode
19751 ;; | Outline function | key binding | Org replacement |
19752 ;; |------------------------------------+-------------+--------------------------|
19753 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19754 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19755 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19756 ;; | `show-entry' | overridden | no replacement |
19757 ;; | `show-branches' | `C-c C-k' | still same function |
19758 ;; | `show-subtree' | overridden | visibility cycling |
19759 ;; | `show-all' | overridden | no replacement |
19760 ;; | `hide-subtree' | overridden | visibility cycling |
19761 ;; | `hide-body' | overridden | no replacement |
19762 ;; | `hide-entry' | overridden | visibility cycling |
19763 ;; | `hide-leaves' | overridden | no replacement |
19764 ;; | `hide-sublevels' | overridden | no replacement |
19765 ;; | `hide-other' | overridden | no replacement |
19767 ;; Make `C-c C-x' a prefix key
19768 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19770 ;; TAB key with modifiers
19771 (org-defkey org-mode-map "\C-i" 'org-cycle)
19772 (org-defkey org-mode-map [(tab)] 'org-cycle)
19773 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19774 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19775 ;; The following line is necessary under Suse GNU/Linux
19776 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19777 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19778 (define-key org-mode-map [backtab] 'org-shifttab)
19780 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19781 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19782 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19784 ;; Cursor keys with modifiers
19785 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19786 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19787 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19788 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19790 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19791 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19792 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19793 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19794 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19795 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19797 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19798 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19799 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19800 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19802 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19803 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19804 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19805 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19807 ;; Babel keys
19808 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19809 (dolist (pair org-babel-key-bindings)
19810 (define-key org-babel-map (car pair) (cdr pair)))
19812 ;;; Extra keys for tty access.
19813 ;; We only set them when really needed because otherwise the
19814 ;; menus don't show the simple keys
19816 (when (or org-use-extra-keys (not window-system))
19817 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19818 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19819 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19820 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19821 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19822 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19823 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19824 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19825 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19826 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19827 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19828 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19829 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19830 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19831 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19832 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19833 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19834 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19835 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19836 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19837 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19838 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19839 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19840 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19841 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19842 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19843 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19844 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19846 ;; All the other keys
19848 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19849 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19850 (if (boundp 'narrow-map)
19851 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19852 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19853 (if (boundp 'narrow-map)
19854 (org-defkey narrow-map "b" 'org-narrow-to-block)
19855 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19856 (if (boundp 'narrow-map)
19857 (org-defkey narrow-map "e" 'org-narrow-to-element)
19858 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19859 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19860 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19861 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19862 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19863 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19864 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19865 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19866 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19867 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19868 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19869 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19870 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19871 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19872 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19873 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19874 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19875 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19876 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19877 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19878 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19879 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19880 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19881 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19882 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19883 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19884 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19885 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19886 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19887 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19888 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19889 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19890 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19891 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19892 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19893 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19894 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19895 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19896 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19897 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19898 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19899 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19900 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19901 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19902 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19903 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19904 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19905 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19906 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19907 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19908 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19909 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19910 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19911 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19912 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19913 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19914 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19915 (org-defkey org-mode-map "\C-c^" 'org-sort)
19916 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19917 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19918 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19919 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19920 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19921 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19922 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19923 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19924 (org-defkey org-mode-map "\C-m" 'org-return)
19925 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19926 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19927 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19928 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19929 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19930 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19931 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19932 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19933 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19934 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19935 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19936 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19937 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19938 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19939 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19940 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19941 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19942 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19943 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19944 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19945 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19946 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19947 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19948 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19949 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19951 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19952 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19953 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19955 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19956 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19957 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19958 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19959 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19960 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19961 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19962 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19963 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19964 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19965 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19966 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19967 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19968 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19969 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19970 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19971 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19972 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19973 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19974 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19975 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19976 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19978 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19979 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19980 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19981 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19982 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19984 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19986 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19988 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19989 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19991 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19994 (defconst org-speed-commands-default
19996 ("Outline Navigation")
19997 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19998 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19999 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20000 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20001 ("F" . org-next-block)
20002 ("B" . org-previous-block)
20003 ("u" . (org-speed-move-safe 'outline-up-heading))
20004 ("j" . org-goto)
20005 ("g" . (org-refile t))
20006 ("Outline Visibility")
20007 ("c" . org-cycle)
20008 ("C" . org-shifttab)
20009 (" " . org-display-outline-path)
20010 ("s" . org-narrow-to-subtree)
20011 ("=" . org-columns)
20012 ("Outline Structure Editing")
20013 ("U" . org-metaup)
20014 ("D" . org-metadown)
20015 ("r" . org-metaright)
20016 ("l" . org-metaleft)
20017 ("R" . org-shiftmetaright)
20018 ("L" . org-shiftmetaleft)
20019 ("i" . (progn (forward-char 1) (call-interactively
20020 'org-insert-heading-respect-content)))
20021 ("^" . org-sort)
20022 ("w" . org-refile)
20023 ("a" . org-archive-subtree-default-with-confirmation)
20024 ("@" . org-mark-subtree)
20025 ("#" . org-toggle-comment)
20026 ("Clock Commands")
20027 ("I" . org-clock-in)
20028 ("O" . org-clock-out)
20029 ("Meta Data Editing")
20030 ("t" . org-todo)
20031 ("," . (org-priority))
20032 ("0" . (org-priority ?\ ))
20033 ("1" . (org-priority ?A))
20034 ("2" . (org-priority ?B))
20035 ("3" . (org-priority ?C))
20036 (":" . org-set-tags-command)
20037 ("e" . org-set-effort)
20038 ("E" . org-inc-effort)
20039 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20040 (org-entry-put (point) "APPT_WARNTIME" m)))
20041 ("Agenda Views etc")
20042 ("v" . org-agenda)
20043 ("/" . org-sparse-tree)
20044 ("Misc")
20045 ("o" . org-open-at-point)
20046 ("?" . org-speed-command-help)
20047 ("<" . (org-agenda-set-restriction-lock 'subtree))
20048 (">" . (org-agenda-remove-restriction-lock))
20050 "The default speed commands.")
20052 (defun org-print-speed-command (e)
20053 (if (> (length (car e)) 1)
20054 (progn
20055 (princ "\n")
20056 (princ (car e))
20057 (princ "\n")
20058 (princ (make-string (length (car e)) ?-))
20059 (princ "\n"))
20060 (princ (car e))
20061 (princ " ")
20062 (if (symbolp (cdr e))
20063 (princ (symbol-name (cdr e)))
20064 (prin1 (cdr e)))
20065 (princ "\n")))
20067 (defun org-speed-command-help ()
20068 "Show the available speed commands."
20069 (interactive)
20070 (if (not org-use-speed-commands)
20071 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20072 (with-output-to-temp-buffer "*Help*"
20073 (princ "User-defined Speed commands\n===========================\n")
20074 (mapc #'org-print-speed-command org-speed-commands-user)
20075 (princ "\n")
20076 (princ "Built-in Speed commands\n=======================\n")
20077 (mapc #'org-print-speed-command org-speed-commands-default))
20078 (with-current-buffer "*Help*"
20079 (setq truncate-lines t))))
20081 (defun org-speed-move-safe (cmd)
20082 "Execute CMD, but make sure that the cursor always ends up in a headline.
20083 If not, return to the original position and throw an error."
20084 (interactive)
20085 (let ((pos (point)))
20086 (call-interactively cmd)
20087 (unless (and (bolp) (org-at-heading-p))
20088 (goto-char pos)
20089 (error "Boundary reached while executing %s" cmd))))
20091 (defvar org-self-insert-command-undo-counter 0)
20093 (defvar org-table-auto-blank-field) ; defined in org-table.el
20094 (defvar org-speed-command nil)
20096 (defun org-speed-command-activate (keys)
20097 "Hook for activating single-letter speed commands.
20098 `org-speed-commands-default' specifies a minimal command set.
20099 Use `org-speed-commands-user' for further customization."
20100 (when (or (and (bolp) (looking-at org-outline-regexp))
20101 (and (functionp org-use-speed-commands)
20102 (funcall org-use-speed-commands)))
20103 (cdr (assoc keys (append org-speed-commands-user
20104 org-speed-commands-default)))))
20106 (defun org-babel-speed-command-activate (keys)
20107 "Hook for activating single-letter code block commands."
20108 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20109 (cdr (assoc keys org-babel-key-bindings))))
20111 (defcustom org-speed-command-hook
20112 '(org-speed-command-default-hook org-babel-speed-command-hook)
20113 "Hook for activating speed commands at strategic locations.
20114 Hook functions are called in sequence until a valid handler is
20115 found.
20117 Each hook takes a single argument, a user-pressed command key
20118 which is also a `self-insert-command' from the global map.
20120 Within the hook, examine the cursor position and the command key
20121 and return nil or a valid handler as appropriate. Handler could
20122 be one of an interactive command, a function, or a form.
20124 Set `org-use-speed-commands' to non-nil value to enable this
20125 hook. The default setting is `org-speed-command-activate'."
20126 :group 'org-structure
20127 :version "24.1"
20128 :type 'hook)
20130 (defun org-self-insert-command (N)
20131 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20132 If the cursor is in a table looking at whitespace, the whitespace is
20133 overwritten, and the table is not marked as requiring realignment."
20134 (interactive "p")
20135 (org-check-before-invisible-edit 'insert)
20136 (cond
20137 ((and org-use-speed-commands
20138 (let ((kv (this-command-keys-vector)))
20139 (setq org-speed-command
20140 (run-hook-with-args-until-success
20141 'org-speed-command-hook
20142 (make-string 1 (aref kv (1- (length kv))))))))
20143 (cond
20144 ((commandp org-speed-command)
20145 (setq this-command org-speed-command)
20146 (call-interactively org-speed-command))
20147 ((functionp org-speed-command)
20148 (funcall org-speed-command))
20149 ((and org-speed-command (listp org-speed-command))
20150 (eval org-speed-command))
20151 (t (let (org-use-speed-commands)
20152 (call-interactively 'org-self-insert-command)))))
20153 ((and
20154 (org-at-table-p)
20155 (progn
20156 ;; Check if we blank the field, and if that triggers align.
20157 (and (featurep 'org-table) org-table-auto-blank-field
20158 (memq last-command
20159 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20160 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20161 ;; Got extra space, this field does not determine
20162 ;; column width.
20163 (let (org-table-may-need-update) (org-table-blank-field))
20164 ;; No extra space, this field may determine column
20165 ;; width.
20166 (org-table-blank-field)))
20168 (eq N 1)
20169 (looking-at "[^|\n]* \\( \\)|"))
20170 ;; There is room for insertion without re-aligning the table.
20171 (delete-region (match-beginning 1) (match-end 1))
20172 (self-insert-command N))
20174 (setq org-table-may-need-update t)
20175 (self-insert-command N)
20176 (org-fix-tags-on-the-fly)
20177 (when org-self-insert-cluster-for-undo
20178 (if (not (eq last-command 'org-self-insert-command))
20179 (setq org-self-insert-command-undo-counter 1)
20180 (if (>= org-self-insert-command-undo-counter 20)
20181 (setq org-self-insert-command-undo-counter 1)
20182 (and (> org-self-insert-command-undo-counter 0)
20183 buffer-undo-list (listp buffer-undo-list)
20184 (not (cadr buffer-undo-list)) ; remove nil entry
20185 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20186 (setq org-self-insert-command-undo-counter
20187 (1+ org-self-insert-command-undo-counter))))))))
20189 (defun org-check-before-invisible-edit (kind)
20190 "Check is editing if kind KIND would be dangerous with invisible text around.
20191 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20192 ;; First, try to get out of here as quickly as possible, to reduce overhead
20193 (when (and org-catch-invisible-edits
20194 (or (not (boundp 'visible-mode)) (not visible-mode))
20195 (or (get-char-property (point) 'invisible)
20196 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20197 ;; OK, we need to take a closer look. Do not consider
20198 ;; invisibility obtained through text properties (e.g., link
20199 ;; fontification), as it cannot be toggled.
20200 (let* ((invisible-at-point
20201 (pcase (get-char-property-and-overlay (point) 'invisible)
20202 (`(,_ . ,(and (pred overlayp) o)) o)))
20203 ;; Assume that point cannot land in the middle of an
20204 ;; overlay, or between two overlays.
20205 (invisible-before-point
20206 (and (not invisible-at-point)
20207 (not (bobp))
20208 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
20209 (`(,_ . ,(and (pred overlayp) o)) o))))
20210 (border-and-ok-direction
20212 ;; Check if we are acting predictably before invisible
20213 ;; text.
20214 (and invisible-at-point
20215 (memq kind '(insert delete-backward)))
20216 ;; Check if we are acting predictably after invisible text
20217 ;; This works not well, and I have turned it off. It seems
20218 ;; better to always show and stop after invisible text.
20219 ;; (and (not invisible-at-point) invisible-before-point
20220 ;; (memq kind '(insert delete)))
20222 (when (or invisible-at-point invisible-before-point)
20223 (when (eq org-catch-invisible-edits 'error)
20224 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20225 (if (and org-custom-properties-overlays
20226 (y-or-n-p "Display invisible properties in this buffer? "))
20227 (org-toggle-custom-properties-visibility)
20228 ;; Make the area visible
20229 (save-excursion
20230 (when invisible-before-point
20231 (goto-char
20232 (previous-single-char-property-change (point) 'invisible)))
20233 ;; Remove whatever overlay is currently making yet-to-be
20234 ;; edited text invisible. Also remove nested invisibility
20235 ;; related overlays.
20236 (delete-overlay (or invisible-at-point invisible-before-point))
20237 (let ((origin (if invisible-at-point (point) (1- (point)))))
20238 (while (pcase (get-char-property-and-overlay origin 'invisible)
20239 (`(,_ . ,(and (pred overlayp) o))
20240 (delete-overlay o)
20241 t)))))
20242 (cond
20243 ((eq org-catch-invisible-edits 'show)
20244 ;; That's it, we do the edit after showing
20245 (message
20246 "Unfolding invisible region around point before editing")
20247 (sit-for 1))
20248 ((and (eq org-catch-invisible-edits 'smart)
20249 border-and-ok-direction)
20250 (message "Unfolding invisible region around point before editing"))
20252 ;; Don't do the edit, make the user repeat it in full visibility
20253 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20255 (defun org-fix-tags-on-the-fly ()
20256 "Align tags in headline at point.
20257 Unlike to `org-set-tags', it ignores region and sorting."
20258 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20259 (org-at-heading-p))
20260 (let ((org-ignore-region t)
20261 (org-tags-sort-function nil))
20262 (org-set-tags nil t))))
20264 (defun org-delete-backward-char (N)
20265 "Like `delete-backward-char', insert whitespace at field end in tables.
20266 When deleting backwards, in tables this function will insert whitespace in
20267 front of the next \"|\" separator, to keep the table aligned. The table will
20268 still be marked for re-alignment if the field did fill the entire column,
20269 because, in this case the deletion might narrow the column."
20270 (interactive "p")
20271 (save-match-data
20272 (org-check-before-invisible-edit 'delete-backward)
20273 (if (and (org-at-table-p)
20274 (eq N 1)
20275 (string-match "|" (buffer-substring (point-at-bol) (point)))
20276 (looking-at ".*?|"))
20277 (let ((pos (point))
20278 (noalign (looking-at "[^|\n\r]* |"))
20279 (c org-table-may-need-update))
20280 (backward-delete-char N)
20281 (unless overwrite-mode
20282 (skip-chars-forward "^|")
20283 (insert " ")
20284 (goto-char (1- pos)))
20285 ;; noalign: if there were two spaces at the end, this field
20286 ;; does not determine the width of the column.
20287 (when noalign (setq org-table-may-need-update c)))
20288 (backward-delete-char N)
20289 (org-fix-tags-on-the-fly))))
20291 (defun org-delete-char (N)
20292 "Like `delete-char', but insert whitespace at field end in tables.
20293 When deleting characters, in tables this function will insert whitespace in
20294 front of the next \"|\" separator, to keep the table aligned. The table will
20295 still be marked for re-alignment if the field did fill the entire column,
20296 because, in this case the deletion might narrow the column."
20297 (interactive "p")
20298 (save-match-data
20299 (org-check-before-invisible-edit 'delete)
20300 (if (and (org-at-table-p)
20301 (not (bolp))
20302 (not (= (char-after) ?|))
20303 (eq N 1))
20304 (if (looking-at ".*?|")
20305 (let ((pos (point))
20306 (noalign (looking-at "[^|\n\r]* |"))
20307 (c org-table-may-need-update))
20308 (replace-match
20309 (concat (substring (match-string 0) 1 -1) " |") nil t)
20310 (goto-char pos)
20311 ;; noalign: if there were two spaces at the end, this field
20312 ;; does not determine the width of the column.
20313 (when noalign (setq org-table-may-need-update c)))
20314 (delete-char N))
20315 (delete-char N)
20316 (org-fix-tags-on-the-fly))))
20318 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20319 (put 'org-self-insert-command 'delete-selection
20320 (lambda ()
20321 (not (run-hook-with-args-until-success
20322 'self-insert-uses-region-functions))))
20323 (put 'orgtbl-self-insert-command 'delete-selection
20324 (lambda ()
20325 (not (run-hook-with-args-until-success
20326 'self-insert-uses-region-functions))))
20327 (put 'org-delete-char 'delete-selection 'supersede)
20328 (put 'org-delete-backward-char 'delete-selection 'supersede)
20329 (put 'org-yank 'delete-selection 'yank)
20331 ;; Make `flyspell-mode' delay after some commands
20332 (put 'org-self-insert-command 'flyspell-delayed t)
20333 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20334 (put 'org-delete-char 'flyspell-delayed t)
20335 (put 'org-delete-backward-char 'flyspell-delayed t)
20337 ;; Make pabbrev-mode expand after Org mode commands
20338 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20339 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20341 (defun org-remap (map &rest commands)
20342 "In MAP, remap the functions given in COMMANDS.
20343 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20344 (let (new old)
20345 (while commands
20346 (setq old (pop commands) new (pop commands))
20347 (org-defkey map (vector 'remap old) new))))
20349 (defun org-transpose-words ()
20350 "Transpose words for Org.
20351 This uses the `org-mode-transpose-word-syntax-table' syntax
20352 table, which interprets characters in `org-emphasis-alist' as
20353 word constituents."
20354 (interactive)
20355 (with-syntax-table org-mode-transpose-word-syntax-table
20356 (call-interactively 'transpose-words)))
20357 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20359 (when (eq org-enable-table-editor 'optimized)
20360 ;; If the user wants maximum table support, we need to hijack
20361 ;; some standard editing functions
20362 (org-remap org-mode-map
20363 'self-insert-command 'org-self-insert-command
20364 'delete-char 'org-delete-char
20365 'delete-backward-char 'org-delete-backward-char)
20366 (org-defkey org-mode-map "|" 'org-force-self-insert))
20368 (defvar org-ctrl-c-ctrl-c-hook nil
20369 "Hook for functions attaching themselves to `C-c C-c'.
20371 This can be used to add additional functionality to the C-c C-c
20372 key which executes context-dependent commands. This hook is run
20373 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20374 run after the last test.
20376 Each function will be called with no arguments. The function
20377 must check if the context is appropriate for it to act. If yes,
20378 it should do its thing and then return a non-nil value. If the
20379 context is wrong, just do nothing and return nil.")
20381 (defvar org-ctrl-c-ctrl-c-final-hook nil
20382 "Hook for functions attaching themselves to `C-c C-c'.
20384 This can be used to add additional functionality to the C-c C-c
20385 key which executes context-dependent commands. This hook is run
20386 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20387 before the first test.
20389 Each function will be called with no arguments. The function
20390 must check if the context is appropriate for it to act. If yes,
20391 it should do its thing and then return a non-nil value. If the
20392 context is wrong, just do nothing and return nil.")
20394 (defvar org-tab-first-hook nil
20395 "Hook for functions to attach themselves to TAB.
20396 See `org-ctrl-c-ctrl-c-hook' for more information.
20397 This hook runs as the first action when TAB is pressed, even before
20398 `org-cycle' messes around with the `outline-regexp' to cater for
20399 inline tasks and plain list item folding.
20400 If any function in this hook returns t, any other actions that
20401 would have been caused by TAB (such as table field motion or visibility
20402 cycling) will not occur.")
20404 (defvar org-tab-after-check-for-table-hook nil
20405 "Hook for functions to attach themselves to TAB.
20406 See `org-ctrl-c-ctrl-c-hook' for more information.
20407 This hook runs after it has been established that the cursor is not in a
20408 table, but before checking if the cursor is in a headline or if global cycling
20409 should be done.
20410 If any function in this hook returns t, not other actions like visibility
20411 cycling will be done.")
20413 (defvar org-tab-after-check-for-cycling-hook nil
20414 "Hook for functions to attach themselves to TAB.
20415 See `org-ctrl-c-ctrl-c-hook' for more information.
20416 This hook runs after it has been established that not table field motion and
20417 not visibility should be done because of current context. This is probably
20418 the place where a package like yasnippets can hook in.")
20420 (defvar org-tab-before-tab-emulation-hook nil
20421 "Hook for functions to attach themselves to TAB.
20422 See `org-ctrl-c-ctrl-c-hook' for more information.
20423 This hook runs after every other options for TAB have been exhausted, but
20424 before indentation and \t insertion takes place.")
20426 (defvar org-metaleft-hook nil
20427 "Hook for functions attaching themselves to `M-left'.
20428 See `org-ctrl-c-ctrl-c-hook' for more information.")
20429 (defvar org-metaright-hook nil
20430 "Hook for functions attaching themselves to `M-right'.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.")
20432 (defvar org-metaup-hook nil
20433 "Hook for functions attaching themselves to `M-up'.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.")
20435 (defvar org-metadown-hook nil
20436 "Hook for functions attaching themselves to `M-down'.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20438 (defvar org-shiftmetaleft-hook nil
20439 "Hook for functions attaching themselves to `M-S-left'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-shiftmetaright-hook nil
20442 "Hook for functions attaching themselves to `M-S-right'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-shiftmetaup-hook nil
20445 "Hook for functions attaching themselves to `M-S-up'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-shiftmetadown-hook nil
20448 "Hook for functions attaching themselves to `M-S-down'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-metareturn-hook nil
20451 "Hook for functions attaching themselves to `M-RET'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-shiftup-hook nil
20454 "Hook for functions attaching themselves to `S-up'.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.")
20456 (defvar org-shiftup-final-hook nil
20457 "Hook for functions attaching themselves to `S-up'.
20458 This one runs after all other options except shift-select have been excluded.
20459 See `org-ctrl-c-ctrl-c-hook' for more information.")
20460 (defvar org-shiftdown-hook nil
20461 "Hook for functions attaching themselves to `S-down'.
20462 See `org-ctrl-c-ctrl-c-hook' for more information.")
20463 (defvar org-shiftdown-final-hook nil
20464 "Hook for functions attaching themselves to `S-down'.
20465 This one runs after all other options except shift-select have been excluded.
20466 See `org-ctrl-c-ctrl-c-hook' for more information.")
20467 (defvar org-shiftleft-hook nil
20468 "Hook for functions attaching themselves to `S-left'.
20469 See `org-ctrl-c-ctrl-c-hook' for more information.")
20470 (defvar org-shiftleft-final-hook nil
20471 "Hook for functions attaching themselves to `S-left'.
20472 This one runs after all other options except shift-select have been excluded.
20473 See `org-ctrl-c-ctrl-c-hook' for more information.")
20474 (defvar org-shiftright-hook nil
20475 "Hook for functions attaching themselves to `S-right'.
20476 See `org-ctrl-c-ctrl-c-hook' for more information.")
20477 (defvar org-shiftright-final-hook nil
20478 "Hook for functions attaching themselves to `S-right'.
20479 This one runs after all other options except shift-select have been excluded.
20480 See `org-ctrl-c-ctrl-c-hook' for more information.")
20482 (defun org-modifier-cursor-error ()
20483 "Throw an error, a modified cursor command was applied in wrong context."
20484 (user-error "This command is active in special context like tables, headlines or items"))
20486 (defun org-shiftselect-error ()
20487 "Throw an error because Shift-Cursor command was applied in wrong context."
20488 (if (and (boundp 'shift-select-mode) shift-select-mode)
20489 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20490 (user-error "This command works only in special context like headlines or timestamps")))
20492 (defun org-call-for-shift-select (cmd)
20493 (let ((this-command-keys-shift-translated t))
20494 (call-interactively cmd)))
20496 (defun org-shifttab (&optional arg)
20497 "Global visibility cycling or move to previous table field.
20498 Call `org-table-previous-field' within a table.
20499 When ARG is nil, cycle globally through visibility states.
20500 When ARG is a numeric prefix, show contents of this level."
20501 (interactive "P")
20502 (cond
20503 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20504 ((integerp arg)
20505 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20506 (message "Content view to level: %d" arg)
20507 (org-content (prefix-numeric-value arg2))
20508 (org-cycle-show-empty-lines t)
20509 (setq org-cycle-global-status 'overview)))
20510 (t (call-interactively 'org-global-cycle))))
20512 (defun org-shiftmetaleft ()
20513 "Promote subtree or delete table column.
20514 Calls `org-promote-subtree', `org-outdent-item-tree', or
20515 `org-table-delete-column', depending on context. See the
20516 individual commands for more information."
20517 (interactive)
20518 (cond
20519 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20520 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20521 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20522 ((if (not (org-region-active-p)) (org-at-item-p)
20523 (save-excursion (goto-char (region-beginning))
20524 (org-at-item-p)))
20525 (call-interactively 'org-outdent-item-tree))
20526 (t (org-modifier-cursor-error))))
20528 (defun org-shiftmetaright ()
20529 "Demote subtree or insert table column.
20530 Calls `org-demote-subtree', `org-indent-item-tree', or
20531 `org-table-insert-column', depending on context. See the
20532 individual commands for more information."
20533 (interactive)
20534 (cond
20535 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20536 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20537 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20538 ((if (not (org-region-active-p)) (org-at-item-p)
20539 (save-excursion (goto-char (region-beginning))
20540 (org-at-item-p)))
20541 (call-interactively 'org-indent-item-tree))
20542 (t (org-modifier-cursor-error))))
20544 (defun org-shiftmetaup (&optional _arg)
20545 "Drag the line at point up.
20546 In a table, kill the current row.
20547 On a clock timestamp, update the value of the timestamp like `S-<up>'
20548 but also adjust the previous clocked item in the clock history.
20549 Everywhere else, drag the line at point up."
20550 (interactive "P")
20551 (cond
20552 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20553 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20554 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20555 (call-interactively 'org-timestamp-up)))
20556 (t (call-interactively 'org-drag-line-backward))))
20558 (defun org-shiftmetadown (&optional _arg)
20559 "Drag the line at point down.
20560 In a table, insert an empty row at the current line.
20561 On a clock timestamp, update the value of the timestamp like `S-<down>'
20562 but also adjust the previous clocked item in the clock history.
20563 Everywhere else, drag the line at point down."
20564 (interactive "P")
20565 (cond
20566 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20567 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20568 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20569 (call-interactively 'org-timestamp-down)))
20570 (t (call-interactively 'org-drag-line-forward))))
20572 (defsubst org-hidden-tree-error ()
20573 (user-error
20574 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20576 (defun org-metaleft (&optional _arg)
20577 "Promote heading, list item at point or move table column left.
20579 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20580 depending on context. With no specific context, calls the Emacs
20581 default `backward-word'. See the individual commands for more
20582 information.
20584 This function runs the hook `org-metaleft-hook' as a first step,
20585 and returns at first non-nil value."
20586 (interactive "P")
20587 (cond
20588 ((run-hook-with-args-until-success 'org-metaleft-hook))
20589 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20590 ((org-with-limited-levels
20591 (or (org-at-heading-p)
20592 (and (org-region-active-p)
20593 (save-excursion
20594 (goto-char (region-beginning))
20595 (org-at-heading-p)))))
20596 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20597 (call-interactively 'org-do-promote))
20598 ;; At an inline task.
20599 ((org-at-heading-p)
20600 (call-interactively 'org-inlinetask-promote))
20601 ((or (org-at-item-p)
20602 (and (org-region-active-p)
20603 (save-excursion
20604 (goto-char (region-beginning))
20605 (org-at-item-p))))
20606 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20607 (call-interactively 'org-outdent-item))
20608 (t (call-interactively 'backward-word))))
20610 (defun org-metaright (&optional _arg)
20611 "Demote heading, list item at point or move table column right.
20613 In front of a drawer or a block keyword, indent it correctly.
20615 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20616 `org-indent-drawer' or `org-indent-block' depending on context.
20617 With no specific context, calls the Emacs default `forward-word'.
20618 See the individual commands for more information.
20620 This function runs the hook `org-metaright-hook' as a first step,
20621 and returns at first non-nil value."
20622 (interactive "P")
20623 (cond
20624 ((run-hook-with-args-until-success 'org-metaright-hook))
20625 ((org-at-table-p) (call-interactively 'org-table-move-column))
20626 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20627 ((org-at-block-p) (call-interactively 'org-indent-block))
20628 ((org-with-limited-levels
20629 (or (org-at-heading-p)
20630 (and (org-region-active-p)
20631 (save-excursion
20632 (goto-char (region-beginning))
20633 (org-at-heading-p)))))
20634 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20635 (call-interactively 'org-do-demote))
20636 ;; At an inline task.
20637 ((org-at-heading-p)
20638 (call-interactively 'org-inlinetask-demote))
20639 ((or (org-at-item-p)
20640 (and (org-region-active-p)
20641 (save-excursion
20642 (goto-char (region-beginning))
20643 (org-at-item-p))))
20644 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20645 (call-interactively 'org-indent-item))
20646 (t (call-interactively 'forward-word))))
20648 (defun org-check-for-hidden (what)
20649 "Check if there are hidden headlines/items in the current visual line.
20650 WHAT can be either `headlines' or `items'. If the current line is
20651 an outline or item heading and it has a folded subtree below it,
20652 this function returns t, nil otherwise."
20653 (let ((re (cond
20654 ((eq what 'headlines) org-outline-regexp-bol)
20655 ((eq what 'items) (org-item-beginning-re))
20656 (t (error "This should not happen"))))
20657 beg end)
20658 (save-excursion
20659 (catch 'exit
20660 (unless (org-region-active-p)
20661 (setq beg (point-at-bol))
20662 (beginning-of-line 2)
20663 (while (and (not (eobp)) ;; this is like `next-line'
20664 (get-char-property (1- (point)) 'invisible))
20665 (beginning-of-line 2))
20666 (setq end (point))
20667 (goto-char beg)
20668 (goto-char (point-at-eol))
20669 (setq end (max end (point)))
20670 (while (re-search-forward re end t)
20671 (when (get-char-property (match-beginning 0) 'invisible)
20672 (throw 'exit t))))
20673 nil))))
20675 (defun org-metaup (&optional _arg)
20676 "Move subtree up or move table row up.
20677 Calls `org-move-subtree-up' or `org-table-move-row' or
20678 `org-move-item-up', depending on context. See the individual commands
20679 for more information."
20680 (interactive "P")
20681 (cond
20682 ((run-hook-with-args-until-success 'org-metaup-hook))
20683 ((org-region-active-p)
20684 (let* ((a (min (region-beginning) (region-end)))
20685 (b (1- (max (region-beginning) (region-end))))
20686 (c (save-excursion (goto-char a)
20687 (move-beginning-of-line 0)))
20688 (d (save-excursion (goto-char a)
20689 (move-end-of-line 0) (point))))
20690 (transpose-regions a b c d)
20691 (goto-char c)))
20692 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20693 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20694 ((org-at-item-p) (call-interactively 'org-move-item-up))
20695 (t (org-drag-element-backward))))
20697 (defun org-metadown (&optional _arg)
20698 "Move subtree down or move table row down.
20699 Calls `org-move-subtree-down' or `org-table-move-row' or
20700 `org-move-item-down', depending on context. See the individual
20701 commands for more information."
20702 (interactive "P")
20703 (cond
20704 ((run-hook-with-args-until-success 'org-metadown-hook))
20705 ((org-region-active-p)
20706 (let* ((a (min (region-beginning) (region-end)))
20707 (b (max (region-beginning) (region-end)))
20708 (c (save-excursion (goto-char b)
20709 (move-beginning-of-line 1)))
20710 (d (save-excursion (goto-char b)
20711 (move-end-of-line 1) (1+ (point)))))
20712 (transpose-regions a b c d)
20713 (goto-char d)))
20714 ((org-at-table-p) (call-interactively 'org-table-move-row))
20715 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20716 ((org-at-item-p) (call-interactively 'org-move-item-down))
20717 (t (org-drag-element-forward))))
20719 (defun org-shiftup (&optional arg)
20720 "Increase item in timestamp or increase priority of current headline.
20721 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20722 depending on context. See the individual commands for more information."
20723 (interactive "P")
20724 (cond
20725 ((run-hook-with-args-until-success 'org-shiftup-hook))
20726 ((and org-support-shift-select (org-region-active-p))
20727 (org-call-for-shift-select 'previous-line))
20728 ((org-at-timestamp-p t)
20729 (call-interactively (if org-edit-timestamp-down-means-later
20730 'org-timestamp-down 'org-timestamp-up)))
20731 ((and (not (eq org-support-shift-select 'always))
20732 org-enable-priority-commands
20733 (org-at-heading-p))
20734 (call-interactively 'org-priority-up))
20735 ((and (not org-support-shift-select) (org-at-item-p))
20736 (call-interactively 'org-previous-item))
20737 ((org-clocktable-try-shift 'up arg))
20738 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20739 (org-support-shift-select
20740 (org-call-for-shift-select 'previous-line))
20741 (t (org-shiftselect-error))))
20743 (defun org-shiftdown (&optional arg)
20744 "Decrease item in timestamp or decrease priority of current headline.
20745 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20746 depending on context. See the individual commands for more information."
20747 (interactive "P")
20748 (cond
20749 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20750 ((and org-support-shift-select (org-region-active-p))
20751 (org-call-for-shift-select 'next-line))
20752 ((org-at-timestamp-p t)
20753 (call-interactively (if org-edit-timestamp-down-means-later
20754 'org-timestamp-up 'org-timestamp-down)))
20755 ((and (not (eq org-support-shift-select 'always))
20756 org-enable-priority-commands
20757 (org-at-heading-p))
20758 (call-interactively 'org-priority-down))
20759 ((and (not org-support-shift-select) (org-at-item-p))
20760 (call-interactively 'org-next-item))
20761 ((org-clocktable-try-shift 'down arg))
20762 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20763 (org-support-shift-select
20764 (org-call-for-shift-select 'next-line))
20765 (t (org-shiftselect-error))))
20767 (defun org-shiftright (&optional arg)
20768 "Cycle the thing at point or in the current line, depending on context.
20769 Depending on context, this does one of the following:
20771 - switch a timestamp at point one day into the future
20772 - on a headline, switch to the next TODO keyword.
20773 - on an item, switch entire list to the next bullet type
20774 - on a property line, switch to the next allowed value
20775 - on a clocktable definition line, move time block into the future"
20776 (interactive "P")
20777 (cond
20778 ((run-hook-with-args-until-success 'org-shiftright-hook))
20779 ((and org-support-shift-select (org-region-active-p))
20780 (org-call-for-shift-select 'forward-char))
20781 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20782 ((and (not (eq org-support-shift-select 'always))
20783 (org-at-heading-p))
20784 (let ((org-inhibit-logging
20785 (not org-treat-S-cursor-todo-selection-as-state-change))
20786 (org-inhibit-blocking
20787 (not org-treat-S-cursor-todo-selection-as-state-change)))
20788 (org-call-with-arg 'org-todo 'right)))
20789 ((or (and org-support-shift-select
20790 (not (eq org-support-shift-select 'always))
20791 (org-at-item-bullet-p))
20792 (and (not org-support-shift-select) (org-at-item-p)))
20793 (org-call-with-arg 'org-cycle-list-bullet nil))
20794 ((and (not (eq org-support-shift-select 'always))
20795 (org-at-property-p))
20796 (call-interactively 'org-property-next-allowed-value))
20797 ((org-clocktable-try-shift 'right arg))
20798 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20799 (org-support-shift-select
20800 (org-call-for-shift-select 'forward-char))
20801 (t (org-shiftselect-error))))
20803 (defun org-shiftleft (&optional arg)
20804 "Cycle the thing at point or in the current line, depending on context.
20805 Depending on context, this does one of the following:
20807 - switch a timestamp at point one day into the past
20808 - on a headline, switch to the previous TODO keyword.
20809 - on an item, switch entire list to the previous bullet type
20810 - on a property line, switch to the previous allowed value
20811 - on a clocktable definition line, move time block into the past"
20812 (interactive "P")
20813 (cond
20814 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20815 ((and org-support-shift-select (org-region-active-p))
20816 (org-call-for-shift-select 'backward-char))
20817 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20818 ((and (not (eq org-support-shift-select 'always))
20819 (org-at-heading-p))
20820 (let ((org-inhibit-logging
20821 (not org-treat-S-cursor-todo-selection-as-state-change))
20822 (org-inhibit-blocking
20823 (not org-treat-S-cursor-todo-selection-as-state-change)))
20824 (org-call-with-arg 'org-todo 'left)))
20825 ((or (and org-support-shift-select
20826 (not (eq org-support-shift-select 'always))
20827 (org-at-item-bullet-p))
20828 (and (not org-support-shift-select) (org-at-item-p)))
20829 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20830 ((and (not (eq org-support-shift-select 'always))
20831 (org-at-property-p))
20832 (call-interactively 'org-property-previous-allowed-value))
20833 ((org-clocktable-try-shift 'left arg))
20834 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20835 (org-support-shift-select
20836 (org-call-for-shift-select 'backward-char))
20837 (t (org-shiftselect-error))))
20839 (defun org-shiftcontrolright ()
20840 "Switch to next TODO set."
20841 (interactive)
20842 (cond
20843 ((and org-support-shift-select (org-region-active-p))
20844 (org-call-for-shift-select 'forward-word))
20845 ((and (not (eq org-support-shift-select 'always))
20846 (org-at-heading-p))
20847 (org-call-with-arg 'org-todo 'nextset))
20848 (org-support-shift-select
20849 (org-call-for-shift-select 'forward-word))
20850 (t (org-shiftselect-error))))
20852 (defun org-shiftcontrolleft ()
20853 "Switch to previous TODO set."
20854 (interactive)
20855 (cond
20856 ((and org-support-shift-select (org-region-active-p))
20857 (org-call-for-shift-select 'backward-word))
20858 ((and (not (eq org-support-shift-select 'always))
20859 (org-at-heading-p))
20860 (org-call-with-arg 'org-todo 'previousset))
20861 (org-support-shift-select
20862 (org-call-for-shift-select 'backward-word))
20863 (t (org-shiftselect-error))))
20865 (defun org-shiftcontrolup (&optional n)
20866 "Change timestamps synchronously up in CLOCK log lines.
20867 Optional argument N tells to change by that many units."
20868 (interactive "P")
20869 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20870 (let (org-support-shift-select)
20871 (org-clock-timestamps-up n))
20872 (user-error "Not at a clock log")))
20874 (defun org-shiftcontroldown (&optional n)
20875 "Change timestamps synchronously down in CLOCK log lines.
20876 Optional argument N tells to change by that many units."
20877 (interactive "P")
20878 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20879 (let (org-support-shift-select)
20880 (org-clock-timestamps-down n))
20881 (user-error "Not at a clock log")))
20883 (defun org-increase-number-at-point (&optional inc)
20884 "Increment the number at point.
20885 With an optional prefix numeric argument INC, increment using
20886 this numeric value."
20887 (interactive "p")
20888 (if (not (number-at-point))
20889 (user-error "Not on a number")
20890 (unless inc (setq inc 1))
20891 (let ((pos (point))
20892 (beg (skip-chars-backward "-+^/*0-9eE."))
20893 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20894 (setq nap (buffer-substring-no-properties
20895 (+ pos beg) (+ pos beg end)))
20896 (delete-region (+ pos beg) (+ pos beg end))
20897 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20898 (when (org-at-table-p)
20899 (org-table-align)
20900 (org-table-end-of-field 1))))
20902 (defun org-decrease-number-at-point (&optional inc)
20903 "Decrement the number at point.
20904 With an optional prefix numeric argument INC, decrement using
20905 this numeric value."
20906 (interactive "p")
20907 (org-increase-number-at-point (- (or inc 1))))
20909 (defun org-ctrl-c-ret ()
20910 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20911 (interactive)
20912 (cond
20913 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20914 (t (call-interactively 'org-insert-heading))))
20916 (defun org-find-visible ()
20917 (let ((s (point)))
20918 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20919 (get-char-property s 'invisible)))
20921 (defun org-find-invisible ()
20922 (let ((s (point)))
20923 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20924 (not (get-char-property s 'invisible))))
20927 (defun org-copy-visible (beg end)
20928 "Copy the visible parts of the region."
20929 (interactive "r")
20930 (let (snippets s)
20931 (save-excursion
20932 (save-restriction
20933 (narrow-to-region beg end)
20934 (setq s (goto-char (point-min)))
20935 (while (not (= (point) (point-max)))
20936 (goto-char (org-find-invisible))
20937 (push (buffer-substring s (point)) snippets)
20938 (setq s (goto-char (org-find-visible))))))
20939 (kill-new (apply 'concat (nreverse snippets)))))
20941 (defun org-copy-special ()
20942 "Copy region in table or copy current subtree.
20943 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20944 context. See the individual commands for more information."
20945 (interactive)
20946 (call-interactively
20947 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20949 (defun org-cut-special ()
20950 "Cut region in table or cut current subtree.
20951 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20952 context. See the individual commands for more information."
20953 (interactive)
20954 (call-interactively
20955 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20957 (defun org-paste-special (arg)
20958 "Paste rectangular region into table, or past subtree relative to level.
20959 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20960 See the individual commands for more information."
20961 (interactive "P")
20962 (if (org-at-table-p)
20963 (org-table-paste-rectangle)
20964 (org-paste-subtree arg)))
20966 (defun org-edit-special (&optional arg)
20967 "Call a special editor for the element at point.
20968 When at a table, call the formula editor with `org-table-edit-formulas'.
20969 When in a source code block, call `org-edit-src-code'.
20970 When in a fixed-width region, call `org-edit-fixed-width-region'.
20971 When in an export block, call `org-edit-export-block'.
20972 When at an #+INCLUDE keyword, visit the included file.
20973 When at a footnote reference, call `org-edit-footnote-reference'
20974 On a link, call `ffap' to visit the link at point.
20975 Otherwise, return a user error."
20976 (interactive "P")
20977 (let ((element (org-element-at-point)))
20978 (barf-if-buffer-read-only)
20979 (pcase (org-element-type element)
20980 (`src-block
20981 (if (not arg) (org-edit-src-code)
20982 (let* ((info (org-babel-get-src-block-info))
20983 (lang (nth 0 info))
20984 (params (nth 2 info))
20985 (session (cdr (assq :session params))))
20986 (if (not session) (org-edit-src-code)
20987 ;; At a src-block with a session and function called with
20988 ;; an ARG: switch to the buffer related to the inferior
20989 ;; process.
20990 (switch-to-buffer
20991 (funcall (intern (concat "org-babel-prep-session:" lang))
20992 session params))))))
20993 (`keyword
20994 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20995 (org-open-link-from-string
20996 (format "[[%s]]"
20997 (expand-file-name
20998 (let ((value (org-element-property :value element)))
20999 (cond ((not (org-string-nw-p value))
21000 (user-error "No file to edit"))
21001 ((string-match "\\`\"\\(.*?\\)\"" value)
21002 (match-string 1 value))
21003 ((string-match "\\`[^ \t\"]\\S-*" value)
21004 (match-string 0 value))
21005 (t (user-error "No valid file specified")))))))
21006 (user-error "No special environment to edit here")))
21007 (`table
21008 (if (eq (org-element-property :type element) 'table.el)
21009 (org-edit-table.el)
21010 (call-interactively 'org-table-edit-formulas)))
21011 ;; Only Org tables contain `table-row' type elements.
21012 (`table-row (call-interactively 'org-table-edit-formulas))
21013 (`example-block (org-edit-src-code))
21014 (`export-block (org-edit-export-block))
21015 (`fixed-width (org-edit-fixed-width-region))
21017 ;; No notable element at point. Though, we may be at a link or
21018 ;; a footnote reference, which are objects. Thus, scan deeper.
21019 (let ((context (org-element-context element)))
21020 (pcase (org-element-type context)
21021 (`footnote-reference (org-edit-footnote-reference))
21022 (`inline-src-block (org-edit-inline-src-code))
21023 (`link (call-interactively #'ffap))
21024 (_ (user-error "No special environment to edit here"))))))))
21026 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21027 (defun org-ctrl-c-ctrl-c (&optional arg)
21028 "Set tags in headline, or update according to changed information at point.
21030 This command does many different things, depending on context:
21032 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21033 this is what we do.
21035 - If the cursor is on a statistics cookie, update it.
21037 - If the cursor is in a headline, prompt for tags and insert them
21038 into the current line, aligned to `org-tags-column'. When called
21039 with prefix arg, realign all tags in the current buffer.
21041 - If the cursor is in one of the special #+KEYWORD lines, this
21042 triggers scanning the buffer for these lines and updating the
21043 information.
21045 - If the cursor is inside a table, realign the table. This command
21046 works even if the automatic table editor has been turned off.
21048 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21049 the entire table.
21051 - If the cursor is at a footnote reference or definition, jump to
21052 the corresponding definition or references, respectively.
21054 - If the cursor is a the beginning of a dynamic block, update it.
21056 - If the current buffer is a capture buffer, close note and file it.
21058 - If the cursor is on a <<<target>>>, update radio targets and
21059 corresponding links in this buffer.
21061 - If the cursor is on a numbered item in a plain list, renumber the
21062 ordered list.
21064 - If the cursor is on a checkbox, toggle it.
21066 - If the cursor is on a code block, evaluate it. The variable
21067 `org-confirm-babel-evaluate' can be used to control prompting
21068 before code block evaluation, by default every code block
21069 evaluation requires confirmation. Code block evaluation can be
21070 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21071 (interactive "P")
21072 (cond
21073 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21074 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21075 (org-remove-occur-highlights)
21076 (message "Temporary highlights/overlays removed from current buffer"))
21077 ((and (local-variable-p 'org-finish-function)
21078 (fboundp org-finish-function))
21079 (funcall org-finish-function))
21080 ((org-babel-hash-at-point))
21081 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21083 (let* ((context
21084 (org-element-lineage
21085 (org-element-context)
21086 ;; Limit to supported contexts.
21087 '(babel-call clock dynamic-block footnote-definition
21088 footnote-reference inline-babel-call inline-src-block
21089 inlinetask item keyword node-property paragraph
21090 plain-list property-drawer radio-target src-block
21091 statistics-cookie table table-cell table-row
21092 timestamp)
21094 (type (org-element-type context)))
21095 ;; For convenience: at the first line of a paragraph on the same
21096 ;; line as an item, apply function on that item instead.
21097 (when (eq type 'paragraph)
21098 (let ((parent (org-element-property :parent context)))
21099 (when (and (eq (org-element-type parent) 'item)
21100 (= (line-beginning-position)
21101 (org-element-property :begin parent)))
21102 (setq context parent)
21103 (setq type 'item))))
21104 ;; Act according to type of element or object at point.
21106 ;; Do nothing on a blank line, except if it is contained in
21107 ;; a src block. Hence, we first check if point is in such
21108 ;; a block and then if it is at a blank line.
21109 (pcase type
21110 ((or `inline-src-block `src-block)
21111 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21112 (org-babel-eval-wipe-error-buffer)
21113 (org-babel-execute-src-block
21114 current-prefix-arg (org-babel-get-src-block-info nil context))))
21115 ((guard (org-match-line "[ \t]*$"))
21116 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21117 (user-error
21118 (substitute-command-keys
21119 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21120 ((or `babel-call `inline-babel-call)
21121 (let ((info (org-babel-lob-get-info context)))
21122 (when info (org-babel-execute-src-block nil info))))
21123 (`clock (org-clock-update-time-maybe))
21124 (`dynamic-block
21125 (save-excursion
21126 (goto-char (org-element-property :post-affiliated context))
21127 (org-update-dblock)))
21128 (`footnote-definition
21129 (goto-char (org-element-property :post-affiliated context))
21130 (call-interactively 'org-footnote-action))
21131 (`footnote-reference (call-interactively #'org-footnote-action))
21132 ((or `headline `inlinetask)
21133 (save-excursion (goto-char (org-element-property :begin context))
21134 (call-interactively #'org-set-tags)))
21135 (`item
21136 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21137 ;; unconditionally, whereas `C-u' will toggle its presence.
21138 ;; Without a universal argument, if the item has a checkbox,
21139 ;; toggle it. Otherwise repair the list.
21140 (let* ((box (org-element-property :checkbox context))
21141 (struct (org-element-property :structure context))
21142 (old-struct (copy-tree struct))
21143 (parents (org-list-parents-alist struct))
21144 (prevs (org-list-prevs-alist struct))
21145 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21146 (org-list-set-checkbox
21147 (org-element-property :begin context) struct
21148 (cond ((equal arg '(16)) "[-]")
21149 ((and (not box) (equal arg '(4))) "[ ]")
21150 ((or (not box) (equal arg '(4))) nil)
21151 ((eq box 'on) "[ ]")
21152 (t "[X]")))
21153 ;; Mimic `org-list-write-struct' but with grabbing a return
21154 ;; value from `org-list-struct-fix-box'.
21155 (org-list-struct-fix-ind struct parents 2)
21156 (org-list-struct-fix-item-end struct)
21157 (org-list-struct-fix-bul struct prevs)
21158 (org-list-struct-fix-ind struct parents)
21159 (let ((block-item
21160 (org-list-struct-fix-box struct parents prevs orderedp)))
21161 (if (and box (equal struct old-struct))
21162 (if (equal arg '(16))
21163 (message "Checkboxes already reset")
21164 (user-error "Cannot toggle this checkbox: %s"
21165 (if (eq box 'on)
21166 "all subitems checked"
21167 "unchecked subitems")))
21168 (org-list-struct-apply-struct struct old-struct)
21169 (org-update-checkbox-count-maybe))
21170 (when block-item
21171 (message "Checkboxes were removed due to empty box at line %d"
21172 (org-current-line block-item))))))
21173 (`keyword
21174 (let ((org-inhibit-startup-visibility-stuff t)
21175 (org-startup-align-all-tables nil))
21176 (when (boundp 'org-table-coordinate-overlays)
21177 (mapc #'delete-overlay org-table-coordinate-overlays)
21178 (setq org-table-coordinate-overlays nil))
21179 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21180 (message "Local setup has been refreshed"))
21181 (`plain-list
21182 ;; At a plain list, with a double C-u argument, set
21183 ;; checkboxes of each item to "[-]", whereas a single one
21184 ;; will toggle their presence according to the state of the
21185 ;; first item in the list. Without an argument, repair the
21186 ;; list.
21187 (let* ((begin (org-element-property :contents-begin context))
21188 (beginm (move-marker (make-marker) begin))
21189 (struct (org-element-property :structure context))
21190 (old-struct (copy-tree struct))
21191 (first-box (save-excursion
21192 (goto-char begin)
21193 (looking-at org-list-full-item-re)
21194 (match-string-no-properties 3)))
21195 (new-box (cond ((equal arg '(16)) "[-]")
21196 ((equal arg '(4)) (unless first-box "[ ]"))
21197 ((equal first-box "[X]") "[ ]")
21198 (t "[X]"))))
21199 (cond
21200 (arg
21201 (dolist (pos
21202 (org-list-get-all-items
21203 begin struct (org-list-prevs-alist struct)))
21204 (org-list-set-checkbox pos struct new-box)))
21205 ((and first-box (eq (point) begin))
21206 ;; For convenience, when point is at bol on the first
21207 ;; item of the list and no argument is provided, simply
21208 ;; toggle checkbox of that item, if any.
21209 (org-list-set-checkbox begin struct new-box)))
21210 (org-list-write-struct
21211 struct (org-list-parents-alist struct) old-struct)
21212 (org-update-checkbox-count-maybe)
21213 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21214 ((or `property-drawer `node-property)
21215 (call-interactively #'org-property-action))
21216 (`radio-target
21217 (call-interactively #'org-update-radio-target-regexp))
21218 (`statistics-cookie
21219 (call-interactively #'org-update-statistics-cookies))
21220 ((or `table `table-cell `table-row)
21221 ;; At a table, recalculate every field and align it. Also
21222 ;; send the table if necessary. If the table has
21223 ;; a `table.el' type, just give up. At a table row or cell,
21224 ;; maybe recalculate line but always align table.
21225 (if (eq (org-element-property :type context) 'table.el)
21226 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21227 Use `\\[org-edit-special]' to edit table.el tables"))
21228 (let ((org-enable-table-editor t))
21229 (if (or (eq type 'table)
21230 ;; Check if point is at a TBLFM line.
21231 (and (eq type 'table-row)
21232 (= (point) (org-element-property :end context))))
21233 (save-excursion
21234 (if (org-at-TBLFM-p)
21235 (progn (require 'org-table)
21236 (org-table-calc-current-TBLFM))
21237 (goto-char (org-element-property :contents-begin context))
21238 (org-call-with-arg 'org-table-recalculate (or arg t))
21239 (orgtbl-send-table 'maybe)))
21240 (org-table-maybe-eval-formula)
21241 (cond (arg (call-interactively #'org-table-recalculate))
21242 ((org-table-maybe-recalculate-line))
21243 (t (org-table-align)))))))
21244 (`timestamp (org-timestamp-change 0 'day))
21245 ((and `nil (guard (org-at-heading-p)))
21246 ;; When point is on an unsupported object type, we can miss
21247 ;; the fact that it also is at a heading. Handle it here.
21248 (call-interactively #'org-set-tags))
21249 ((guard
21250 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21252 (user-error
21253 (substitute-command-keys
21254 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21256 (defun org-mode-restart ()
21257 (interactive)
21258 (let ((indent-status (bound-and-true-p org-indent-mode)))
21259 (funcall major-mode)
21260 (hack-local-variables)
21261 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21262 (org-indent-mode -1)))
21263 (message "%s restarted" major-mode))
21265 (defun org-kill-note-or-show-branches ()
21266 "Abort storing current note, or call `outline-show-branches'."
21267 (interactive)
21268 (if (not org-finish-function)
21269 (progn
21270 (outline-hide-subtree)
21271 (call-interactively 'outline-show-branches))
21272 (let ((org-note-abort t))
21273 (funcall org-finish-function))))
21275 (defun org-delete-indentation (&optional arg)
21276 "Join current line to previous and fix whitespace at join.
21278 If previous line is a headline add to headline title. Otherwise
21279 the function calls `delete-indentation'.
21281 With a non-nil optional argument, join it to the following one."
21282 (interactive "*P")
21283 (if (save-excursion
21284 (beginning-of-line (if arg 1 0))
21285 (let ((case-fold-search nil))
21286 (looking-at org-complex-heading-regexp)))
21287 ;; At headline.
21288 (let ((tags-column (when (match-beginning 5)
21289 (save-excursion (goto-char (match-beginning 5))
21290 (current-column))))
21291 (string (concat " " (progn (when arg (forward-line 1))
21292 (org-trim (delete-and-extract-region
21293 (line-beginning-position)
21294 (line-end-position)))))))
21295 (unless (bobp) (delete-region (point) (1- (point))))
21296 (goto-char (or (match-end 4)
21297 (match-beginning 5)
21298 (match-end 0)))
21299 (skip-chars-backward " \t")
21300 (save-excursion (insert string))
21301 ;; Adjust alignment of tags.
21302 (cond
21303 ((not tags-column)) ;no tags
21304 (org-auto-align-tags (org-set-tags nil t))
21305 (t (org--align-tags-here tags-column)))) ;preserve tags column
21306 (delete-indentation arg)))
21308 (defun org-open-line (n)
21309 "Insert a new row in tables, call `open-line' elsewhere.
21310 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21311 As a special case, when a document starts with a table, allow to
21312 call `open-line' on the very first character."
21313 (interactive "*p")
21314 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21315 (org-table-insert-row)
21316 (open-line n)))
21318 (defun org-return (&optional indent)
21319 "Goto next table row or insert a newline.
21321 Calls `org-table-next-row' or `newline', depending on context.
21323 When optional INDENT argument is non-nil, call
21324 `newline-and-indent' instead of `newline'.
21326 When `org-return-follows-link' is non-nil and point is on
21327 a timestamp or a link, call `org-open-at-point'. However, it
21328 will not happen if point is in a table or on a \"dead\"
21329 object (e.g., within a comment). In these case, you need to use
21330 `org-open-at-point' directly."
21331 (interactive)
21332 (let ((context (if org-return-follows-link (org-element-context)
21333 (org-element-at-point))))
21334 (cond
21335 ;; In a table, call `org-table-next-row'.
21336 ((or (and (eq (org-element-type context) 'table)
21337 (>= (point) (org-element-property :contents-begin context))
21338 (< (point) (org-element-property :contents-end context)))
21339 (org-element-lineage context '(table-row table-cell) t))
21340 (org-table-justify-field-maybe)
21341 (call-interactively #'org-table-next-row))
21342 ;; On a link or a timestamp, call `org-open-at-point' if
21343 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21344 ;; locations, e.g., in a comment, as `org-open-at-point'.
21345 ((and org-return-follows-link
21346 (or (org-in-regexp org-ts-regexp-both nil t)
21347 (org-in-regexp org-tsr-regexp-both nil t)
21348 (org-in-regexp org-any-link-re nil t)))
21349 (call-interactively #'org-open-at-point))
21350 ;; Insert newline in heading, but preserve tags.
21351 ((and (not (bolp))
21352 (save-excursion (beginning-of-line)
21353 (let ((case-fold-search nil))
21354 (looking-at org-complex-heading-regexp))))
21355 ;; At headline. Split line. However, if point is on keyword,
21356 ;; priority cookie or tags, do not break any of them: add
21357 ;; a newline after the headline instead.
21358 (let ((tags-column (and (match-beginning 5)
21359 (save-excursion (goto-char (match-beginning 5))
21360 (current-column))))
21361 (string
21362 (when (and (match-end 4) (org-point-in-group (point) 4))
21363 (delete-and-extract-region (point) (match-end 4)))))
21364 ;; Adjust tag alignment.
21365 (cond
21366 ((not (and tags-column string)))
21367 (org-auto-align-tags (org-set-tags nil t))
21368 (t (org--align-tags-here tags-column))) ;preserve tags column
21369 (end-of-line)
21370 (org-show-entry)
21371 (if indent (newline-and-indent) (newline))
21372 (when string (save-excursion (insert (org-trim string))))))
21373 ;; In a list, make sure indenting keeps trailing text within.
21374 ((and indent
21375 (not (eolp))
21376 (org-element-lineage context '(item)))
21377 (let ((trailing-data
21378 (delete-and-extract-region (point) (line-end-position))))
21379 (newline-and-indent)
21380 (save-excursion (insert trailing-data))))
21381 (t (if indent (newline-and-indent) (newline))))))
21383 (defun org-return-indent ()
21384 "Goto next table row or insert a newline and indent.
21385 Calls `org-table-next-row' or `newline-and-indent', depending on
21386 context. See the individual commands for more information."
21387 (interactive)
21388 (org-return t))
21390 (defun org-ctrl-c-star ()
21391 "Compute table, or change heading status of lines.
21392 Calls `org-table-recalculate' or `org-toggle-heading',
21393 depending on context."
21394 (interactive)
21395 (cond
21396 ((org-at-table-p)
21397 (call-interactively 'org-table-recalculate))
21399 ;; Convert all lines in region to list items
21400 (call-interactively 'org-toggle-heading))))
21402 (defun org-ctrl-c-minus ()
21403 "Insert separator line in table or modify bullet status of line.
21404 Also turns a plain line or a region of lines into list items.
21405 Calls `org-table-insert-hline', `org-toggle-item', or
21406 `org-cycle-list-bullet', depending on context."
21407 (interactive)
21408 (cond
21409 ((org-at-table-p)
21410 (call-interactively 'org-table-insert-hline))
21411 ((org-region-active-p)
21412 (call-interactively 'org-toggle-item))
21413 ((org-in-item-p)
21414 (call-interactively 'org-cycle-list-bullet))
21416 (call-interactively 'org-toggle-item))))
21418 (defun org-toggle-heading (&optional nstars)
21419 "Convert headings to normal text, or items or text to headings.
21420 If there is no active region, only convert the current line.
21422 With a `\\[universal-argument]' prefix, convert the whole list at
21423 point into heading.
21425 In a region:
21427 - If the first non blank line is a headline, remove the stars
21428 from all headlines in the region.
21430 - If it is a normal line, turn each and every normal line (i.e.,
21431 not an heading or an item) in the region into headings. If you
21432 want to convert only the first line of this region, use one
21433 universal prefix argument.
21435 - If it is a plain list item, turn all plain list items into headings.
21437 When converting a line into a heading, the number of stars is chosen
21438 such that the lines become children of the current entry. However,
21439 when a numeric prefix argument is given, its value determines the
21440 number of stars to add."
21441 (interactive "P")
21442 (let ((skip-blanks
21443 (function
21444 ;; Return beginning of first non-blank line, starting from
21445 ;; line at POS.
21446 (lambda (pos)
21447 (save-excursion
21448 (goto-char pos)
21449 (while (org-at-comment-p) (forward-line))
21450 (skip-chars-forward " \r\t\n")
21451 (point-at-bol)))))
21452 beg end toggled)
21453 ;; Determine boundaries of changes. If a universal prefix has
21454 ;; been given, put the list in a region. If region ends at a bol,
21455 ;; do not consider the last line to be in the region.
21457 (when (and current-prefix-arg (org-at-item-p))
21458 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21459 (org-mark-element))
21461 (if (org-region-active-p)
21462 (setq beg (funcall skip-blanks (region-beginning))
21463 end (copy-marker (save-excursion
21464 (goto-char (region-end))
21465 (if (bolp) (point) (point-at-eol)))))
21466 (setq beg (funcall skip-blanks (point-at-bol))
21467 end (copy-marker (point-at-eol))))
21468 ;; Ensure inline tasks don't count as headings.
21469 (org-with-limited-levels
21470 (save-excursion
21471 (goto-char beg)
21472 (cond
21473 ;; Case 1. Started at an heading: de-star headings.
21474 ((org-at-heading-p)
21475 (while (< (point) end)
21476 (when (org-at-heading-p t)
21477 (looking-at org-outline-regexp) (replace-match "")
21478 (setq toggled t))
21479 (forward-line)))
21480 ;; Case 2. Started at an item: change items into headlines.
21481 ;; One star will be added by `org-list-to-subtree'.
21482 ((org-at-item-p)
21483 (while (< (point) end)
21484 (when (org-at-item-p)
21485 ;; Pay attention to cases when region ends before list.
21486 (let* ((struct (org-list-struct))
21487 (list-end
21488 (min (org-list-get-bottom-point struct) (1+ end))))
21489 (save-restriction
21490 (narrow-to-region (point) list-end)
21491 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21492 (setq toggled t))
21493 (forward-line)))
21494 ;; Case 3. Started at normal text: make every line an heading,
21495 ;; skipping headlines and items.
21496 (t (let* ((stars
21497 (make-string
21498 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21499 (add-stars
21500 (cond (nstars "") ; stars from prefix only
21501 ((equal stars "") "*") ; before first heading
21502 (org-odd-levels-only "**") ; inside heading, odd
21503 (t "*"))) ; inside heading, oddeven
21504 (rpl (concat stars add-stars " "))
21505 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21506 (while (< (point) (if (equal nstars '(4)) lend end))
21507 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21508 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21509 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21510 (forward-line)))))))
21511 (unless toggled (message "Cannot toggle heading from here"))))
21513 (defun org-meta-return (&optional _arg)
21514 "Insert a new heading or wrap a region in a table.
21515 Calls `org-insert-heading' or `org-table-wrap-region', depending
21516 on context. See the individual commands for more information."
21517 (interactive)
21518 (org-check-before-invisible-edit 'insert)
21519 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21520 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21521 #'org-insert-heading))))
21523 ;;; Menu entries
21525 (defsubst org-in-subtree-not-table-p ()
21526 "Are we in a subtree and not in a table?"
21527 (and (not (org-before-first-heading-p))
21528 (not (org-at-table-p))))
21530 ;; Define the Org mode menus
21531 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21532 '("Tbl"
21533 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21534 ["Next Field" org-cycle (org-at-table-p)]
21535 ["Previous Field" org-shifttab (org-at-table-p)]
21536 ["Next Row" org-return (org-at-table-p)]
21537 "--"
21538 ["Blank Field" org-table-blank-field (org-at-table-p)]
21539 ["Edit Field" org-table-edit-field (org-at-table-p)]
21540 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21541 "--"
21542 ("Column"
21543 ["Move Column Left" org-metaleft (org-at-table-p)]
21544 ["Move Column Right" org-metaright (org-at-table-p)]
21545 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21546 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21547 ("Row"
21548 ["Move Row Up" org-metaup (org-at-table-p)]
21549 ["Move Row Down" org-metadown (org-at-table-p)]
21550 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21551 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21552 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21553 "--"
21554 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21555 ("Rectangle"
21556 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21557 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21558 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21559 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21560 "--"
21561 ("Calculate"
21562 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21563 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21564 ["Edit Formulas" org-edit-special (org-at-table-p)]
21565 "--"
21566 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21567 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21568 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21569 "--"
21570 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21571 "--"
21572 ["Sum Column/Rectangle" org-table-sum
21573 (or (org-at-table-p) (org-region-active-p))]
21574 ["Which Column?" org-table-current-column (org-at-table-p)])
21575 ["Debug Formulas"
21576 org-table-toggle-formula-debugger
21577 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21578 ["Show Col/Row Numbers"
21579 org-table-toggle-coordinate-overlays
21580 :style toggle
21581 :selected (bound-and-true-p org-table-overlay-coordinates)]
21582 "--"
21583 ["Create" org-table-create (and (not (org-at-table-p))
21584 org-enable-table-editor)]
21585 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21586 ["Import from File" org-table-import (not (org-at-table-p))]
21587 ["Export to File" org-table-export (org-at-table-p)]
21588 "--"
21589 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21590 "--"
21591 ("Plot"
21592 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21593 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21595 (easy-menu-define org-org-menu org-mode-map "Org menu"
21596 '("Org"
21597 ("Show/Hide"
21598 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21599 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21600 ["Sparse Tree..." org-sparse-tree t]
21601 ["Reveal Context" org-reveal t]
21602 ["Show All" outline-show-all t]
21603 "--"
21604 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21605 "--"
21606 ["New Heading" org-insert-heading t]
21607 ("Navigate Headings"
21608 ["Up" outline-up-heading t]
21609 ["Next" outline-next-visible-heading t]
21610 ["Previous" outline-previous-visible-heading t]
21611 ["Next Same Level" outline-forward-same-level t]
21612 ["Previous Same Level" outline-backward-same-level t]
21613 "--"
21614 ["Jump" org-goto t])
21615 ("Edit Structure"
21616 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21617 "--"
21618 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21619 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21620 "--"
21621 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21622 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21623 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21624 "--"
21625 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21626 "--"
21627 ["Copy visible text" org-copy-visible t]
21628 "--"
21629 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21630 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21631 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21632 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21633 "--"
21634 ["Sort Region/Children" org-sort t]
21635 "--"
21636 ["Convert to odd levels" org-convert-to-odd-levels t]
21637 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21638 ("Editing"
21639 ["Emphasis..." org-emphasize t]
21640 ["Edit Source Example" org-edit-special t]
21641 "--"
21642 ["Footnote new/jump" org-footnote-action t]
21643 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21644 ("Archive"
21645 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21646 "--"
21647 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21648 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21649 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21651 "--"
21652 ("Hyperlinks"
21653 ["Store Link (Global)" org-store-link t]
21654 ["Find existing link to here" org-occur-link-in-agenda-files t]
21655 ["Insert Link" org-insert-link t]
21656 ["Follow Link" org-open-at-point t]
21657 "--"
21658 ["Next link" org-next-link t]
21659 ["Previous link" org-previous-link t]
21660 "--"
21661 ["Descriptive Links"
21662 org-toggle-link-display
21663 :style radio
21664 :selected org-descriptive-links
21666 ["Literal Links"
21667 org-toggle-link-display
21668 :style radio
21669 :selected (not org-descriptive-links)])
21670 "--"
21671 ("TODO Lists"
21672 ["TODO/DONE/-" org-todo t]
21673 ("Select keyword"
21674 ["Next keyword" org-shiftright (org-at-heading-p)]
21675 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21676 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21677 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21678 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21679 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21680 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21681 "--"
21682 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21683 :selected org-enforce-todo-dependencies :style toggle :active t]
21684 "Settings for tree at point"
21685 ["Do Children sequentially" org-toggle-ordered-property :style radio
21686 :selected (org-entry-get nil "ORDERED")
21687 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21688 ["Do Children parallel" org-toggle-ordered-property :style radio
21689 :selected (not (org-entry-get nil "ORDERED"))
21690 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21691 "--"
21692 ["Set Priority" org-priority t]
21693 ["Priority Up" org-shiftup t]
21694 ["Priority Down" org-shiftdown t]
21695 "--"
21696 ["Get news from all feeds" org-feed-update-all t]
21697 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21698 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21699 ("TAGS and Properties"
21700 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21701 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21702 "--"
21703 ["Set property" org-set-property (not (org-before-first-heading-p))]
21704 ["Column view of properties" org-columns t]
21705 ["Insert Column View DBlock" org-columns-insert-dblock t])
21706 ("Dates and Scheduling"
21707 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21708 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21709 ("Change Date"
21710 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21711 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21712 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21713 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21714 ["Compute Time Range" org-evaluate-time-range t]
21715 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21716 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21717 "--"
21718 ["Custom time format" org-toggle-time-stamp-overlays
21719 :style radio :selected org-display-custom-times]
21720 "--"
21721 ["Goto Calendar" org-goto-calendar t]
21722 ["Date from Calendar" org-date-from-calendar t]
21723 "--"
21724 ["Start/Restart Timer" org-timer-start t]
21725 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21726 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21727 ["Insert Timer String" org-timer t]
21728 ["Insert Timer Item" org-timer-item t])
21729 ("Logging work"
21730 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21731 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21732 ["Clock out" org-clock-out t]
21733 ["Clock cancel" org-clock-cancel t]
21734 "--"
21735 ["Mark as default task" org-clock-mark-default-task t]
21736 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21737 ["Goto running clock" org-clock-goto t]
21738 "--"
21739 ["Display times" org-clock-display t]
21740 ["Create clock table" org-clock-report t]
21741 "--"
21742 ["Record DONE time"
21743 (progn (setq org-log-done (not org-log-done))
21744 (message "Switching to %s will %s record a timestamp"
21745 (car org-done-keywords)
21746 (if org-log-done "automatically" "not")))
21747 :style toggle :selected org-log-done])
21748 "--"
21749 ["Agenda Command..." org-agenda t]
21750 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21751 ("File List for Agenda")
21752 ("Special views current file"
21753 ["TODO Tree" org-show-todo-tree t]
21754 ["Check Deadlines" org-check-deadlines t]
21755 ["Timeline" org-timeline t]
21756 ["Tags/Property tree" org-match-sparse-tree t])
21757 "--"
21758 ["Export/Publish..." org-export-dispatch t]
21759 ("LaTeX"
21760 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21761 :selected org-cdlatex-mode]
21762 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21763 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21764 ["Modify math symbol" org-cdlatex-math-modify
21765 (org-inside-LaTeX-fragment-p)]
21766 ["Insert citation" org-reftex-citation t])
21767 "--"
21768 ("MobileOrg"
21769 ["Push Files and Views" org-mobile-push t]
21770 ["Get Captured and Flagged" org-mobile-pull t]
21771 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21772 "--"
21773 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21774 "--"
21775 ("Documentation"
21776 ["Show Version" org-version t]
21777 ["Info Documentation" org-info t])
21778 ("Customize"
21779 ["Browse Org Group" org-customize t]
21780 "--"
21781 ["Expand This Menu" org-create-customize-menu
21782 (fboundp 'customize-menu-create)])
21783 ["Send bug report" org-submit-bug-report t]
21784 "--"
21785 ("Refresh/Reload"
21786 ["Refresh setup current buffer" org-mode-restart t]
21787 ["Reload Org (after update)" org-reload t]
21788 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21791 (defun org-info (&optional node)
21792 "Read documentation for Org in the info system.
21793 With optional NODE, go directly to that node."
21794 (interactive)
21795 (info (format "(org)%s" (or node ""))))
21797 ;;;###autoload
21798 (defun org-submit-bug-report ()
21799 "Submit a bug report on Org via mail.
21801 Don't hesitate to report any problems or inaccurate documentation.
21803 If you don't have setup sending mail from (X)Emacs, please copy the
21804 output buffer into your mail program, as it gives us important
21805 information about your Org version and configuration."
21806 (interactive)
21807 (require 'reporter)
21808 (defvar reporter-prompt-for-summary-p)
21809 (org-load-modules-maybe)
21810 (org-require-autoloaded-modules)
21811 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21812 (reporter-submit-bug-report
21813 "emacs-orgmode@gnu.org"
21814 (org-version nil 'full)
21815 (let (list)
21816 (save-window-excursion
21817 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21818 (delete-other-windows)
21819 (erase-buffer)
21820 (insert "You are about to submit a bug report to the Org mailing list.
21822 We would like to add your full Org and Outline configuration to the
21823 bug report. This greatly simplifies the work of the maintainer and
21824 other experts on the mailing list.
21826 HOWEVER, some variables you have customized may contain private
21827 information. The names of customers, colleagues, or friends, might
21828 appear in the form of file names, tags, todo states, or search strings.
21829 If you answer yes to the prompt, you might want to check and remove
21830 such private information before sending the email.")
21831 (add-text-properties (point-min) (point-max) '(face org-warning))
21832 (when (yes-or-no-p "Include your Org configuration ")
21833 (mapatoms
21834 (lambda (v)
21835 (and (boundp v)
21836 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21837 (or (and (symbol-value v)
21838 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21839 (and
21840 (get v 'custom-type) (get v 'standard-value)
21841 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21842 (push v list)))))
21843 (kill-buffer (get-buffer "*Warn about privacy*"))
21844 list))
21845 nil nil
21846 "Remember to cover the basics, that is, what you expected to happen and
21847 what in fact did happen. You don't know how to make a good report? See
21849 http://orgmode.org/manual/Feedback.html#Feedback
21851 Your bug report will be posted to the Org mailing list.
21852 ------------------------------------------------------------------------")
21853 (save-excursion
21854 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21855 (replace-match "\\1Bug: \\3 [\\2]")))))
21858 (defun org-install-agenda-files-menu ()
21859 (let ((bl (buffer-list)))
21860 (save-excursion
21861 (while bl
21862 (set-buffer (pop bl))
21863 (when (derived-mode-p 'org-mode) (setq bl nil)))
21864 (when (derived-mode-p 'org-mode)
21865 (easy-menu-change
21866 '("Org") "File List for Agenda"
21867 (append
21868 (list
21869 ["Edit File List" (org-edit-agenda-file-list) t]
21870 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21871 ["Remove Current File from List" org-remove-file t]
21872 ["Cycle through agenda files" org-cycle-agenda-files t]
21873 ["Occur in all agenda files" org-occur-in-agenda-files t]
21874 "--")
21875 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21877 ;;;; Documentation
21879 (defun org-require-autoloaded-modules ()
21880 (interactive)
21881 (mapc #'require
21882 '(org-agenda org-archive org-attach org-clock org-colview org-id
21883 org-table org-timer)))
21885 ;;;###autoload
21886 (defun org-reload (&optional uncompiled)
21887 "Reload all org lisp files.
21888 With prefix arg UNCOMPILED, load the uncompiled versions."
21889 (interactive "P")
21890 (require 'loadhist)
21891 (let* ((org-dir (org-find-library-dir "org"))
21892 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21893 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21894 (remove-re (format "\\`%s\\'"
21895 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21896 (feats (delete-dups
21897 (mapcar 'file-name-sans-extension
21898 (mapcar 'file-name-nondirectory
21899 (delq nil
21900 (mapcar 'feature-file
21901 features))))))
21902 (lfeat (append
21903 (sort
21904 (setq feats
21905 (delq nil (mapcar
21906 (lambda (f)
21907 (if (and (string-match feature-re f)
21908 (not (string-match remove-re f)))
21909 f nil))
21910 feats)))
21911 'string-lessp)
21912 (list "org-version" "org")))
21913 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21914 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21915 load-uncore load-misses)
21916 (setq load-misses
21917 (delq 't
21918 (mapcar (lambda (f)
21919 (or (org-load-noerror-mustsuffix (concat org-dir f))
21920 (and (string= org-dir contrib-dir)
21921 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21922 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21923 (add-to-list 'load-uncore f 'append)
21926 lfeat)))
21927 (when load-uncore
21928 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21929 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21930 (if load-misses
21931 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21932 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21933 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21935 ;;;###autoload
21936 (defun org-customize ()
21937 "Call the customize function with org as argument."
21938 (interactive)
21939 (org-load-modules-maybe)
21940 (org-require-autoloaded-modules)
21941 (customize-browse 'org))
21943 (defun org-create-customize-menu ()
21944 "Create a full customization menu for Org mode, insert it into the menu."
21945 (interactive)
21946 (org-load-modules-maybe)
21947 (org-require-autoloaded-modules)
21948 (if (fboundp 'customize-menu-create)
21949 (progn
21950 (easy-menu-change
21951 '("Org") "Customize"
21952 `(["Browse Org group" org-customize t]
21953 "--"
21954 ,(customize-menu-create 'org)
21955 ["Set" Custom-set t]
21956 ["Save" Custom-save t]
21957 ["Reset to Current" Custom-reset-current t]
21958 ["Reset to Saved" Custom-reset-saved t]
21959 ["Reset to Standard Settings" Custom-reset-standard t]))
21960 (message "\"Org\"-menu now contains full customization menu"))
21961 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21963 ;;;; Miscellaneous stuff
21965 ;;; Generally useful functions
21967 (defun org-get-at-eol (property n)
21968 "Get text property PROPERTY at the end of line less N characters."
21969 (get-text-property (- (point-at-eol) n) property))
21971 (defun org-find-text-property-in-string (prop s)
21972 "Return the first non-nil value of property PROP in string S."
21973 (or (get-text-property 0 prop s)
21974 (get-text-property (or (next-single-property-change 0 prop s) 0)
21975 prop s)))
21977 (defun org-display-warning (message)
21978 "Display the given MESSAGE as a warning."
21979 (display-warning 'org message :warning))
21981 (defun org-eval (form)
21982 "Eval FORM and return result."
21983 (condition-case error
21984 (eval form)
21985 (error (format "%%![Error: %s]" error))))
21987 (defun org-in-clocktable-p ()
21988 "Check if the cursor is in a clocktable."
21989 (let ((pos (point)) start)
21990 (save-excursion
21991 (end-of-line 1)
21992 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21993 (setq start (match-beginning 0))
21994 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21995 (>= (match-end 0) pos)
21996 start))))
21998 (defun org-in-verbatim-emphasis ()
21999 (save-match-data
22000 (and (org-in-regexp org-emph-re 2)
22001 (>= (point) (match-beginning 3))
22002 (<= (point) (match-end 4))
22003 (member (match-string 3) '("=" "~")))))
22005 (defun org-overlay-display (ovl text &optional face evap)
22006 "Make overlay OVL display TEXT with face FACE."
22007 (overlay-put ovl 'display text)
22008 (if face (overlay-put ovl 'face face))
22009 (if evap (overlay-put ovl 'evaporate t)))
22011 (defun org-overlay-before-string (ovl text &optional face evap)
22012 "Make overlay OVL display TEXT with face FACE."
22013 (if face (org-add-props text nil 'face face))
22014 (overlay-put ovl 'before-string text)
22015 (if evap (overlay-put ovl 'evaporate t)))
22017 (defun org-find-overlays (prop &optional pos delete)
22018 "Find all overlays specifying PROP at POS or point.
22019 If DELETE is non-nil, delete all those overlays."
22020 (let (found)
22021 (dolist (ov (overlays-at (or pos (point))) found)
22022 (cond ((not (overlay-get ov prop)))
22023 (delete (delete-overlay ov))
22024 (t (push ov found))))))
22026 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22027 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22028 (if (and marker (marker-buffer marker)
22029 (buffer-live-p (marker-buffer marker)))
22030 (progn
22031 (pop-to-buffer-same-window (marker-buffer marker))
22032 (when (or (> marker (point-max)) (< marker (point-min)))
22033 (widen))
22034 (goto-char marker)
22035 (org-show-context 'org-goto))
22036 (if bookmark
22037 (bookmark-jump bookmark)
22038 (error "Cannot find location"))))
22040 (defun org-quote-csv-field (s)
22041 "Quote field for inclusion in CSV material."
22042 (if (string-match "[\",]" s)
22043 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22046 (defun org-force-self-insert (N)
22047 "Needed to enforce self-insert under remapping."
22048 (interactive "p")
22049 (self-insert-command N))
22051 (defun org-string-width (s)
22052 "Compute width of string, ignoring invisible characters.
22053 This ignores character with invisibility property `org-link', and also
22054 characters with property `org-cwidth', because these will become invisible
22055 upon the next fontification round."
22056 (let (b l)
22057 (when (or (eq t buffer-invisibility-spec)
22058 (assq 'org-link buffer-invisibility-spec))
22059 (while (setq b (text-property-any 0 (length s)
22060 'invisible 'org-link s))
22061 (setq s (concat (substring s 0 b)
22062 (substring s (or (next-single-property-change
22063 b 'invisible s)
22064 (length s)))))))
22065 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22066 (setq s (concat (substring s 0 b)
22067 (substring s (or (next-single-property-change
22068 b 'org-cwidth s)
22069 (length s))))))
22070 (setq l (string-width s) b -1)
22071 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22072 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22075 (defun org-shorten-string (s maxlength)
22076 "Shorten string S so that it is no longer than MAXLENGTH characters.
22077 If the string is shorter or has length MAXLENGTH, just return the
22078 original string. If it is longer, the functions finds a space in the
22079 string, breaks this string off at that locations and adds three dots
22080 as ellipsis. Including the ellipsis, the string will not be longer
22081 than MAXLENGTH. If finding a good breaking point in the string does
22082 not work, the string is just chopped off in the middle of a word
22083 if necessary."
22084 (if (<= (length s) maxlength)
22086 (let* ((n (max (- maxlength 4) 1))
22087 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22088 (if (string-match re s)
22089 (concat (match-string 1 s) "...")
22090 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22092 (defun org-get-indentation (&optional line)
22093 "Get the indentation of the current line, interpreting tabs.
22094 When LINE is given, assume it represents a line and compute its indentation."
22095 (if line
22096 (when (string-match "^ *" (org-remove-tabs line))
22097 (match-end 0))
22098 (save-excursion
22099 (beginning-of-line 1)
22100 (skip-chars-forward " \t")
22101 (current-column))))
22103 (defun org-get-string-indentation (s)
22104 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22105 (let ((n -1) (i 0) (w tab-width) c)
22106 (catch 'exit
22107 (while (< (setq n (1+ n)) (length s))
22108 (setq c (aref s n))
22109 (cond ((= c ?\ ) (setq i (1+ i)))
22110 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22111 (t (throw 'exit t)))))
22114 (defun org-remove-tabs (s &optional width)
22115 "Replace tabulators in S with spaces.
22116 Assumes that s is a single line, starting in column 0."
22117 (setq width (or width tab-width))
22118 (while (string-match "\t" s)
22119 (setq s (replace-match
22120 (make-string
22121 (- (* width (/ (+ (match-beginning 0) width) width))
22122 (match-beginning 0)) ?\ )
22123 t t s)))
22126 (defun org-fix-indentation (line ind)
22127 "Fix indentation in LINE.
22128 IND is a cons cell with target and minimum indentation.
22129 If the current indentation in LINE is smaller than the minimum,
22130 leave it alone. If it is larger than ind, set it to the target."
22131 (let* ((l (org-remove-tabs line))
22132 (i (org-get-indentation l))
22133 (i1 (car ind)) (i2 (cdr ind)))
22134 (when (>= i i2) (setq l (substring line i2)))
22135 (if (> i1 0)
22136 (concat (make-string i1 ?\ ) l)
22137 l)))
22139 (defun org-remove-indentation (code &optional n)
22140 "Remove maximum common indentation in string CODE and return it.
22141 N may optionally be the number of columns to remove. Return CODE
22142 as-is if removal failed."
22143 (with-temp-buffer
22144 (insert code)
22145 (if (org-do-remove-indentation n) (buffer-string) code)))
22147 (defun org-do-remove-indentation (&optional n)
22148 "Remove the maximum common indentation from the buffer.
22149 When optional argument N is a positive integer, remove exactly
22150 that much characters from indentation, if possible. Return nil
22151 if it fails."
22152 (catch :exit
22153 (goto-char (point-min))
22154 ;; Find maximum common indentation, if not specified.
22155 (let ((n (or n
22156 (let ((min-ind (point-max)))
22157 (save-excursion
22158 (while (re-search-forward "^[ \t]*\\S-" nil t)
22159 (let ((ind (1- (current-column))))
22160 (if (zerop ind) (throw :exit nil)
22161 (setq min-ind (min min-ind ind))))))
22162 min-ind))))
22163 (if (zerop n) (throw :exit nil)
22164 ;; Remove exactly N indentation, but give up if not possible.
22165 (while (not (eobp))
22166 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22167 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22168 ((< ind n) (throw :exit nil))
22169 (t (indent-line-to (- ind n))))
22170 (forward-line)))
22171 ;; Signal success.
22172 t))))
22174 (defun org-fill-template (template alist)
22175 "Find each %key of ALIST in TEMPLATE and replace it."
22176 (let ((case-fold-search nil))
22177 (dolist (entry (sort (copy-sequence alist)
22178 (lambda (a b) (< (length (car a)) (length (car b))))))
22179 (setq template
22180 (replace-regexp-in-string
22181 (concat "%" (regexp-quote (car entry)))
22182 (or (cdr entry) "") template t t)))
22183 template))
22185 (defun org-base-buffer (buffer)
22186 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22187 (if (not buffer)
22188 buffer
22189 (or (buffer-base-buffer buffer)
22190 buffer)))
22192 (defun org-wrap (string &optional width lines)
22193 "Wrap string to either a number of lines, or a width in characters.
22194 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22195 that costs. If there is a word longer than WIDTH, the text is actually
22196 wrapped to the length of that word.
22197 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22198 many lines, whatever width that takes.
22199 The return value is a list of lines, without newlines at the end."
22200 (let* ((words (org-split-string string "[ \t\n]+"))
22201 (maxword (apply 'max (mapcar 'org-string-width words)))
22202 w ll)
22203 (cond (width
22204 (org-do-wrap words (max maxword width)))
22205 (lines
22206 (setq w maxword)
22207 (setq ll (org-do-wrap words maxword))
22208 (if (<= (length ll) lines)
22210 (setq ll words)
22211 (while (> (length ll) lines)
22212 (setq w (1+ w))
22213 (setq ll (org-do-wrap words w)))
22214 ll))
22215 (t (error "Cannot wrap this")))))
22217 (defun org-do-wrap (words width)
22218 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22219 (let (lines line)
22220 (while words
22221 (setq line (pop words))
22222 (while (and words (< (+ (length line) (length (car words))) width))
22223 (setq line (concat line " " (pop words))))
22224 (setq lines (push line lines)))
22225 (nreverse lines)))
22227 (defun org-split-string (string &optional separators)
22228 "Splits STRING into substrings at SEPARATORS.
22229 SEPARATORS is a regular expression.
22230 No empty strings are returned if there are matches at the beginning
22231 and end of string."
22232 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22233 (let ((start 0) notfirst list)
22234 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22235 (if (and notfirst
22236 (= start (match-beginning 0))
22237 (< start (length string)))
22238 (1+ start) start))
22239 (< (match-beginning 0) (length string)))
22240 (setq notfirst t)
22241 (or (eq (match-beginning 0) 0)
22242 (and (eq (match-beginning 0) (match-end 0))
22243 (eq (match-beginning 0) start))
22244 (push (substring string start (match-beginning 0)) list))
22245 (setq start (match-end 0)))
22246 (or (eq start (length string))
22247 (push (substring string start) list))
22248 (nreverse list)))
22250 (defun org-quote-vert (s)
22251 "Replace \"|\" with \"\\vert\"."
22252 (while (string-match "|" s)
22253 (setq s (replace-match "\\vert" t t s)))
22256 (defun org-uuidgen-p (s)
22257 "Is S an ID created by UUIDGEN?"
22258 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22260 (defun org-in-src-block-p (&optional inside)
22261 "Whether point is in a code source block.
22262 When INSIDE is non-nil, don't consider we are within a src block
22263 when point is at #+BEGIN_SRC or #+END_SRC."
22264 (let ((case-fold-search t))
22265 (or (and (eq (get-char-property (point) 'src-block) t))
22266 (and (not inside)
22267 (save-match-data
22268 (save-excursion
22269 (beginning-of-line)
22270 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22272 (defun org-context ()
22273 "Return a list of contexts of the current cursor position.
22274 If several contexts apply, all are returned.
22275 Each context entry is a list with a symbol naming the context, and
22276 two positions indicating start and end of the context. Possible
22277 contexts are:
22279 :headline anywhere in a headline
22280 :headline-stars on the leading stars in a headline
22281 :todo-keyword on a TODO keyword (including DONE) in a headline
22282 :tags on the TAGS in a headline
22283 :priority on the priority cookie in a headline
22284 :item on the first line of a plain list item
22285 :item-bullet on the bullet/number of a plain list item
22286 :checkbox on the checkbox in a plain list item
22287 :table in an Org table
22288 :table-special on a special filed in a table
22289 :table-table in a table.el table
22290 :clocktable in a clocktable
22291 :src-block in a source block
22292 :link on a hyperlink
22293 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22294 :target on a <<target>>
22295 :radio-target on a <<<radio-target>>>
22296 :latex-fragment on a LaTeX fragment
22297 :latex-preview on a LaTeX fragment with overlaid preview image
22299 This function expects the position to be visible because it uses font-lock
22300 faces as a help to recognize the following contexts: :table-special, :link,
22301 and :keyword."
22302 (let* ((f (get-text-property (point) 'face))
22303 (faces (if (listp f) f (list f)))
22304 (case-fold-search t)
22305 (p (point)) clist o)
22306 ;; First the large context
22307 (cond
22308 ((org-at-heading-p t)
22309 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22310 (when (progn
22311 (beginning-of-line 1)
22312 (looking-at org-todo-line-tags-regexp))
22313 (push (org-point-in-group p 1 :headline-stars) clist)
22314 (push (org-point-in-group p 2 :todo-keyword) clist)
22315 (push (org-point-in-group p 4 :tags) clist))
22316 (goto-char p)
22317 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22318 (when (looking-at "\\[#[A-Z0-9]\\]")
22319 (push (org-point-in-group p 0 :priority) clist)))
22321 ((org-at-item-p)
22322 (push (org-point-in-group p 2 :item-bullet) clist)
22323 (push (list :item (point-at-bol)
22324 (save-excursion (org-end-of-item) (point)))
22325 clist)
22326 (and (org-at-item-checkbox-p)
22327 (push (org-point-in-group p 0 :checkbox) clist)))
22329 ((org-at-table-p)
22330 (push (list :table (org-table-begin) (org-table-end)) clist)
22331 (when (memq 'org-formula faces)
22332 (push (list :table-special
22333 (previous-single-property-change p 'face)
22334 (next-single-property-change p 'face)) clist)))
22335 ((org-at-table-p 'any)
22336 (push (list :table-table) clist)))
22337 (goto-char p)
22339 (let ((case-fold-search t))
22340 ;; New the "medium" contexts: clocktables, source blocks
22341 (cond ((org-in-clocktable-p)
22342 (push (list :clocktable
22343 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22344 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22345 (match-beginning 1))
22346 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22347 (match-end 0))) clist))
22348 ((org-in-src-block-p)
22349 (push (list :src-block
22350 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22351 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22352 (match-beginning 1))
22353 (and (search-forward "#+END_SRC" nil t)
22354 (match-beginning 0))) clist))))
22355 (goto-char p)
22357 ;; Now the small context
22358 (cond
22359 ((org-at-timestamp-p)
22360 (push (org-point-in-group p 0 :timestamp) clist))
22361 ((memq 'org-link faces)
22362 (push (list :link
22363 (previous-single-property-change p 'face)
22364 (next-single-property-change p 'face)) clist))
22365 ((memq 'org-special-keyword faces)
22366 (push (list :keyword
22367 (previous-single-property-change p 'face)
22368 (next-single-property-change p 'face)) clist))
22369 ((org-at-target-p)
22370 (push (org-point-in-group p 0 :target) clist)
22371 (goto-char (1- (match-beginning 0)))
22372 (when (looking-at org-radio-target-regexp)
22373 (push (org-point-in-group p 0 :radio-target) clist))
22374 (goto-char p))
22375 ((setq o (cl-some
22376 (lambda (o)
22377 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22379 (overlays-at (point))))
22380 (push (list :latex-fragment
22381 (overlay-start o) (overlay-end o)) clist)
22382 (push (list :latex-preview
22383 (overlay-start o) (overlay-end o)) clist))
22384 ((org-inside-LaTeX-fragment-p)
22385 ;; FIXME: positions wrong.
22386 (push (list :latex-fragment (point) (point)) clist)))
22388 (setq clist (nreverse (delq nil clist)))
22389 clist))
22391 (defun org-in-regexp (regexp &optional nlines visually)
22392 "Check if point is inside a match of REGEXP.
22394 Normally only the current line is checked, but you can include
22395 NLINES extra lines around point into the search. If VISUALLY is
22396 set, require that the cursor is not after the match but really
22397 on, so that the block visually is on the match.
22399 Return nil or a cons cell (BEG . END) where BEG and END are,
22400 respectively, the positions at the beginning and the end of the
22401 match."
22402 (catch :exit
22403 (let ((pos (point))
22404 (eol (line-end-position (if nlines (1+ nlines) 1))))
22405 (save-excursion
22406 (beginning-of-line (- 1 (or nlines 0)))
22407 (while (and (re-search-forward regexp eol t)
22408 (<= (match-beginning 0) pos))
22409 (let ((end (match-end 0)))
22410 (when (or (> end pos) (and (= end pos) (not visually)))
22411 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22413 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22414 "Non-nil when point is between matches of START-RE and END-RE.
22416 Also return a non-nil value when point is on one of the matches.
22418 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22419 buffer positions. Default values are the positions of headlines
22420 surrounding the point.
22422 The functions returns a cons cell whose car (resp. cdr) is the
22423 position before START-RE (resp. after END-RE)."
22424 (save-match-data
22425 (let ((pos (point))
22426 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22427 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22428 beg end)
22429 (save-excursion
22430 ;; Point is on a block when on START-RE or if START-RE can be
22431 ;; found before it...
22432 (and (or (org-in-regexp start-re)
22433 (re-search-backward start-re limit-up t))
22434 (setq beg (match-beginning 0))
22435 ;; ... and END-RE after it...
22436 (goto-char (match-end 0))
22437 (re-search-forward end-re limit-down t)
22438 (> (setq end (match-end 0)) pos)
22439 ;; ... without another START-RE in-between.
22440 (goto-char (match-beginning 0))
22441 (not (re-search-backward start-re (1+ beg) t))
22442 ;; Return value.
22443 (cons beg end))))))
22445 (defun org-in-block-p (names)
22446 "Non-nil when point belongs to a block whose name belongs to NAMES.
22448 NAMES is a list of strings containing names of blocks.
22450 Return first block name matched, or nil. Beware that in case of
22451 nested blocks, the returned name may not belong to the closest
22452 block from point."
22453 (save-match-data
22454 (catch 'exit
22455 (let ((case-fold-search t)
22456 (lim-up (save-excursion (outline-previous-heading)))
22457 (lim-down (save-excursion (outline-next-heading))))
22458 (dolist (name names)
22459 (let ((n (regexp-quote name)))
22460 (when (org-between-regexps-p
22461 (concat "^[ \t]*#\\+begin_" n)
22462 (concat "^[ \t]*#\\+end_" n)
22463 lim-up lim-down)
22464 (throw 'exit n)))))
22465 nil)))
22467 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22468 "Call `multi-occur' with buffers for all agenda files."
22469 (interactive "sOrg-files matching: ")
22470 (let* ((files (org-agenda-files))
22471 (tnames (mapcar #'file-truename files))
22472 (extra org-agenda-text-search-extra-files))
22473 (when (eq (car extra) 'agenda-archives)
22474 (setq extra (cdr extra))
22475 (setq files (org-add-archive-files files)))
22476 (dolist (f extra)
22477 (unless (member (file-truename f) tnames)
22478 (unless (member f files) (setq files (append files (list f))))
22479 (setq tnames (append tnames (list (file-truename f))))))
22480 (multi-occur
22481 (mapcar (lambda (x)
22482 (with-current-buffer
22483 ;; FIXME: Why not just (find-file-noselect x)?
22484 ;; Is it to avoid the "revert buffer" prompt?
22485 (or (get-file-buffer x) (find-file-noselect x))
22486 (widen)
22487 (current-buffer)))
22488 files)
22489 regexp)))
22491 (add-hook 'occur-mode-find-occurrence-hook
22492 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22494 (defun org-occur-link-in-agenda-files ()
22495 "Create a link and search for it in the agendas.
22496 The link is not stored in `org-stored-links', it is just created
22497 for the search purpose."
22498 (interactive)
22499 (let ((link (condition-case nil
22500 (org-store-link nil)
22501 (error "Unable to create a link to here"))))
22502 (org-occur-in-agenda-files (regexp-quote link))))
22504 (defun org-reverse-string (string)
22505 "Return the reverse of STRING."
22506 (apply 'string (reverse (string-to-list string))))
22508 ;; defsubst org-uniquify must be defined before first use
22510 (defun org-uniquify-alist (alist)
22511 "Merge elements of ALIST with the same key.
22513 For example, in this alist:
22515 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22516 => \\='((a 1 3) (b 2))
22518 merge (a 1) and (a 3) into (a 1 3).
22520 The function returns the new ALIST."
22521 (let (rtn)
22522 (dolist (e alist rtn)
22523 (let (n)
22524 (if (not (assoc (car e) rtn))
22525 (push e rtn)
22526 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22527 (setq rtn (assq-delete-all (car e) rtn))
22528 (push n rtn))))))
22530 (defun org-delete-all (elts list)
22531 "Remove all elements in ELTS from LIST.
22532 Comparison is done with `equal'. It is a destructive operation
22533 that may remove elements by altering the list structure."
22534 (while elts
22535 (setq list (delete (pop elts) list)))
22536 list)
22538 (defun org-back-over-empty-lines ()
22539 "Move backwards over whitespace, to the beginning of the first empty line.
22540 Returns the number of empty lines passed."
22541 (let ((pos (point)))
22542 (if (cdr (assq 'heading org-blank-before-new-entry))
22543 (skip-chars-backward " \t\n\r")
22544 (unless (eobp)
22545 (forward-line -1)))
22546 (beginning-of-line 2)
22547 (goto-char (min (point) pos))
22548 (count-lines (point) pos)))
22550 (defun org-skip-whitespace ()
22551 (skip-chars-forward " \t\n\r"))
22553 (defun org-point-in-group (point group &optional context)
22554 "Check if POINT is in match-group GROUP.
22555 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22556 match. If the match group does not exist or point is not inside it,
22557 return nil."
22558 (and (match-beginning group)
22559 (>= point (match-beginning group))
22560 (<= point (match-end group))
22561 (if context
22562 (list context (match-beginning group) (match-end group))
22563 t)))
22565 (defun org-switch-to-buffer-other-window (&rest args)
22566 "Switch to buffer in a second window on the current frame.
22567 In particular, do not allow pop-up frames.
22568 Returns the newly created buffer."
22569 (org-no-popups
22570 (apply 'switch-to-buffer-other-window args)))
22572 (defun org-combine-plists (&rest plists)
22573 "Create a single property list from all plists in PLISTS.
22574 The process starts by copying the first list, and then setting properties
22575 from the other lists. Settings in the last list are the most significant
22576 ones and overrule settings in the other lists."
22577 (let ((rtn (copy-sequence (pop plists)))
22578 p v ls)
22579 (while plists
22580 (setq ls (pop plists))
22581 (while ls
22582 (setq p (pop ls) v (pop ls))
22583 (setq rtn (plist-put rtn p v))))
22584 rtn))
22586 (defun org-replace-escapes (string table)
22587 "Replace %-escapes in STRING with values in TABLE.
22588 TABLE is an association list with keys like \"%a\" and string values.
22589 The sequences in STRING may contain normal field width and padding information,
22590 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22591 so values can contain further %-escapes if they are define later in TABLE."
22592 (let ((tbl (copy-alist table))
22593 (case-fold-search nil)
22594 (pchg 0)
22595 re rpl)
22596 (dolist (e tbl)
22597 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22598 (when (and (cdr e) (string-match re (cdr e)))
22599 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22600 (safe "SREF"))
22601 (add-text-properties 0 3 (list 'sref sref) safe)
22602 (setcdr e (replace-match safe t t (cdr e)))))
22603 (while (string-match re string)
22604 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22605 (cdr e)))
22606 (setq string (replace-match rpl t t string))))
22607 (while (setq pchg (next-property-change pchg string))
22608 (let ((sref (get-text-property pchg 'sref string)))
22609 (when (and sref (string-match "SREF" string pchg))
22610 (setq string (replace-match sref t t string)))))
22611 string))
22613 (defun org-find-base-buffer-visiting (file)
22614 "Like `find-buffer-visiting' but always return the base buffer and
22615 not an indirect buffer."
22616 (let ((buf (or (get-file-buffer file)
22617 (find-buffer-visiting file))))
22618 (if buf
22619 (or (buffer-base-buffer buf) buf)
22620 nil)))
22622 ;;; TODO: Only called once, from ox-odt which should probably use
22623 ;;; org-export-inline-image-p or something.
22624 (defun org-file-image-p (file)
22625 "Return non-nil if FILE is an image."
22626 (save-match-data
22627 (string-match (image-file-name-regexp) file)))
22629 (defun org-get-cursor-date (&optional with-time)
22630 "Return the date at cursor in as a time.
22631 This works in the calendar and in the agenda, anywhere else it just
22632 returns the current time.
22633 If WITH-TIME is non-nil, returns the time of the event at point (in
22634 the agenda) or the current time of the day."
22635 (let (date day defd tp hod mod)
22636 (when with-time
22637 (setq tp (get-text-property (point) 'time))
22638 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22639 (setq hod (string-to-number (match-string 1 tp))
22640 mod (string-to-number (match-string 2 tp))))
22641 (or tp (let ((now (decode-time)))
22642 (setq hod (nth 2 now)
22643 mod (nth 1 now)))))
22644 (cond
22645 ((eq major-mode 'calendar-mode)
22646 (setq date (calendar-cursor-to-date)
22647 defd (encode-time 0 (or mod 0) (or hod 0)
22648 (nth 1 date) (nth 0 date) (nth 2 date))))
22649 ((eq major-mode 'org-agenda-mode)
22650 (setq day (get-text-property (point) 'day))
22651 (when day
22652 (setq date (calendar-gregorian-from-absolute day)
22653 defd (encode-time 0 (or mod 0) (or hod 0)
22654 (nth 1 date) (nth 0 date) (nth 2 date))))))
22655 (or defd (current-time))))
22657 (defun org-mark-subtree (&optional up)
22658 "Mark the current subtree.
22659 This puts point at the start of the current subtree, and mark at
22660 the end. If a numeric prefix UP is given, move up into the
22661 hierarchy of headlines by UP levels before marking the subtree."
22662 (interactive "P")
22663 (org-with-limited-levels
22664 (cond ((org-at-heading-p) (beginning-of-line))
22665 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22666 (t (outline-previous-visible-heading 1))))
22667 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22668 (if (called-interactively-p 'any)
22669 (call-interactively 'org-mark-element)
22670 (org-mark-element)))
22672 (defun org-file-newer-than-p (file time)
22673 "Non-nil if FILE is newer than TIME.
22674 FILE is a filename, as a string, TIME is a list of integers, as
22675 returned by, e.g., `current-time'."
22676 (and (file-exists-p file)
22677 ;; Only compare times up to whole seconds as some file-systems
22678 ;; (e.g. HFS+) do not retain any finer granularity. As
22679 ;; a consequence, make sure we return non-nil when the two
22680 ;; times are equal.
22681 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22682 (cl-subseq time 0 2)))))
22684 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22685 "Compile a SOURCE file using PROCESS.
22687 PROCESS is either a function or a list of shell commands, as
22688 strings. EXT is a file extension, without the leading dot, as
22689 a string. It is used to check if the process actually succeeded.
22691 PROCESS must create a file with the same base name and directory
22692 as SOURCE, but ending with EXT. The function then returns its
22693 filename. Otherwise, it raises an error. The error message can
22694 then be refined by providing string ERR-MSG, which is appended to
22695 the standard message.
22697 If PROCESS is a function, it is called with a single argument:
22698 the SOURCE file.
22700 If it is a list of commands, each of them is called using
22701 `shell-command'. By default, in each command, %b, %f, %F, %o and
22702 %O are replaced with, respectively, SOURCE base name, name, full
22703 name, directory and absolute output file name. It is possible,
22704 however, to use more place-holders by specifying them in optional
22705 argument SPEC, as an alist following the pattern
22707 (CHARACTER . REPLACEMENT-STRING).
22709 When PROCESS is a list of commands, optional argument LOG-BUF can
22710 be set to a buffer or a buffer name. `shell-command' then uses
22711 it for output."
22712 (let* ((base-name (file-name-base source))
22713 (full-name (file-truename source))
22714 (out-dir (or (file-name-directory source) "./"))
22715 (output (expand-file-name (concat base-name "." ext) out-dir))
22716 (time (current-time))
22717 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22718 (save-window-excursion
22719 (pcase process
22720 ((pred functionp) (funcall process (shell-quote-argument source)))
22721 ((pred consp)
22722 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22723 (spec (append spec
22724 `((?b . ,(shell-quote-argument base-name))
22725 (?f . ,(shell-quote-argument source))
22726 (?F . ,(shell-quote-argument full-name))
22727 (?o . ,(shell-quote-argument out-dir))
22728 (?O . ,(shell-quote-argument output))))))
22729 (dolist (command process)
22730 (shell-command (format-spec command spec) log-buf))))
22731 (_ (error "No valid command to process %S%s" source err-msg))))
22732 ;; Check for process failure. Output file is expected to be
22733 ;; located in the same directory as SOURCE.
22734 (unless (org-file-newer-than-p output time)
22735 (error (format "File %S wasn't produced%s" output err-msg)))
22736 output))
22738 ;;; Indentation
22740 (defvar org-element-greater-elements)
22741 (defun org--get-expected-indentation (element contentsp)
22742 "Expected indentation column for current line, according to ELEMENT.
22743 ELEMENT is an element containing point. CONTENTSP is non-nil
22744 when indentation is to be computed according to contents of
22745 ELEMENT."
22746 (let ((type (org-element-type element))
22747 (start (org-element-property :begin element))
22748 (post-affiliated (org-element-property :post-affiliated element)))
22749 (org-with-wide-buffer
22750 (cond
22751 (contentsp
22752 (cl-case type
22753 ((diary-sexp footnote-definition) 0)
22754 ((headline inlinetask nil)
22755 (if (not org-adapt-indentation) 0
22756 (let ((level (org-current-level)))
22757 (if level (1+ level) 0))))
22758 ((item plain-list) (org-list-item-body-column post-affiliated))
22760 (goto-char start)
22761 (org-get-indentation))))
22762 ((memq type '(headline inlinetask nil))
22763 (if (org-match-line "[ \t]*$")
22764 (org--get-expected-indentation element t)
22766 ((memq type '(diary-sexp footnote-definition)) 0)
22767 ;; First paragraph of a footnote definition or an item.
22768 ;; Indent like parent.
22769 ((< (line-beginning-position) start)
22770 (org--get-expected-indentation
22771 (org-element-property :parent element) t))
22772 ;; At first line: indent according to previous sibling, if any,
22773 ;; ignoring footnote definitions and inline tasks, or parent's
22774 ;; contents.
22775 ((= (line-beginning-position) start)
22776 (catch 'exit
22777 (while t
22778 (if (= (point-min) start) (throw 'exit 0)
22779 (goto-char (1- start))
22780 (let* ((previous (org-element-at-point))
22781 (parent previous))
22782 (while (and parent (<= (org-element-property :end parent) start))
22783 (setq previous parent
22784 parent (org-element-property :parent parent)))
22785 (cond
22786 ((not previous) (throw 'exit 0))
22787 ((> (org-element-property :end previous) start)
22788 (throw 'exit (org--get-expected-indentation previous t)))
22789 ((memq (org-element-type previous)
22790 '(footnote-definition inlinetask))
22791 (setq start (org-element-property :begin previous)))
22792 (t (goto-char (org-element-property :begin previous))
22793 (throw 'exit
22794 (if (bolp) (org-get-indentation)
22795 ;; At first paragraph in an item or
22796 ;; a footnote definition.
22797 (org--get-expected-indentation
22798 (org-element-property :parent previous) t))))))))))
22799 ;; Otherwise, move to the first non-blank line above.
22801 (beginning-of-line)
22802 (let ((pos (point)))
22803 (skip-chars-backward " \r\t\n")
22804 (cond
22805 ;; Two blank lines end a footnote definition or a plain
22806 ;; list. When we indent an empty line after them, the
22807 ;; containing list or footnote definition is over, so it
22808 ;; qualifies as a previous sibling. Therefore, we indent
22809 ;; like its first line.
22810 ((and (memq type '(footnote-definition plain-list))
22811 (> (count-lines (point) pos) 2))
22812 (goto-char start)
22813 (org-get-indentation))
22814 ;; Line above is the first one of a paragraph at the
22815 ;; beginning of an item or a footnote definition. Indent
22816 ;; like parent.
22817 ((< (line-beginning-position) start)
22818 (org--get-expected-indentation
22819 (org-element-property :parent element) t))
22820 ;; Line above is the beginning of an element, i.e., point
22821 ;; was originally on the blank lines between element's start
22822 ;; and contents.
22823 ((= (line-beginning-position) post-affiliated)
22824 (org--get-expected-indentation element t))
22825 ;; POS is after contents in a greater element. Indent like
22826 ;; the beginning of the element.
22827 ((and (memq type org-element-greater-elements)
22828 (let ((cend (org-element-property :contents-end element)))
22829 (and cend (<= cend pos))))
22830 ;; As a special case, if point is at the end of a footnote
22831 ;; definition or an item, indent like the very last element
22832 ;; within. If that last element is an item, indent like
22833 ;; its contents.
22834 (if (memq type '(footnote-definition item plain-list))
22835 (let ((last (org-element-at-point)))
22836 (goto-char pos)
22837 (org--get-expected-indentation
22838 last (eq (org-element-type last) 'item)))
22839 (goto-char start)
22840 (org-get-indentation)))
22841 ;; In any other case, indent like the current line.
22842 (t (org-get-indentation)))))))))
22844 (defun org--align-node-property ()
22845 "Align node property at point.
22846 Alignment is done according to `org-property-format', which see."
22847 (when (save-excursion
22848 (beginning-of-line)
22849 (looking-at org-property-re))
22850 (replace-match
22851 (concat (match-string 4)
22852 (org-trim
22853 (format org-property-format (match-string 1) (match-string 3))))
22854 t t)))
22856 (defun org-indent-line ()
22857 "Indent line depending on context.
22859 Indentation is done according to the following rules:
22861 - Footnote definitions, diary sexps, headlines and inline tasks
22862 have to start at column 0.
22864 - On the very first line of an element, consider, in order, the
22865 next rules until one matches:
22867 1. If there's a sibling element before, ignoring footnote
22868 definitions and inline tasks, indent like its first line.
22870 2. If element has a parent, indent like its contents. More
22871 precisely, if parent is an item, indent after the
22872 description part, if any, or the bullet (see
22873 `org-list-description-max-indent'). Else, indent like
22874 parent's first line.
22876 3. Otherwise, indent relatively to current level, if
22877 `org-adapt-indentation' is non-nil, or to left margin.
22879 - On a blank line at the end of an element, indent according to
22880 the type of the element. More precisely
22882 1. If element is a plain list, an item, or a footnote
22883 definition, indent like the very last element within.
22885 2. If element is a paragraph, indent like its last non blank
22886 line.
22888 3. Otherwise, indent like its very first line.
22890 - In the code part of a source block, use language major mode
22891 to indent current line if `org-src-tab-acts-natively' is
22892 non-nil. If it is nil, do nothing.
22894 - Otherwise, indent like the first non-blank line above.
22896 The function doesn't indent an item as it could break the whole
22897 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22898 `\\[org-shiftmetaright]'.
22900 Also align node properties according to `org-property-format'."
22901 (interactive)
22902 (cond
22903 (orgstruct-is-++
22904 (let ((indent-line-function
22905 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22906 (indent-according-to-mode)))
22907 ((org-at-heading-p) 'noindent)
22909 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22910 (type (org-element-type element)))
22911 (cond ((and (memq type '(plain-list item))
22912 (= (line-beginning-position)
22913 (org-element-property :post-affiliated element)))
22914 'noindent)
22915 ((and (eq type 'latex-environment)
22916 (>= (point) (org-element-property :post-affiliated element))
22917 (< (point) (org-with-wide-buffer
22918 (goto-char (org-element-property :end element))
22919 (skip-chars-backward " \r\t\n")
22920 (line-beginning-position 2))))
22921 'noindent)
22922 ((and (eq type 'src-block)
22923 org-src-tab-acts-natively
22924 (> (line-beginning-position)
22925 (org-element-property :post-affiliated element))
22926 (< (line-beginning-position)
22927 (org-with-wide-buffer
22928 (goto-char (org-element-property :end element))
22929 (skip-chars-backward " \r\t\n")
22930 (line-beginning-position))))
22931 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22933 (let ((column (org--get-expected-indentation element nil)))
22934 ;; Preserve current column.
22935 (if (<= (current-column) (current-indentation))
22936 (indent-line-to column)
22937 (save-excursion (indent-line-to column))))
22938 ;; Align node property. Also preserve current column.
22939 (when (eq type 'node-property)
22940 (let ((column (current-column)))
22941 (org--align-node-property)
22942 (org-move-to-column column)))))))))
22944 (defun org-indent-region (start end)
22945 "Indent each non-blank line in the region.
22946 Called from a program, START and END specify the region to
22947 indent. The function will not indent contents of example blocks,
22948 verse blocks and export blocks as leading white spaces are
22949 assumed to be significant there."
22950 (interactive "r")
22951 (save-excursion
22952 (goto-char start)
22953 (skip-chars-forward " \r\t\n")
22954 (unless (eobp) (beginning-of-line))
22955 (let ((indent-to
22956 (lambda (ind pos)
22957 ;; Set IND as indentation for all lines between point and
22958 ;; POS. Blank lines are ignored. Leave point after POS
22959 ;; once done.
22960 (let ((limit (copy-marker pos)))
22961 (while (< (point) limit)
22962 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22963 (forward-line))
22964 (set-marker limit nil))))
22965 (end (copy-marker end)))
22966 (while (< (point) end)
22967 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22968 (let* ((element (org-element-at-point))
22969 (type (org-element-type element))
22970 (element-end (copy-marker (org-element-property :end element)))
22971 (ind (org--get-expected-indentation element nil)))
22972 (cond
22973 ;; Element indented as a single block. Example blocks
22974 ;; preserving indentation are a special case since the
22975 ;; "contents" must not be indented whereas the block
22976 ;; boundaries can.
22977 ((or (memq type '(export-block latex-environment))
22978 (and (eq type 'example-block)
22979 (not
22980 (or org-src-preserve-indentation
22981 (org-element-property :preserve-indent element)))))
22982 (let ((offset (- ind (org-get-indentation))))
22983 (unless (zerop offset)
22984 (indent-rigidly (org-element-property :begin element)
22985 (org-element-property :end element)
22986 offset)))
22987 (goto-char element-end))
22988 ;; Elements indented line wise. Be sure to exclude
22989 ;; example blocks (preserving indentation) and source
22990 ;; blocks from this category as they are treated
22991 ;; specially later.
22992 ((or (memq type '(paragraph table table-row))
22993 (not (or (org-element-property :contents-begin element)
22994 (memq type '(example-block src-block)))))
22995 (when (eq type 'node-property)
22996 (org--align-node-property)
22997 (beginning-of-line))
22998 (funcall indent-to ind (min element-end end)))
22999 ;; Elements consisting of three parts: before the
23000 ;; contents, the contents, and after the contents. The
23001 ;; contents are treated specially, according to the
23002 ;; element type, or not indented at all. Other parts are
23003 ;; indented as a single block.
23005 (let* ((post (copy-marker
23006 (org-element-property :post-affiliated element)))
23007 (cbeg
23008 (copy-marker
23009 (cond
23010 ((not (org-element-property :contents-begin element))
23011 ;; Fake contents for source blocks.
23012 (org-with-wide-buffer
23013 (goto-char post)
23014 (line-beginning-position 2)))
23015 ((memq type '(footnote-definition item plain-list))
23016 ;; Contents in these elements could start on
23017 ;; the same line as the beginning of the
23018 ;; element. Make sure we start indenting
23019 ;; from the second line.
23020 (org-with-wide-buffer
23021 (goto-char post)
23022 (end-of-line)
23023 (skip-chars-forward " \r\t\n")
23024 (if (eobp) (point) (line-beginning-position))))
23025 (t (org-element-property :contents-begin element)))))
23026 (cend (copy-marker
23027 (or (org-element-property :contents-end element)
23028 ;; Fake contents for source blocks.
23029 (org-with-wide-buffer
23030 (goto-char element-end)
23031 (skip-chars-backward " \r\t\n")
23032 (line-beginning-position)))
23033 t)))
23034 ;; Do not change items indentation individually as it
23035 ;; might break the list as a whole. On the other
23036 ;; hand, when at a plain list, indent it as a whole.
23037 (cond ((eq type 'plain-list)
23038 (let ((offset (- ind (org-get-indentation))))
23039 (unless (zerop offset)
23040 (indent-rigidly (org-element-property :begin element)
23041 (org-element-property :end element)
23042 offset))
23043 (goto-char cbeg)))
23044 ((eq type 'item) (goto-char cbeg))
23045 (t (funcall indent-to ind (min cbeg end))))
23046 (when (< (point) end)
23047 (cl-case type
23048 ((example-block verse-block))
23049 (src-block
23050 ;; In a source block, indent source code
23051 ;; according to language major mode, but only if
23052 ;; `org-src-tab-acts-natively' is non-nil.
23053 (when (and (< (point) end) org-src-tab-acts-natively)
23054 (ignore-errors
23055 (org-babel-do-in-edit-buffer
23056 (indent-region (point-min) (point-max))))))
23057 (t (org-indent-region (point) (min cend end))))
23058 (goto-char (min cend end))
23059 (when (< (point) end)
23060 (funcall indent-to ind (min element-end end))))
23061 (set-marker post nil)
23062 (set-marker cbeg nil)
23063 (set-marker cend nil))))
23064 (set-marker element-end nil))))
23065 (set-marker end nil))))
23067 (defun org-indent-drawer ()
23068 "Indent the drawer at point."
23069 (interactive)
23070 (unless (save-excursion
23071 (beginning-of-line)
23072 (looking-at-p org-drawer-regexp))
23073 (user-error "Not at a drawer"))
23074 (let ((element (org-element-at-point)))
23075 (unless (memq (org-element-type element) '(drawer property-drawer))
23076 (user-error "Not at a drawer"))
23077 (org-with-wide-buffer
23078 (org-indent-region (org-element-property :begin element)
23079 (org-element-property :end element))))
23080 (message "Drawer at point indented"))
23082 (defun org-indent-block ()
23083 "Indent the block at point."
23084 (interactive)
23085 (unless (save-excursion
23086 (beginning-of-line)
23087 (let ((case-fold-search t))
23088 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23089 (user-error "Not at a block"))
23090 (let ((element (org-element-at-point)))
23091 (unless (memq (org-element-type element)
23092 '(comment-block center-block dynamic-block example-block
23093 export-block quote-block special-block
23094 src-block verse-block))
23095 (user-error "Not at a block"))
23096 (org-with-wide-buffer
23097 (org-indent-region (org-element-property :begin element)
23098 (org-element-property :end element))))
23099 (message "Block at point indented"))
23102 ;;; Filling
23104 ;; We use our own fill-paragraph and auto-fill functions.
23106 ;; `org-fill-paragraph' relies on adaptive filling and context
23107 ;; checking. Appropriate `fill-prefix' is computed with
23108 ;; `org-adaptive-fill-function'.
23110 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23111 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23112 ;; `org-adaptive-fill-function' value. Internally,
23113 ;; `org-comment-line-break-function' breaks the line.
23115 ;; `org-setup-filling' installs filling and auto-filling related
23116 ;; variables during `org-mode' initialization.
23118 (defvar org-element-paragraph-separate) ; org-element.el
23119 (defun org-setup-filling ()
23120 (require 'org-element)
23121 ;; Prevent auto-fill from inserting unwanted new items.
23122 (when (boundp 'fill-nobreak-predicate)
23123 (setq-local
23124 fill-nobreak-predicate
23125 (org-uniquify
23126 (append fill-nobreak-predicate
23127 '(org-fill-line-break-nobreak-p
23128 org-fill-paragraph-with-timestamp-nobreak-p)))))
23129 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23130 (setq-local paragraph-start paragraph-ending)
23131 (setq-local paragraph-separate paragraph-ending))
23132 (setq-local fill-paragraph-function 'org-fill-paragraph)
23133 (setq-local auto-fill-inhibit-regexp nil)
23134 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23135 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23136 (setq-local comment-line-break-function 'org-comment-line-break-function))
23138 (defun org-fill-line-break-nobreak-p ()
23139 "Non-nil when a new line at point would create an Org line break."
23140 (save-excursion
23141 (skip-chars-backward "[ \t]")
23142 (skip-chars-backward "\\\\")
23143 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23145 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23146 "Non-nil when a new line at point would split a timestamp."
23147 (and (org-at-timestamp-p t)
23148 (not (looking-at org-ts-regexp-both))))
23150 (declare-function message-in-body-p "message" ())
23151 (defvar orgtbl-line-start-regexp) ; From org-table.el
23152 (defun org-adaptive-fill-function ()
23153 "Compute a fill prefix for the current line.
23154 Return fill prefix, as a string, or nil if current line isn't
23155 meant to be filled. For convenience, if `adaptive-fill-regexp'
23156 matches in paragraphs or comments, use it."
23157 (catch 'exit
23158 (when (derived-mode-p 'message-mode)
23159 (save-excursion
23160 (beginning-of-line)
23161 (cond ((not (message-in-body-p)) (throw 'exit nil))
23162 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23163 ((looking-at message-cite-prefix-regexp)
23164 (throw 'exit (match-string-no-properties 0)))
23165 ((looking-at org-outline-regexp)
23166 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23167 (org-with-wide-buffer
23168 (unless (org-at-heading-p)
23169 (let* ((p (line-beginning-position))
23170 (element (save-excursion
23171 (beginning-of-line)
23172 (org-element-at-point)))
23173 (type (org-element-type element))
23174 (post-affiliated (org-element-property :post-affiliated element)))
23175 (unless (< p post-affiliated)
23176 (cl-case type
23177 (comment
23178 (save-excursion
23179 (beginning-of-line)
23180 (looking-at "[ \t]*")
23181 (concat (match-string 0) "# ")))
23182 (footnote-definition "")
23183 ((item plain-list)
23184 (make-string (org-list-item-body-column post-affiliated) ?\s))
23185 (paragraph
23186 ;; Fill prefix is usually the same as the current line,
23187 ;; unless the paragraph is at the beginning of an item.
23188 (let ((parent (org-element-property :parent element)))
23189 (save-excursion
23190 (beginning-of-line)
23191 (cond ((eq (org-element-type parent) 'item)
23192 (make-string (org-list-item-body-column
23193 (org-element-property :begin parent))
23194 ?\s))
23195 ((and adaptive-fill-regexp
23196 ;; Locally disable
23197 ;; `adaptive-fill-function' to let
23198 ;; `fill-context-prefix' handle
23199 ;; `adaptive-fill-regexp' variable.
23200 (let (adaptive-fill-function)
23201 (fill-context-prefix
23202 post-affiliated
23203 (org-element-property :end element)))))
23204 ((looking-at "[ \t]+") (match-string 0))
23205 (t "")))))
23206 (comment-block
23207 ;; Only fill contents if P is within block boundaries.
23208 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23209 (forward-line)
23210 (point)))
23211 (cend (save-excursion
23212 (goto-char (org-element-property :end element))
23213 (skip-chars-backward " \r\t\n")
23214 (line-beginning-position))))
23215 (when (and (>= p cbeg) (< p cend))
23216 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23217 (match-string 0)
23218 "")))))))))))
23220 (declare-function message-goto-body "message" ())
23221 (defvar message-cite-prefix-regexp) ; From message.el
23222 (defun org-fill-paragraph (&optional justify)
23223 "Fill element at point, when applicable.
23225 This function only applies to comment blocks, comments, example
23226 blocks and paragraphs. Also, as a special case, re-align table
23227 when point is at one.
23229 If JUSTIFY is non-nil (interactively, with prefix argument),
23230 justify as well. If `sentence-end-double-space' is non-nil, then
23231 period followed by one space does not end a sentence, so don't
23232 break a line there. The variable `fill-column' controls the
23233 width for filling.
23235 For convenience, when point is at a plain list, an item or
23236 a footnote definition, try to fill the first paragraph within."
23237 (interactive)
23238 (if (and (derived-mode-p 'message-mode)
23239 (or (not (message-in-body-p))
23240 (save-excursion (move-beginning-of-line 1)
23241 (looking-at message-cite-prefix-regexp))))
23242 ;; First ensure filling is correct in message-mode.
23243 (let ((fill-paragraph-function
23244 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23245 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23246 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23247 (paragraph-separate
23248 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23249 (fill-paragraph nil))
23250 (with-syntax-table org-mode-transpose-word-syntax-table
23251 ;; Move to end of line in order to get the first paragraph
23252 ;; within a plain list or a footnote definition.
23253 (let ((element (save-excursion
23254 (end-of-line)
23255 (or (ignore-errors (org-element-at-point))
23256 (user-error "An element cannot be parsed line %d"
23257 (line-number-at-pos (point)))))))
23258 ;; First check if point is in a blank line at the beginning of
23259 ;; the buffer. In that case, ignore filling.
23260 (cl-case (org-element-type element)
23261 ;; Use major mode filling function is src blocks.
23262 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23263 ;; Align Org tables, leave table.el tables as-is.
23264 (table-row (org-table-align) t)
23265 (table
23266 (when (eq (org-element-property :type element) 'org)
23267 (save-excursion
23268 (goto-char (org-element-property :post-affiliated element))
23269 (org-table-align)))
23271 (paragraph
23272 ;; Paragraphs may contain `line-break' type objects.
23273 (let ((beg (max (point-min)
23274 (org-element-property :contents-begin element)))
23275 (end (min (point-max)
23276 (org-element-property :contents-end element))))
23277 ;; Do nothing if point is at an affiliated keyword.
23278 (if (< (line-end-position) beg) t
23279 (when (derived-mode-p 'message-mode)
23280 ;; In `message-mode', do not fill following citation
23281 ;; in current paragraph nor text before message body.
23282 (let ((body-start (save-excursion (message-goto-body))))
23283 (when body-start (setq beg (max body-start beg))))
23284 (when (save-excursion
23285 (re-search-forward
23286 (concat "^" message-cite-prefix-regexp) end t))
23287 (setq end (match-beginning 0))))
23288 ;; Fill paragraph, taking line breaks into account.
23289 (save-excursion
23290 (goto-char beg)
23291 (let ((cuts (list beg)))
23292 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23293 (when (eq 'line-break
23294 (org-element-type
23295 (save-excursion (backward-char)
23296 (org-element-context))))
23297 (push (point) cuts)))
23298 (dolist (c (delq end cuts))
23299 (fill-region-as-paragraph c end justify)
23300 (setq end c))))
23301 t)))
23302 ;; Contents of `comment-block' type elements should be
23303 ;; filled as plain text, but only if point is within block
23304 ;; markers.
23305 (comment-block
23306 (let* ((case-fold-search t)
23307 (beg (save-excursion
23308 (goto-char (org-element-property :begin element))
23309 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23310 (forward-line)
23311 (point)))
23312 (end (save-excursion
23313 (goto-char (org-element-property :end element))
23314 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23315 (line-beginning-position))))
23316 (if (or (< (point) beg) (> (point) end)) t
23317 (fill-region-as-paragraph
23318 (save-excursion (end-of-line)
23319 (re-search-backward "^[ \t]*$" beg 'move)
23320 (line-beginning-position))
23321 (save-excursion (beginning-of-line)
23322 (re-search-forward "^[ \t]*$" end 'move)
23323 (line-beginning-position))
23324 justify))))
23325 ;; Fill comments.
23326 (comment
23327 (let ((begin (org-element-property :post-affiliated element))
23328 (end (org-element-property :end element)))
23329 (when (and (>= (point) begin) (<= (point) end))
23330 (let ((begin (save-excursion
23331 (end-of-line)
23332 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23333 (progn (forward-line) (point))
23334 begin)))
23335 (end (save-excursion
23336 (end-of-line)
23337 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23338 (1- (line-beginning-position))
23339 (skip-chars-backward " \r\t\n")
23340 (line-end-position)))))
23341 ;; Do not fill comments when at a blank line.
23342 (when (> end begin)
23343 (let ((fill-prefix
23344 (save-excursion
23345 (beginning-of-line)
23346 (looking-at "[ \t]*#")
23347 (let ((comment-prefix (match-string 0)))
23348 (goto-char (match-end 0))
23349 (if (looking-at adaptive-fill-regexp)
23350 (concat comment-prefix (match-string 0))
23351 (concat comment-prefix " "))))))
23352 (save-excursion
23353 (fill-region-as-paragraph begin end justify))))))
23355 ;; Ignore every other element.
23356 (otherwise t))))))
23358 (defun org-auto-fill-function ()
23359 "Auto-fill function."
23360 ;; Check if auto-filling is meaningful.
23361 (let ((fc (current-fill-column)))
23362 (when (and fc (> (current-column) fc))
23363 (let* ((fill-prefix (org-adaptive-fill-function))
23364 ;; Enforce empty fill prefix, if required. Otherwise, it
23365 ;; will be computed again.
23366 (adaptive-fill-mode (not (equal fill-prefix ""))))
23367 (when fill-prefix (do-auto-fill))))))
23369 (defun org-comment-line-break-function (&optional soft)
23370 "Break line at point and indent, continuing comment if within one.
23371 The inserted newline is marked hard if variable
23372 `use-hard-newlines' is true, unless optional argument SOFT is
23373 non-nil."
23374 (if soft (insert-and-inherit ?\n) (newline 1))
23375 (save-excursion (forward-char -1) (delete-horizontal-space))
23376 (delete-horizontal-space)
23377 (indent-to-left-margin)
23378 (insert-before-markers-and-inherit fill-prefix))
23381 ;;; Fixed Width Areas
23383 (defun org-toggle-fixed-width ()
23384 "Toggle fixed-width markup.
23386 Add or remove fixed-width markup on current line, whenever it
23387 makes sense. Return an error otherwise.
23389 If a region is active and if it contains only fixed-width areas
23390 or blank lines, remove all fixed-width markup in it. If the
23391 region contains anything else, convert all non-fixed-width lines
23392 to fixed-width ones.
23394 Blank lines at the end of the region are ignored unless the
23395 region only contains such lines."
23396 (interactive)
23397 (if (not (org-region-active-p))
23398 ;; No region:
23400 ;; Remove fixed width marker only in a fixed-with element.
23402 ;; Add fixed width maker in paragraphs, in blank lines after
23403 ;; elements or at the beginning of a headline or an inlinetask,
23404 ;; and before any one-line elements (e.g., a clock).
23405 (progn
23406 (beginning-of-line)
23407 (let* ((element (org-element-at-point))
23408 (type (org-element-type element)))
23409 (cond
23410 ((and (eq type 'fixed-width)
23411 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23412 (replace-match
23413 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23414 ((and (memq type '(babel-call clock comment diary-sexp headline
23415 horizontal-rule keyword paragraph
23416 planning))
23417 (<= (org-element-property :post-affiliated element) (point)))
23418 (skip-chars-forward " \t")
23419 (insert ": "))
23420 ((and (looking-at-p "[ \t]*$")
23421 (or (eq type 'inlinetask)
23422 (save-excursion
23423 (skip-chars-forward " \r\t\n")
23424 (<= (org-element-property :end element) (point)))))
23425 (delete-region (point) (line-end-position))
23426 (org-indent-line)
23427 (insert ": "))
23428 (t (user-error "Cannot insert a fixed-width line here")))))
23429 ;; Region active.
23430 (let* ((begin (save-excursion
23431 (goto-char (region-beginning))
23432 (line-beginning-position)))
23433 (end (copy-marker
23434 (save-excursion
23435 (goto-char (region-end))
23436 (unless (eolp) (beginning-of-line))
23437 (if (save-excursion (re-search-backward "\\S-" begin t))
23438 (progn (skip-chars-backward " \r\t\n") (point))
23439 (point)))))
23440 (all-fixed-width-p
23441 (catch 'not-all-p
23442 (save-excursion
23443 (goto-char begin)
23444 (skip-chars-forward " \r\t\n")
23445 (when (eobp) (throw 'not-all-p nil))
23446 (while (< (point) end)
23447 (let ((element (org-element-at-point)))
23448 (if (eq (org-element-type element) 'fixed-width)
23449 (goto-char (org-element-property :end element))
23450 (throw 'not-all-p nil))))
23451 t))))
23452 (if all-fixed-width-p
23453 (save-excursion
23454 (goto-char begin)
23455 (while (< (point) end)
23456 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23457 (replace-match
23458 "" nil nil nil
23459 (if (= (line-end-position) (match-end 0)) 0 1)))
23460 (forward-line)))
23461 (let ((min-ind (point-max)))
23462 ;; Find minimum indentation across all lines.
23463 (save-excursion
23464 (goto-char begin)
23465 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23466 (setq min-ind 0)
23467 (catch 'zerop
23468 (while (< (point) end)
23469 (unless (looking-at-p "[ \t]*$")
23470 (let ((ind (org-get-indentation)))
23471 (setq min-ind (min min-ind ind))
23472 (when (zerop ind) (throw 'zerop t))))
23473 (forward-line)))))
23474 ;; Loop over all lines and add fixed-width markup everywhere
23475 ;; but in fixed-width lines.
23476 (save-excursion
23477 (goto-char begin)
23478 (while (< (point) end)
23479 (cond
23480 ((org-at-heading-p)
23481 (insert ": ")
23482 (forward-line)
23483 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23484 (insert ":")
23485 (forward-line)))
23486 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23487 (let* ((element (org-element-at-point))
23488 (element-end (org-element-property :end element)))
23489 (if (eq (org-element-type element) 'fixed-width)
23490 (progn (goto-char element-end)
23491 (skip-chars-backward " \r\t\n")
23492 (forward-line))
23493 (let ((limit (min end element-end)))
23494 (while (< (point) limit)
23495 (org-move-to-column min-ind t)
23496 (insert ": ")
23497 (forward-line))))))
23499 (org-move-to-column min-ind t)
23500 (insert ": ")
23501 (forward-line)))))))
23502 (set-marker end nil))))
23505 ;;; Comments
23507 ;; Org comments syntax is quite complex. It requires the entire line
23508 ;; to be just a comment. Also, even with the right syntax at the
23509 ;; beginning of line, some some elements (i.e. verse-block or
23510 ;; example-block) don't accept comments. Usual Emacs comment commands
23511 ;; cannot cope with those requirements. Therefore, Org replaces them.
23513 ;; Org still relies on `comment-dwim', but cannot trust
23514 ;; `comment-only-p'. So, `comment-region-function' and
23515 ;; `uncomment-region-function' both point
23516 ;; to`org-comment-or-uncomment-region'. Eventually,
23517 ;; `org-insert-comment' takes care of insertion of comments at the
23518 ;; beginning of line.
23520 ;; `org-setup-comments-handling' install comments related variables
23521 ;; during `org-mode' initialization.
23523 (defun org-setup-comments-handling ()
23524 (interactive)
23525 (setq-local comment-use-syntax nil)
23526 (setq-local comment-start "# ")
23527 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23528 (setq-local comment-insert-comment-function 'org-insert-comment)
23529 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23530 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23532 (defun org-insert-comment ()
23533 "Insert an empty comment above current line.
23534 If the line is empty, insert comment at its beginning. When
23535 point is within a source block, comment according to the related
23536 major mode."
23537 (if (let ((element (org-element-at-point)))
23538 (and (eq (org-element-type element) 'src-block)
23539 (< (save-excursion
23540 (goto-char (org-element-property :post-affiliated element))
23541 (line-end-position))
23542 (point))
23543 (> (save-excursion
23544 (goto-char (org-element-property :end element))
23545 (skip-chars-backward " \r\t\n")
23546 (line-beginning-position))
23547 (point))))
23548 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23549 (beginning-of-line)
23550 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23551 (open-line 1))
23552 (org-indent-line)
23553 (insert "# ")))
23555 (defvar comment-empty-lines) ; From newcomment.el.
23556 (defun org-comment-or-uncomment-region (beg end &rest _)
23557 "Comment or uncomment each non-blank line in the region.
23558 Uncomment each non-blank line between BEG and END if it only
23559 contains commented lines. Otherwise, comment them. If region is
23560 strictly within a source block, use appropriate comment syntax."
23561 (if (let ((element (org-element-at-point)))
23562 (and (eq (org-element-type element) 'src-block)
23563 (< (save-excursion
23564 (goto-char (org-element-property :post-affiliated element))
23565 (line-end-position))
23566 beg)
23567 (>= (save-excursion
23568 (goto-char (org-element-property :end element))
23569 (skip-chars-backward " \r\t\n")
23570 (line-beginning-position))
23571 end)))
23572 ;; Translate region boundaries for the Org buffer to the source
23573 ;; buffer.
23574 (let ((offset (- end beg)))
23575 (save-excursion
23576 (goto-char beg)
23577 (org-babel-do-in-edit-buffer
23578 (comment-or-uncomment-region (point) (+ offset (point))))))
23579 (save-restriction
23580 ;; Restrict region
23581 (narrow-to-region (save-excursion (goto-char beg)
23582 (skip-chars-forward " \r\t\n" end)
23583 (line-beginning-position))
23584 (save-excursion (goto-char end)
23585 (skip-chars-backward " \r\t\n" beg)
23586 (line-end-position)))
23587 (let ((uncommentp
23588 ;; UNCOMMENTP is non-nil when every non blank line between
23589 ;; BEG and END is a comment.
23590 (save-excursion
23591 (goto-char (point-min))
23592 (while (and (not (eobp))
23593 (let ((element (org-element-at-point)))
23594 (and (eq (org-element-type element) 'comment)
23595 (goto-char (min (point-max)
23596 (org-element-property
23597 :end element)))))))
23598 (eobp))))
23599 (if uncommentp
23600 ;; Only blank lines and comments in region: uncomment it.
23601 (save-excursion
23602 (goto-char (point-min))
23603 (while (not (eobp))
23604 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23605 (replace-match "" nil nil nil 1))
23606 (forward-line)))
23607 ;; Comment each line in region.
23608 (let ((min-indent (point-max)))
23609 ;; First find the minimum indentation across all lines.
23610 (save-excursion
23611 (goto-char (point-min))
23612 (while (and (not (eobp)) (not (zerop min-indent)))
23613 (unless (looking-at "[ \t]*$")
23614 (setq min-indent (min min-indent (current-indentation))))
23615 (forward-line)))
23616 ;; Then loop over all lines.
23617 (save-excursion
23618 (goto-char (point-min))
23619 (while (not (eobp))
23620 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23621 ;; Don't get fooled by invisible text (e.g. link path)
23622 ;; when moving to column MIN-INDENT.
23623 (let ((buffer-invisibility-spec nil))
23624 (org-move-to-column min-indent t))
23625 (insert comment-start))
23626 (forward-line)))))))))
23628 (defun org-comment-dwim (_arg)
23629 "Call `comment-dwim' within a source edit buffer if needed."
23630 (interactive "*P")
23631 (if (org-in-src-block-p)
23632 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23633 (call-interactively 'comment-dwim)))
23636 ;;; Timestamps API
23638 ;; This section contains tools to operate on timestamp objects, as
23639 ;; returned by, e.g. `org-element-context'.
23641 (defun org-timestamp--to-internal-time (timestamp &optional end)
23642 "Encode TIMESTAMP object into Emacs internal time.
23643 Use end of date range or time range when END is non-nil."
23644 (apply #'encode-time
23645 (cons 0
23646 (mapcar
23647 (lambda (prop) (or (org-element-property prop timestamp) 0))
23648 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23649 '(:minute-start :hour-start :day-start :month-start
23650 :year-start))))))
23652 (defun org-timestamp-has-time-p (timestamp)
23653 "Non-nil when TIMESTAMP has a time specified."
23654 (org-element-property :hour-start timestamp))
23656 (defun org-timestamp-format (timestamp format &optional end utc)
23657 "Format a TIMESTAMP object into a string.
23659 FORMAT is a format specifier to be passed to
23660 `format-time-string'.
23662 When optional argument END is non-nil, use end of date-range or
23663 time-range, if possible.
23665 When optional argument UTC is non-nil, time will be expressed as
23666 Universal Time."
23667 (format-time-string
23668 format (org-timestamp--to-internal-time timestamp end)
23669 (and utc t)))
23671 (defun org-timestamp-split-range (timestamp &optional end)
23672 "Extract a TIMESTAMP object from a date or time range.
23674 END, when non-nil, means extract the end of the range.
23675 Otherwise, extract its start.
23677 Return a new timestamp object."
23678 (let ((type (org-element-property :type timestamp)))
23679 (if (memq type '(active inactive diary)) timestamp
23680 (let ((split-ts (org-element-copy timestamp)))
23681 ;; Set new type.
23682 (org-element-put-property
23683 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23684 ;; Copy start properties over end properties if END is
23685 ;; non-nil. Otherwise, copy end properties over `start' ones.
23686 (let ((p-alist '((:minute-start . :minute-end)
23687 (:hour-start . :hour-end)
23688 (:day-start . :day-end)
23689 (:month-start . :month-end)
23690 (:year-start . :year-end))))
23691 (dolist (p-cell p-alist)
23692 (org-element-put-property
23693 split-ts
23694 (funcall (if end #'car #'cdr) p-cell)
23695 (org-element-property
23696 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23697 ;; Eventually refresh `:raw-value'.
23698 (org-element-put-property split-ts :raw-value nil)
23699 (org-element-put-property
23700 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23702 (defun org-timestamp-translate (timestamp &optional boundary)
23703 "Translate TIMESTAMP object to custom format.
23705 Format string is defined in `org-time-stamp-custom-formats',
23706 which see.
23708 When optional argument BOUNDARY is non-nil, it is either the
23709 symbol `start' or `end'. In this case, only translate the
23710 starting or ending part of TIMESTAMP if it is a date or time
23711 range. Otherwise, translate both parts.
23713 Return timestamp as-is if `org-display-custom-times' is nil or if
23714 it has a `diary' type."
23715 (let ((type (org-element-property :type timestamp)))
23716 (if (or (not org-display-custom-times) (eq type 'diary))
23717 (org-element-interpret-data timestamp)
23718 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23719 org-time-stamp-custom-formats)))
23720 (if (and (not boundary) (memq type '(active-range inactive-range)))
23721 (concat (org-timestamp-format timestamp fmt)
23722 "--"
23723 (org-timestamp-format timestamp fmt t))
23724 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23728 ;;; Other stuff.
23730 (defvar reftex-docstruct-symbol)
23731 (defvar org--rds)
23733 (defun org-reftex-citation ()
23734 "Use reftex-citation to insert a citation into the buffer.
23735 This looks for a line like
23737 #+BIBLIOGRAPHY: foo plain option:-d
23739 and derives from it that foo.bib is the bibliography file relevant
23740 for this document. It then installs the necessary environment for RefTeX
23741 to work in this buffer and calls `reftex-citation' to insert a citation
23742 into the buffer.
23744 Export of such citations to both LaTeX and HTML is handled by the contributed
23745 package ox-bibtex by Taru Karttunen."
23746 (interactive)
23747 (let ((reftex-docstruct-symbol 'org--rds)
23748 org--rds bib)
23749 (org-with-wide-buffer
23750 (let ((case-fold-search t)
23751 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23752 (if (not (save-excursion
23753 (or (re-search-forward re nil t)
23754 (re-search-backward re nil t))))
23755 (user-error "No bibliography defined in file")
23756 (setq bib (concat (match-string 1) ".bib")
23757 org--rds (list (list 'bib bib))))))
23758 (call-interactively 'reftex-citation)))
23760 ;;;; Functions extending outline functionality
23762 (defun org-beginning-of-line (&optional n)
23763 "Go to the beginning of the current visible line.
23765 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23766 tags on the first attempt, and only move to after the tags when
23767 the cursor is already beyond the end of the headline.
23769 With argument N not nil or 1, move forward N - 1 lines first."
23770 (interactive "^p")
23771 (let ((origin (point))
23772 (special (pcase org-special-ctrl-a/e
23773 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23774 deactivate-mark)
23775 ;; First move to a visible line.
23776 (if (bound-and-true-p visual-line-mode)
23777 (beginning-of-visual-line n)
23778 (move-beginning-of-line n)
23779 ;; `move-beginning-of-line' may leave point after invisible
23780 ;; characters if line starts with such of these (e.g., with
23781 ;; a link at column 0). Really move to the beginning of the
23782 ;; current visible line.
23783 (beginning-of-line))
23784 (cond
23785 ;; No special behavior. Point is already at the beginning of
23786 ;; a line, logical or visual.
23787 ((not special))
23788 ;; `beginning-of-visual-line' left point before logical beginning
23789 ;; of line: point is at the beginning of a visual line. Bail
23790 ;; out.
23791 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23792 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23793 ;; At a headline, special position is before the title, but
23794 ;; after any TODO keyword or priority cookie.
23795 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23796 (line-end-position)))
23797 (bol (point)))
23798 (if (eq special 'reversed)
23799 (when (and (= origin bol) (eq last-command this-command))
23800 (goto-char refpos))
23801 (when (or (> origin refpos) (= origin bol))
23802 (goto-char refpos)))))
23803 ((and (looking-at org-list-full-item-re)
23804 (memq (org-element-type (save-match-data (org-element-at-point)))
23805 '(item plain-list)))
23806 ;; Set special position at first white space character after
23807 ;; bullet, and check-box, if any.
23808 (let ((after-bullet
23809 (let ((box (match-end 3)))
23810 (cond ((not box) (match-end 1))
23811 ((eq (char-after box) ?\s) (1+ box))
23812 (t box)))))
23813 (if (eq special 'reversed)
23814 (when (and (= (point) origin) (eq last-command this-command))
23815 (goto-char after-bullet))
23816 (when (or (> origin after-bullet) (= (point) origin))
23817 (goto-char after-bullet)))))
23818 ;; No special context. Point is already at beginning of line.
23819 (t nil))))
23821 (defun org-end-of-line (&optional n)
23822 "Go to the end of the line, but before ellipsis, if any.
23824 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23825 tags on the first attempt, and only move to after the tags when
23826 the cursor is already beyond the end of the headline.
23828 With argument N not nil or 1, move forward N - 1 lines first."
23829 (interactive "^p")
23830 (let ((origin (point))
23831 (special (pcase org-special-ctrl-a/e
23832 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23833 deactivate-mark)
23834 ;; First move to a visible line.
23835 (if (bound-and-true-p visual-line-mode)
23836 (beginning-of-visual-line n)
23837 (move-beginning-of-line n))
23838 (cond
23839 ;; At a headline, with tags.
23840 ((and special
23841 (save-excursion
23842 (beginning-of-line)
23843 (let ((case-fold-search nil))
23844 (looking-at org-complex-heading-regexp)))
23845 (match-end 5))
23846 (let ((tags (save-excursion
23847 (goto-char (match-beginning 5))
23848 (skip-chars-backward " \t")
23849 (point)))
23850 (visual-end (and (bound-and-true-p visual-line-mode)
23851 (save-excursion
23852 (end-of-visual-line)
23853 (point)))))
23854 ;; If `end-of-visual-line' brings us before end of line or
23855 ;; even tags, i.e., the headline spans over multiple visual
23856 ;; lines, move there.
23857 (cond ((and visual-end
23858 (< visual-end tags)
23859 (<= origin visual-end))
23860 (goto-char visual-end))
23861 ((eq special 'reversed)
23862 (if (and (= origin (line-end-position))
23863 (eq this-command last-command))
23864 (goto-char tags)
23865 (end-of-line)))
23867 (if (or (< origin tags) (= origin (line-end-position)))
23868 (goto-char tags)
23869 (end-of-line))))))
23870 ((bound-and-true-p visual-line-mode)
23871 (let ((bol (line-beginning-position)))
23872 (end-of-visual-line)
23873 ;; If `end-of-visual-line' gets us past the ellipsis at the
23874 ;; end of a line, backtrack and use `end-of-line' instead.
23875 (when (/= bol (line-beginning-position))
23876 (goto-char bol)
23877 (end-of-line))))
23878 (t (end-of-line)))))
23880 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23881 (define-key org-mode-map "\C-e" 'org-end-of-line)
23883 (defun org-backward-sentence (&optional _arg)
23884 "Go to beginning of sentence, or beginning of table field.
23885 This will call `backward-sentence' or `org-table-beginning-of-field',
23886 depending on context."
23887 (interactive)
23888 (let* ((element (org-element-at-point))
23889 (contents-begin (org-element-property :contents-begin element))
23890 (table (org-element-lineage element '(table) t)))
23891 (if (and table
23892 (> (point) contents-begin)
23893 (<= (point) (org-element-property :contents-end table)))
23894 (call-interactively #'org-table-beginning-of-field)
23895 (save-restriction
23896 (when (and contents-begin
23897 (< (point-min) contents-begin)
23898 (> (point) contents-begin))
23899 (narrow-to-region contents-begin
23900 (org-element-property :contents-end element)))
23901 (call-interactively #'backward-sentence)))))
23903 (defun org-forward-sentence (&optional _arg)
23904 "Go to end of sentence, or end of table field.
23905 This will call `forward-sentence' or `org-table-end-of-field',
23906 depending on context."
23907 (interactive)
23908 (let* ((element (org-element-at-point))
23909 (contents-end (org-element-property :contents-end element))
23910 (table (org-element-lineage element '(table) t)))
23911 (if (and table
23912 (>= (point) (org-element-property :contents-begin table))
23913 (< (point) contents-end))
23914 (call-interactively #'org-table-end-of-field)
23915 (save-restriction
23916 (when (and contents-end
23917 (> (point-max) contents-end)
23918 ;; Skip blank lines between elements.
23919 (< (org-element-property :end element)
23920 (save-excursion (goto-char contents-end)
23921 (skip-chars-forward " \r\t\n"))))
23922 (narrow-to-region (org-element-property :contents-begin element)
23923 contents-end))
23924 (call-interactively #'forward-sentence)))))
23926 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23927 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23929 (defun org-kill-line (&optional _arg)
23930 "Kill line, to tags or end of line."
23931 (interactive)
23932 (cond
23933 ((or (not org-special-ctrl-k)
23934 (bolp)
23935 (not (org-at-heading-p)))
23936 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23937 org-ctrl-k-protect-subtree
23938 (or (eq org-ctrl-k-protect-subtree 'error)
23939 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23940 (user-error "C-k aborted as it would kill a hidden subtree"))
23941 (call-interactively
23942 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23943 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23944 (kill-region (point) (match-beginning 1))
23945 (org-set-tags nil t))
23946 (t (kill-region (point) (point-at-eol)))))
23948 (define-key org-mode-map "\C-k" 'org-kill-line)
23950 (defun org-yank (&optional arg)
23951 "Yank. If the kill is a subtree, treat it specially.
23952 This command will look at the current kill and check if is a single
23953 subtree, or a series of subtrees[1]. If it passes the test, and if the
23954 cursor is at the beginning of a line or after the stars of a currently
23955 empty headline, then the yank is handled specially. How exactly depends
23956 on the value of the following variables.
23958 `org-yank-folded-subtrees'
23959 By default, this variable is non-nil, which results in
23960 subtree(s) being folded after insertion, except if doing so
23961 would swallow text after the yanked text.
23963 `org-yank-adjusted-subtrees'
23964 When non-nil (the default value is nil), the subtree will be
23965 promoted or demoted in order to fit into the local outline tree
23966 structure, which means that the level will be adjusted so that it
23967 becomes the smaller one of the two *visible* surrounding headings.
23969 Any prefix to this command will cause `yank' to be called directly with
23970 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23971 will just
23972 plainly yank the text as it is.
23974 \[1] The test checks if the first non-white line is a heading
23975 and if there are no other headings with fewer stars."
23976 (interactive "P")
23977 (org-yank-generic 'yank arg))
23979 (defun org-yank-generic (command arg)
23980 "Perform some yank-like command.
23982 This function implements the behavior described in the `org-yank'
23983 documentation. However, it has been generalized to work for any
23984 interactive command with similar behavior."
23986 ;; pretend to be command COMMAND
23987 (setq this-command command)
23989 (if arg
23990 (call-interactively command)
23992 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23993 (and (org-kill-is-subtree-p)
23994 (or (bolp)
23995 (and (looking-at "[ \t]*$")
23996 (string-match
23997 "\\`\\*+\\'"
23998 (buffer-substring (point-at-bol) (point)))))))
23999 swallowp)
24000 (cond
24001 ((and subtreep org-yank-folded-subtrees)
24002 (let ((beg (point))
24003 end)
24004 (if (and subtreep org-yank-adjusted-subtrees)
24005 (org-paste-subtree nil nil 'for-yank)
24006 (call-interactively command))
24008 (setq end (point))
24009 (goto-char beg)
24010 (when (and (bolp) subtreep
24011 (not (setq swallowp
24012 (org-yank-folding-would-swallow-text beg end))))
24013 (org-with-limited-levels
24014 (or (looking-at org-outline-regexp)
24015 (re-search-forward org-outline-regexp-bol end t))
24016 (while (and (< (point) end) (looking-at org-outline-regexp))
24017 (outline-hide-subtree)
24018 (org-cycle-show-empty-lines 'folded)
24019 (condition-case nil
24020 (outline-forward-same-level 1)
24021 (error (goto-char end))))))
24022 (when swallowp
24023 (message
24024 "Inserted text not folded because that would swallow text"))
24026 (goto-char end)
24027 (skip-chars-forward " \t\n\r")
24028 (beginning-of-line 1)
24029 (push-mark beg 'nomsg)))
24030 ((and subtreep org-yank-adjusted-subtrees)
24031 (let ((beg (point-at-bol)))
24032 (org-paste-subtree nil nil 'for-yank)
24033 (push-mark beg 'nomsg)))
24035 (call-interactively command))))))
24037 (defun org-yank-folding-would-swallow-text (beg end)
24038 "Would hide-subtree at BEG swallow any text after END?"
24039 (let (level)
24040 (org-with-limited-levels
24041 (save-excursion
24042 (goto-char beg)
24043 (when (or (looking-at org-outline-regexp)
24044 (re-search-forward org-outline-regexp-bol end t))
24045 (setq level (org-outline-level)))
24046 (goto-char end)
24047 (skip-chars-forward " \t\r\n\v\f")
24048 (not (or (eobp)
24049 (and (bolp) (looking-at-p org-outline-regexp)
24050 (<= (org-outline-level) level))))))))
24052 (define-key org-mode-map "\C-y" 'org-yank)
24054 (defun org-truely-invisible-p ()
24055 "Check if point is at a character currently not visible.
24056 This version does not only check the character property, but also
24057 `visible-mode'."
24058 (unless (bound-and-true-p visible-mode)
24059 (org-invisible-p)))
24061 (defun org-invisible-p2 ()
24062 "Check if point is at a character currently not visible.
24064 If the point is at EOL (and not at the beginning of a buffer too),
24065 move it back by one char before doing this check."
24066 (save-excursion
24067 (when (and (eolp) (not (bobp)))
24068 (backward-char 1))
24069 (org-invisible-p)))
24071 (defun org-back-to-heading (&optional invisible-ok)
24072 "Call `outline-back-to-heading', but provide a better error message."
24073 (condition-case nil
24074 (outline-back-to-heading invisible-ok)
24075 (error (error "Before first headline at position %d in buffer %s"
24076 (point) (current-buffer)))))
24078 (defun org-before-first-heading-p ()
24079 "Before first heading?"
24080 (save-excursion
24081 (end-of-line)
24082 (null (re-search-backward org-outline-regexp-bol nil t))))
24084 (defun org-at-heading-p (&optional ignored)
24085 (outline-on-heading-p t))
24087 (defun org-in-commented-heading-p (&optional no-inheritance)
24088 "Non-nil if point is under a commented heading.
24089 This function also checks ancestors of the current headline,
24090 unless optional argument NO-INHERITANCE is non-nil."
24091 (cond
24092 ((org-before-first-heading-p) nil)
24093 ((let ((headline (nth 4 (org-heading-components))))
24094 (and headline
24095 (let ((case-fold-search nil))
24096 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24097 headline)))))
24098 (no-inheritance nil)
24100 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24102 (defun org-at-comment-p nil
24103 "Is cursor in a commented line?"
24104 (save-excursion
24105 (save-match-data
24106 (beginning-of-line)
24107 (looking-at "^[ \t]*# "))))
24109 (defun org-at-drawer-p nil
24110 "Is cursor at a drawer keyword?"
24111 (save-excursion
24112 (move-beginning-of-line 1)
24113 (looking-at org-drawer-regexp)))
24115 (defun org-at-block-p nil
24116 "Is cursor at a block keyword?"
24117 (save-excursion
24118 (move-beginning-of-line 1)
24119 (looking-at org-block-regexp)))
24121 (defun org-point-at-end-of-empty-headline ()
24122 "If point is at the end of an empty headline, return t, else nil.
24123 If the heading only contains a TODO keyword, it is still still considered
24124 empty."
24125 (let ((case-fold-search nil))
24126 (and (looking-at "[ \t]*$")
24127 org-todo-line-regexp
24128 (save-excursion
24129 (beginning-of-line)
24130 (looking-at org-todo-line-regexp)
24131 (string= (match-string 3) "")))))
24133 (defun org-at-heading-or-item-p ()
24134 (or (org-at-heading-p) (org-at-item-p)))
24136 (defun org-at-target-p ()
24137 (or (org-in-regexp org-radio-target-regexp)
24138 (org-in-regexp org-target-regexp)))
24139 ;; Compatibility alias with Org versions < 7.8.03
24140 (defalias 'org-on-target-p 'org-at-target-p)
24142 (defun org-up-heading-all (arg)
24143 "Move to the heading line of which the present line is a subheading.
24144 This function considers both visible and invisible heading lines.
24145 With argument, move up ARG levels."
24146 (outline-up-heading arg t))
24148 (defun org-up-heading-safe ()
24149 "Move to the heading line of which the present line is a subheading.
24150 This version will not throw an error. It will return the level of the
24151 headline found, or nil if no higher level is found.
24153 Also, this function will be a lot faster than `outline-up-heading',
24154 because it relies on stars being the outline starters. This can really
24155 make a significant difference in outlines with very many siblings."
24156 (when (ignore-errors (org-back-to-heading t))
24157 (let ((level-up (1- (funcall outline-level))))
24158 (and (> level-up 0)
24159 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24160 (funcall outline-level)))))
24162 (defun org-first-sibling-p ()
24163 "Is this heading the first child of its parents?"
24164 (interactive)
24165 (let ((re org-outline-regexp-bol)
24166 level l)
24167 (unless (org-at-heading-p t)
24168 (user-error "Not at a heading"))
24169 (setq level (funcall outline-level))
24170 (save-excursion
24171 (if (not (re-search-backward re nil t))
24173 (setq l (funcall outline-level))
24174 (< l level)))))
24176 (defun org-goto-sibling (&optional previous)
24177 "Goto the next sibling, even if it is invisible.
24178 When PREVIOUS is set, go to the previous sibling instead. Returns t
24179 when a sibling was found. When none is found, return nil and don't
24180 move point."
24181 (let ((fun (if previous 're-search-backward 're-search-forward))
24182 (pos (point))
24183 (re org-outline-regexp-bol)
24184 level l)
24185 (when (ignore-errors (org-back-to-heading t))
24186 (setq level (funcall outline-level))
24187 (catch 'exit
24188 (or previous (forward-char 1))
24189 (while (funcall fun re nil t)
24190 (setq l (funcall outline-level))
24191 (when (< l level) (goto-char pos) (throw 'exit nil))
24192 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24193 (goto-char pos)
24194 nil))))
24196 (defun org-show-siblings ()
24197 "Show all siblings of the current headline."
24198 (save-excursion
24199 (while (org-goto-sibling) (org-flag-heading nil)))
24200 (save-excursion
24201 (while (org-goto-sibling 'previous)
24202 (org-flag-heading nil))))
24204 (defun org-goto-first-child ()
24205 "Goto the first child, even if it is invisible.
24206 Return t when a child was found. Otherwise don't move point and
24207 return nil."
24208 (let (level (pos (point)) (re org-outline-regexp-bol))
24209 (when (ignore-errors (org-back-to-heading t))
24210 (setq level (outline-level))
24211 (forward-char 1)
24212 (if (and (re-search-forward re nil t) (> (outline-level) level))
24213 (progn (goto-char (match-beginning 0)) t)
24214 (goto-char pos) nil))))
24216 (defun org-show-hidden-entry ()
24217 "Show an entry where even the heading is hidden."
24218 (save-excursion
24219 (org-show-entry)))
24221 (defun org-flag-heading (flag &optional entry)
24222 "Flag the current heading. FLAG non-nil means make invisible.
24223 When ENTRY is non-nil, show the entire entry."
24224 (save-excursion
24225 (org-back-to-heading t)
24226 ;; Check if we should show the entire entry
24227 (if entry
24228 (progn
24229 (org-show-entry)
24230 (save-excursion
24231 (and (outline-next-heading)
24232 (org-flag-heading nil))))
24233 (outline-flag-region (max (point-min) (1- (point)))
24234 (save-excursion (outline-end-of-heading) (point))
24235 flag))))
24237 (defun org-get-next-sibling ()
24238 "Move to next heading of the same level, and return point.
24239 If there is no such heading, return nil.
24240 This is like outline-next-sibling, but invisible headings are ok."
24241 (let ((level (funcall outline-level)))
24242 (outline-next-heading)
24243 (while (and (not (eobp)) (> (funcall outline-level) level))
24244 (outline-next-heading))
24245 (unless (or (eobp) (< (funcall outline-level) level))
24246 (point))))
24248 (defun org-get-last-sibling ()
24249 "Move to previous heading of the same level, and return point.
24250 If there is no such heading, return nil."
24251 (let ((opoint (point))
24252 (level (funcall outline-level)))
24253 (outline-previous-heading)
24254 (when (and (/= (point) opoint) (outline-on-heading-p t))
24255 (while (and (> (funcall outline-level) level)
24256 (not (bobp)))
24257 (outline-previous-heading))
24258 (unless (< (funcall outline-level) level)
24259 (point)))))
24261 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24262 "Goto to the end of a subtree."
24263 ;; This contains an exact copy of the original function, but it uses
24264 ;; `org-back-to-heading', to make it work also in invisible
24265 ;; trees. And is uses an invisible-ok argument.
24266 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24267 ;; Furthermore, when used inside Org, finding the end of a large subtree
24268 ;; with many children and grandchildren etc, this can be much faster
24269 ;; than the outline version.
24270 (org-back-to-heading invisible-ok)
24271 (let ((first t)
24272 (level (funcall outline-level)))
24273 (if (and (derived-mode-p 'org-mode) (< level 1000))
24274 ;; A true heading (not a plain list item), in Org
24275 ;; This means we can easily find the end by looking
24276 ;; only for the right number of stars. Using a regexp to do
24277 ;; this is so much faster than using a Lisp loop.
24278 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24279 (forward-char 1)
24280 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24281 ;; something else, do it the slow way
24282 (while (and (not (eobp))
24283 (or first (> (funcall outline-level) level)))
24284 (setq first nil)
24285 (outline-next-heading)))
24286 (unless to-heading
24287 (when (memq (preceding-char) '(?\n ?\^M))
24288 ;; Go to end of line before heading
24289 (forward-char -1)
24290 (when (memq (preceding-char) '(?\n ?\^M))
24291 ;; leave blank line before heading
24292 (forward-char -1)))))
24293 (point))
24295 (defun org-end-of-meta-data (&optional full)
24296 "Skip planning line and properties drawer in current entry.
24297 When optional argument FULL is non-nil, also skip empty lines,
24298 clocking lines and regular drawers at the beginning of the
24299 entry."
24300 (org-back-to-heading t)
24301 (forward-line)
24302 (when (looking-at-p org-planning-line-re) (forward-line))
24303 (when (looking-at org-property-drawer-re)
24304 (goto-char (match-end 0))
24305 (forward-line))
24306 (when (and full (not (org-at-heading-p)))
24307 (catch 'exit
24308 (let ((end (save-excursion (outline-next-heading) (point)))
24309 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24310 (while (not (eobp))
24311 (cond ((looking-at-p org-drawer-regexp)
24312 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24313 (forward-line)
24314 (throw 'exit t)))
24315 ((looking-at-p re) (forward-line))
24316 (t (throw 'exit t))))))))
24318 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24319 "Move forward to the ARG'th subheading at same level as this one.
24320 Stop at the first and last subheadings of a superior heading.
24321 Normally this only looks at visible headings, but when INVISIBLE-OK is
24322 non-nil it will also look at invisible ones."
24323 (interactive "p")
24324 (let ((backward? (and arg (< arg 0))))
24325 (if (org-before-first-heading-p)
24326 (if backward? (goto-char (point-min)) (outline-next-heading))
24327 (org-back-to-heading invisible-ok)
24328 (unless backward? (end-of-line)) ;do not match current headline
24329 (let ((level (- (match-end 0) (match-beginning 0) 1))
24330 (f (if backward? #'re-search-backward #'re-search-forward))
24331 (count (if arg (abs arg) 1))
24332 (result (point)))
24333 (while (and (> count 0)
24334 (funcall f org-outline-regexp-bol nil 'move))
24335 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24336 (cond ((< l level) (setq count 0))
24337 ((and (= l level)
24338 (or invisible-ok
24339 (not (org-invisible-p
24340 (line-beginning-position)))))
24341 (cl-decf count)
24342 (when (= l level) (setq result (point)))))))
24343 (goto-char result))
24344 (beginning-of-line))))
24346 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24347 "Move backward to the ARG'th subheading at same level as this one.
24348 Stop at the first and last subheadings of a superior heading."
24349 (interactive "p")
24350 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24352 (defun org-next-visible-heading (arg)
24353 "Move to the next visible heading.
24355 This function wraps `outline-next-visible-heading' with
24356 `org-with-limited-levels' in order to skip over inline tasks and
24357 respect customization of `org-odd-levels-only'."
24358 (interactive "p")
24359 (org-with-limited-levels
24360 (outline-next-visible-heading arg)))
24362 (defun org-previous-visible-heading (arg)
24363 "Move to the previous visible heading.
24365 This function wraps `outline-previous-visible-heading' with
24366 `org-with-limited-levels' in order to skip over inline tasks and
24367 respect customization of `org-odd-levels-only'."
24368 (interactive "p")
24369 (org-with-limited-levels
24370 (outline-previous-visible-heading arg)))
24372 (defun org-next-block (arg &optional backward block-regexp)
24373 "Jump to the next block.
24375 With a prefix argument ARG, jump forward ARG many blocks.
24377 When BACKWARD is non-nil, jump to the previous block.
24379 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24380 Match data is set according to this regexp when the function
24381 returns.
24383 Return point at beginning of the opening line of found block.
24384 Throw an error if no block is found."
24385 (interactive "p")
24386 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24387 (case-fold-search t)
24388 (search-fn (if backward #'re-search-backward #'re-search-forward))
24389 (count (or arg 1))
24390 (origin (point))
24391 last-element)
24392 (if backward (beginning-of-line) (end-of-line))
24393 (while (and (> count 0) (funcall search-fn re nil t))
24394 (let ((element (save-excursion
24395 (goto-char (match-beginning 0))
24396 (save-match-data (org-element-at-point)))))
24397 (when (and (memq (org-element-type element)
24398 '(center-block comment-block dynamic-block
24399 example-block export-block quote-block
24400 special-block src-block verse-block))
24401 (<= (match-beginning 0)
24402 (org-element-property :post-affiliated element)))
24403 (setq last-element element)
24404 (cl-decf count))))
24405 (if (= count 0)
24406 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24407 (save-match-data (org-show-context)))
24408 (goto-char origin)
24409 (user-error "No %s code blocks" (if backward "previous" "further")))))
24411 (defun org-previous-block (arg &optional block-regexp)
24412 "Jump to the previous block.
24413 With a prefix argument ARG, jump backward ARG many source blocks.
24414 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24415 (interactive "p")
24416 (org-next-block arg t block-regexp))
24418 (defun org-forward-paragraph ()
24419 "Move forward to beginning of next paragraph or equivalent.
24421 The function moves point to the beginning of the next visible
24422 structural element, which can be a paragraph, a table, a list
24423 item, etc. It also provides some special moves for convenience:
24425 - On an affiliated keyword, jump to the beginning of the
24426 relative element.
24427 - On an item or a footnote definition, move to the second
24428 element inside, if any.
24429 - On a table or a property drawer, jump after it.
24430 - On a verse or source block, stop after blank lines."
24431 (interactive)
24432 (when (eobp) (user-error "Cannot move further down"))
24433 (let* ((deactivate-mark nil)
24434 (element (org-element-at-point))
24435 (type (org-element-type element))
24436 (post-affiliated (org-element-property :post-affiliated element))
24437 (contents-begin (org-element-property :contents-begin element))
24438 (contents-end (org-element-property :contents-end element))
24439 (end (let ((end (org-element-property :end element)) (parent element))
24440 (while (and (setq parent (org-element-property :parent parent))
24441 (= (org-element-property :contents-end parent) end))
24442 (setq end (org-element-property :end parent)))
24443 end)))
24444 (cond ((not element)
24445 (skip-chars-forward " \r\t\n")
24446 (or (eobp) (beginning-of-line)))
24447 ;; On affiliated keywords, move to element's beginning.
24448 ((< (point) post-affiliated)
24449 (goto-char post-affiliated))
24450 ;; At a table row, move to the end of the table. Similarly,
24451 ;; at a node property, move to the end of the property
24452 ;; drawer.
24453 ((memq type '(node-property table-row))
24454 (goto-char (org-element-property
24455 :end (org-element-property :parent element))))
24456 ((memq type '(property-drawer table)) (goto-char end))
24457 ;; Consider blank lines as separators in verse and source
24458 ;; blocks to ease editing.
24459 ((memq type '(src-block verse-block))
24460 (when (eq type 'src-block)
24461 (setq contents-end
24462 (save-excursion (goto-char end)
24463 (skip-chars-backward " \r\t\n")
24464 (line-beginning-position))))
24465 (beginning-of-line)
24466 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24467 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24468 (goto-char end)
24469 (skip-chars-forward " \r\t\n")
24470 (if (= (point) contents-end) (goto-char end)
24471 (beginning-of-line))))
24472 ;; With no contents, just skip element.
24473 ((not contents-begin) (goto-char end))
24474 ;; If contents are invisible, skip the element altogether.
24475 ((org-invisible-p (line-end-position))
24476 (cl-case type
24477 (headline
24478 (org-with-limited-levels (outline-next-visible-heading 1)))
24479 ;; At a plain list, make sure we move to the next item
24480 ;; instead of skipping the whole list.
24481 (plain-list (forward-char)
24482 (org-forward-paragraph))
24483 (otherwise (goto-char end))))
24484 ((>= (point) contents-end) (goto-char end))
24485 ((>= (point) contents-begin)
24486 ;; This can only happen on paragraphs and plain lists.
24487 (cl-case type
24488 (paragraph (goto-char end))
24489 ;; At a plain list, try to move to second element in
24490 ;; first item, if possible.
24491 (plain-list (end-of-line)
24492 (org-forward-paragraph))))
24493 ;; When contents start on the middle of a line (e.g. in
24494 ;; items and footnote definitions), try to reach first
24495 ;; element starting after current line.
24496 ((> (line-end-position) contents-begin)
24497 (end-of-line)
24498 (org-forward-paragraph))
24499 (t (goto-char contents-begin)))))
24501 (defun org-backward-paragraph ()
24502 "Move backward to start of previous paragraph or equivalent.
24504 The function moves point to the beginning of the current
24505 structural element, which can be a paragraph, a table, a list
24506 item, etc., or to the beginning of the previous visible one if
24507 point is already there. It also provides some special moves for
24508 convenience:
24510 - On an affiliated keyword, jump to the first one.
24511 - On a table or a property drawer, move to its beginning.
24512 - On a verse or source block, stop before blank lines."
24513 (interactive)
24514 (when (bobp) (user-error "Cannot move further up"))
24515 (let* ((deactivate-mark nil)
24516 (element (org-element-at-point))
24517 (type (org-element-type element))
24518 (contents-begin (org-element-property :contents-begin element))
24519 (contents-end (org-element-property :contents-end element))
24520 (post-affiliated (org-element-property :post-affiliated element))
24521 (begin (org-element-property :begin element)))
24522 (cond
24523 ((not element) (goto-char (point-min)))
24524 ((= (point) begin)
24525 (backward-char)
24526 (org-backward-paragraph))
24527 ((<= (point) post-affiliated) (goto-char begin))
24528 ((memq type '(node-property table-row))
24529 (goto-char (org-element-property
24530 :post-affiliated (org-element-property :parent element))))
24531 ((memq type '(property-drawer table)) (goto-char begin))
24532 ((memq type '(src-block verse-block))
24533 (when (eq type 'src-block)
24534 (setq contents-begin
24535 (save-excursion (goto-char begin) (forward-line) (point))))
24536 (if (= (point) contents-begin) (goto-char post-affiliated)
24537 ;; Inside a verse block, see blank lines as paragraph
24538 ;; separators.
24539 (let ((origin (point)))
24540 (skip-chars-backward " \r\t\n" contents-begin)
24541 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24542 (skip-chars-forward " \r\t\n" origin)
24543 (if (= (point) origin) (goto-char contents-begin)
24544 (beginning-of-line))))))
24545 ((not contents-begin) (goto-char (or post-affiliated begin)))
24546 ((eq type 'paragraph)
24547 (goto-char contents-begin)
24548 ;; When at first paragraph in an item or a footnote definition,
24549 ;; move directly to beginning of line.
24550 (let ((parent-contents
24551 (org-element-property
24552 :contents-begin (org-element-property :parent element))))
24553 (when (and parent-contents (= parent-contents contents-begin))
24554 (beginning-of-line))))
24555 ;; At the end of a greater element, move to the beginning of the
24556 ;; last element within.
24557 ((>= (point) contents-end)
24558 (goto-char (1- contents-end))
24559 (org-backward-paragraph))
24560 (t (goto-char (or post-affiliated begin))))
24561 ;; Ensure we never leave point invisible.
24562 (when (org-invisible-p (point)) (beginning-of-visual-line))))
24564 (defun org-forward-element ()
24565 "Move forward by one element.
24566 Move to the next element at the same level, when possible."
24567 (interactive)
24568 (cond ((eobp) (user-error "Cannot move further down"))
24569 ((org-with-limited-levels (org-at-heading-p))
24570 (let ((origin (point)))
24571 (goto-char (org-end-of-subtree nil t))
24572 (unless (org-with-limited-levels (org-at-heading-p))
24573 (goto-char origin)
24574 (user-error "Cannot move further down"))))
24576 (let* ((elem (org-element-at-point))
24577 (end (org-element-property :end elem))
24578 (parent (org-element-property :parent elem)))
24579 (cond ((and parent (= (org-element-property :contents-end parent) end))
24580 (goto-char (org-element-property :end parent)))
24581 ((integer-or-marker-p end) (goto-char end))
24582 (t (message "No element at point")))))))
24584 (defun org-backward-element ()
24585 "Move backward by one element.
24586 Move to the previous element at the same level, when possible."
24587 (interactive)
24588 (cond ((bobp) (user-error "Cannot move further up"))
24589 ((org-with-limited-levels (org-at-heading-p))
24590 ;; At a headline, move to the previous one, if any, or stay
24591 ;; here.
24592 (let ((origin (point)))
24593 (org-with-limited-levels (org-backward-heading-same-level 1))
24594 ;; When current headline has no sibling above, move to its
24595 ;; parent.
24596 (when (= (point) origin)
24597 (or (org-with-limited-levels (org-up-heading-safe))
24598 (progn (goto-char origin)
24599 (user-error "Cannot move further up"))))))
24601 (let* ((elem (org-element-at-point))
24602 (beg (org-element-property :begin elem)))
24603 (cond
24604 ;; Move to beginning of current element if point isn't
24605 ;; there already.
24606 ((null beg) (message "No element at point"))
24607 ((/= (point) beg) (goto-char beg))
24608 (t (goto-char beg)
24609 (skip-chars-backward " \r\t\n")
24610 (unless (bobp)
24611 (let ((prev (org-element-at-point)))
24612 (goto-char (org-element-property :begin prev))
24613 (while (and (setq prev (org-element-property :parent prev))
24614 (<= (org-element-property :end prev) beg))
24615 (goto-char (org-element-property :begin prev)))))))))))
24617 (defun org-up-element ()
24618 "Move to upper element."
24619 (interactive)
24620 (if (org-with-limited-levels (org-at-heading-p))
24621 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24622 (let* ((elem (org-element-at-point))
24623 (parent (org-element-property :parent elem)))
24624 (if parent (goto-char (org-element-property :begin parent))
24625 (if (org-with-limited-levels (org-before-first-heading-p))
24626 (user-error "No surrounding element")
24627 (org-with-limited-levels (org-back-to-heading)))))))
24629 (defun org-down-element ()
24630 "Move to inner element."
24631 (interactive)
24632 (let ((element (org-element-at-point)))
24633 (cond
24634 ((memq (org-element-type element) '(plain-list table))
24635 (goto-char (org-element-property :contents-begin element))
24636 (forward-char))
24637 ((memq (org-element-type element) org-element-greater-elements)
24638 ;; If contents are hidden, first disclose them.
24639 (when (org-invisible-p (line-end-position)) (org-cycle))
24640 (goto-char (or (org-element-property :contents-begin element)
24641 (user-error "No content for this element"))))
24642 (t (user-error "No inner element")))))
24644 (defun org-drag-element-backward ()
24645 "Move backward element at point."
24646 (interactive)
24647 (let ((elem (or (org-element-at-point)
24648 (user-error "No element at point"))))
24649 (if (eq (org-element-type elem) 'headline)
24650 ;; Preserve point when moving a whole tree, even if point was
24651 ;; on blank lines below the headline.
24652 (let ((offset (skip-chars-backward " \t\n")))
24653 (unwind-protect (org-move-subtree-up)
24654 (forward-char (- offset))))
24655 (let ((prev-elem
24656 (save-excursion
24657 (goto-char (org-element-property :begin elem))
24658 (skip-chars-backward " \r\t\n")
24659 (unless (bobp)
24660 (let* ((beg (org-element-property :begin elem))
24661 (prev (org-element-at-point))
24662 (up prev))
24663 (while (and (setq up (org-element-property :parent up))
24664 (<= (org-element-property :end up) beg))
24665 (setq prev up))
24666 prev)))))
24667 ;; Error out if no previous element or previous element is
24668 ;; a parent of the current one.
24669 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24670 (user-error "Cannot drag element backward")
24671 (let ((pos (point)))
24672 (org-element-swap-A-B prev-elem elem)
24673 (goto-char (+ (org-element-property :begin prev-elem)
24674 (- pos (org-element-property :begin elem))))))))))
24676 (defun org-drag-element-forward ()
24677 "Move forward element at point."
24678 (interactive)
24679 (let* ((pos (point))
24680 (elem (or (org-element-at-point)
24681 (user-error "No element at point"))))
24682 (when (= (point-max) (org-element-property :end elem))
24683 (user-error "Cannot drag element forward"))
24684 (goto-char (org-element-property :end elem))
24685 (let ((next-elem (org-element-at-point)))
24686 (when (or (org-element-nested-p elem next-elem)
24687 (and (eq (org-element-type next-elem) 'headline)
24688 (not (eq (org-element-type elem) 'headline))))
24689 (goto-char pos)
24690 (user-error "Cannot drag element forward"))
24691 ;; Compute new position of point: it's shifted by NEXT-ELEM
24692 ;; body's length (without final blanks) and by the length of
24693 ;; blanks between ELEM and NEXT-ELEM.
24694 (let ((size-next (- (save-excursion
24695 (goto-char (org-element-property :end next-elem))
24696 (skip-chars-backward " \r\t\n")
24697 (forward-line)
24698 ;; Small correction if buffer doesn't end
24699 ;; with a newline character.
24700 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24701 (org-element-property :begin next-elem)))
24702 (size-blank (- (org-element-property :end elem)
24703 (save-excursion
24704 (goto-char (org-element-property :end elem))
24705 (skip-chars-backward " \r\t\n")
24706 (forward-line)
24707 (point)))))
24708 (org-element-swap-A-B elem next-elem)
24709 (goto-char (+ pos size-next size-blank))))))
24711 (defun org-drag-line-forward (arg)
24712 "Drag the line at point ARG lines forward."
24713 (interactive "p")
24714 (dotimes (_ (abs arg))
24715 (let ((c (current-column)))
24716 (if (< 0 arg)
24717 (progn
24718 (beginning-of-line 2)
24719 (transpose-lines 1)
24720 (beginning-of-line 0))
24721 (transpose-lines 1)
24722 (beginning-of-line -1))
24723 (org-move-to-column c))))
24725 (defun org-drag-line-backward (arg)
24726 "Drag the line at point ARG lines backward."
24727 (interactive "p")
24728 (org-drag-line-forward (- arg)))
24730 (defun org-mark-element ()
24731 "Put point at beginning of this element, mark at end.
24733 Interactively, if this command is repeated or (in Transient Mark
24734 mode) if the mark is active, it marks the next element after the
24735 ones already marked."
24736 (interactive)
24737 (let (deactivate-mark)
24738 (if (and (called-interactively-p 'any)
24739 (or (and (eq last-command this-command) (mark t))
24740 (and transient-mark-mode mark-active)))
24741 (set-mark
24742 (save-excursion
24743 (goto-char (mark))
24744 (goto-char (org-element-property :end (org-element-at-point)))))
24745 (let ((element (org-element-at-point)))
24746 (end-of-line)
24747 (push-mark (org-element-property :end element) t t)
24748 (goto-char (org-element-property :begin element))))))
24750 (defun org-narrow-to-element ()
24751 "Narrow buffer to current element."
24752 (interactive)
24753 (let ((elem (org-element-at-point)))
24754 (cond
24755 ((eq (car elem) 'headline)
24756 (narrow-to-region
24757 (org-element-property :begin elem)
24758 (org-element-property :end elem)))
24759 ((memq (car elem) org-element-greater-elements)
24760 (narrow-to-region
24761 (org-element-property :contents-begin elem)
24762 (org-element-property :contents-end elem)))
24764 (narrow-to-region
24765 (org-element-property :begin elem)
24766 (org-element-property :end elem))))))
24768 (defun org-transpose-element ()
24769 "Transpose current and previous elements, keeping blank lines between.
24770 Point is moved after both elements."
24771 (interactive)
24772 (org-skip-whitespace)
24773 (let ((end (org-element-property :end (org-element-at-point))))
24774 (org-drag-element-backward)
24775 (goto-char end)))
24777 (defun org-unindent-buffer ()
24778 "Un-indent the visible part of the buffer.
24779 Relative indentation (between items, inside blocks, etc.) isn't
24780 modified."
24781 (interactive)
24782 (unless (eq major-mode 'org-mode)
24783 (user-error "Cannot un-indent a buffer not in Org mode"))
24784 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24785 (unindent-tree
24786 (lambda (contents)
24787 (dolist (element (reverse contents))
24788 (if (memq (org-element-type element) '(headline section))
24789 (funcall unindent-tree (org-element-contents element))
24790 (save-excursion
24791 (save-restriction
24792 (narrow-to-region
24793 (org-element-property :begin element)
24794 (org-element-property :end element))
24795 (org-do-remove-indentation))))))))
24796 (funcall unindent-tree (org-element-contents parse-tree))))
24798 (defun org-show-children (&optional level)
24799 "Show all direct subheadings of this heading.
24800 Prefix arg LEVEL is how many levels below the current level
24801 should be shown. Default is enough to cause the following
24802 heading to appear."
24803 (interactive "p")
24804 ;; If `orgstruct-mode' is active, use the slower version.
24805 (if orgstruct-mode (call-interactively #'outline-show-children)
24806 (save-excursion
24807 (org-back-to-heading t)
24808 (let* ((current-level (funcall outline-level))
24809 (max-level (org-get-valid-level
24810 current-level
24811 (if level (prefix-numeric-value level) 1)))
24812 (end (save-excursion (org-end-of-subtree t t)))
24813 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24814 (past-first-child nil)
24815 ;; Make sure to skip inlinetasks.
24816 (re (format regexp-fmt
24817 current-level
24818 (cond
24819 ((not (featurep 'org-inlinetask)) "")
24820 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24822 (t (1- org-inlinetask-min-level))))))
24823 ;; Display parent heading.
24824 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24825 (forward-line)
24826 ;; Display children. First child may be deeper than expected
24827 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24828 ;; MAX-LEVEL accordingly.
24829 (while (re-search-forward re end t)
24830 (unless past-first-child
24831 (setq re (format regexp-fmt
24832 current-level
24833 (max (funcall outline-level) max-level)))
24834 (setq past-first-child t))
24835 (outline-flag-region
24836 (line-end-position 0) (line-end-position) nil))))))
24838 (defun org-show-subtree ()
24839 "Show everything after this heading at deeper levels."
24840 (interactive)
24841 (outline-flag-region
24842 (point)
24843 (save-excursion
24844 (org-end-of-subtree t t))
24845 nil))
24847 (defun org-show-entry ()
24848 "Show the body directly following this heading.
24849 Show the heading too, if it is currently invisible."
24850 (interactive)
24851 (save-excursion
24852 (ignore-errors
24853 (org-back-to-heading t)
24854 (outline-flag-region
24855 (max (point-min) (1- (point)))
24856 (save-excursion
24857 (if (re-search-forward
24858 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24859 (match-beginning 1)
24860 (point-max)))
24861 nil)
24862 (org-cycle-hide-drawers 'children))))
24864 (defun org-make-options-regexp (kwds &optional extra)
24865 "Make a regular expression for keyword lines.
24866 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24867 when non-nil, is a regexp matching keywords names."
24868 (concat "^[ \t]*#\\+\\("
24869 (regexp-opt kwds)
24870 (and extra (concat (and kwds "\\|") extra))
24871 "\\):[ \t]*\\(.*\\)"))
24873 ;;;; Integration with and fixes for other packages
24875 ;;; Imenu support
24877 (defvar-local org-imenu-markers nil
24878 "All markers currently used by Imenu.")
24880 (defun org-imenu-new-marker (&optional pos)
24881 "Return a new marker for use by Imenu, and remember the marker."
24882 (let ((m (make-marker)))
24883 (move-marker m (or pos (point)))
24884 (push m org-imenu-markers)
24887 (defun org-imenu-get-tree ()
24888 "Produce the index for Imenu."
24889 (dolist (x org-imenu-markers) (move-marker x nil))
24890 (setq org-imenu-markers nil)
24891 (let* ((case-fold-search nil)
24892 (n org-imenu-depth)
24893 (re (concat "^" (org-get-limited-outline-regexp)))
24894 (subs (make-vector (1+ n) nil))
24895 (last-level 0)
24896 m level head0 head)
24897 (org-with-wide-buffer
24898 (goto-char (point-max))
24899 (while (re-search-backward re nil t)
24900 (setq level (org-reduced-level (funcall outline-level)))
24901 (when (and (<= level n)
24902 (looking-at org-complex-heading-regexp)
24903 (setq head0 (match-string-no-properties 4)))
24904 (setq head (org-link-display-format head0)
24905 m (org-imenu-new-marker))
24906 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24907 (if (>= level last-level)
24908 (push (cons head m) (aref subs level))
24909 (push (cons head (aref subs (1+ level))) (aref subs level))
24910 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24911 (setq last-level level))))
24912 (aref subs 1)))
24914 (eval-after-load "imenu"
24915 '(progn
24916 (add-hook 'imenu-after-jump-hook
24917 (lambda ()
24918 (when (derived-mode-p 'org-mode)
24919 (org-show-context 'org-goto))))))
24921 (defun org-link-display-format (s)
24922 "Replace links in string S with their description.
24923 If there is no description, use the link target."
24924 (save-match-data
24925 (replace-regexp-in-string
24926 org-bracket-link-analytic-regexp
24927 (lambda (m)
24928 (if (match-end 5) (match-string 5 m)
24929 (concat (match-string 1 m) (match-string 3 m))))
24930 s nil t)))
24932 (defun org-toggle-link-display ()
24933 "Toggle the literal or descriptive display of links."
24934 (interactive)
24935 (if org-descriptive-links
24936 (progn (org-remove-from-invisibility-spec '(org-link))
24937 (org-restart-font-lock)
24938 (setq org-descriptive-links nil))
24939 (progn (add-to-invisibility-spec '(org-link))
24940 (org-restart-font-lock)
24941 (setq org-descriptive-links t))))
24943 ;; Speedbar support
24945 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24946 "Overlay marking the agenda restriction line in speedbar.")
24947 (overlay-put org-speedbar-restriction-lock-overlay
24948 'face 'org-agenda-restriction-lock)
24949 (overlay-put org-speedbar-restriction-lock-overlay
24950 'help-echo "Agendas are currently limited to this item.")
24951 (delete-overlay org-speedbar-restriction-lock-overlay)
24953 (defun org-speedbar-set-agenda-restriction ()
24954 "Restrict future agenda commands to the location at point in speedbar.
24955 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24956 (interactive)
24957 (require 'org-agenda)
24958 (let (p m tp np dir txt)
24959 (cond
24960 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24961 'org-imenu t))
24962 (setq m (get-text-property p 'org-imenu-marker))
24963 (with-current-buffer (marker-buffer m)
24964 (goto-char m)
24965 (org-agenda-set-restriction-lock 'subtree)))
24966 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24967 'speedbar-function 'speedbar-find-file))
24968 (setq tp (previous-single-property-change
24969 (1+ p) 'speedbar-function)
24970 np (next-single-property-change
24971 tp 'speedbar-function)
24972 dir (speedbar-line-directory)
24973 txt (buffer-substring-no-properties (or tp (point-min))
24974 (or np (point-max))))
24975 (with-current-buffer (find-file-noselect
24976 (let ((default-directory dir))
24977 (expand-file-name txt)))
24978 (unless (derived-mode-p 'org-mode)
24979 (user-error "Cannot restrict to non-Org mode file"))
24980 (org-agenda-set-restriction-lock 'file)))
24981 (t (user-error "Don't know how to restrict Org mode agenda")))
24982 (move-overlay org-speedbar-restriction-lock-overlay
24983 (point-at-bol) (point-at-eol))
24984 (setq current-prefix-arg nil)
24985 (org-agenda-maybe-redo)))
24987 (defvar speedbar-file-key-map)
24988 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24989 (eval-after-load "speedbar"
24990 '(progn
24991 (speedbar-add-supported-extension ".org")
24992 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24993 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24994 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24995 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24996 (add-hook 'speedbar-visiting-tag-hook
24997 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24999 ;;; Fixes and Hacks for problems with other packages
25001 (defun org--flyspell-object-check-p (element)
25002 "Non-nil when Flyspell can check object at point.
25003 ELEMENT is the element at point."
25004 (let ((object (save-excursion
25005 (when (looking-at-p "\\>") (backward-char))
25006 (org-element-context element))))
25007 (cl-case (org-element-type object)
25008 ;; Prevent checks in links due to keybinding conflict with
25009 ;; Flyspell.
25010 ((code entity export-snippet inline-babel-call
25011 inline-src-block line-break latex-fragment link macro
25012 statistics-cookie target timestamp verbatim)
25013 nil)
25014 (footnote-reference
25015 ;; Only in inline footnotes, within the definition.
25016 (and (eq (org-element-property :type object) 'inline)
25017 (< (save-excursion
25018 (goto-char (org-element-property :begin object))
25019 (search-forward ":" nil t 2))
25020 (point))))
25021 (otherwise t))))
25023 (defun org-mode-flyspell-verify ()
25024 "Function used for `flyspell-generic-check-word-predicate'."
25025 (if (org-at-heading-p)
25026 ;; At a headline or an inlinetask, check title only. This is
25027 ;; faster than relying on `org-element-at-point'.
25028 (and (save-excursion (beginning-of-line)
25029 (and (let ((case-fold-search t))
25030 (not (looking-at-p "\\*+ END[ \t]*$")))
25031 (let ((case-fold-search nil))
25032 (looking-at org-complex-heading-regexp))))
25033 (match-beginning 4)
25034 (>= (point) (match-beginning 4))
25035 (or (not (match-beginning 5))
25036 (< (point) (match-beginning 5))))
25037 (let* ((element (org-element-at-point))
25038 (post-affiliated (org-element-property :post-affiliated element)))
25039 (cond
25040 ;; Ignore checks in all affiliated keywords but captions.
25041 ((< (point) post-affiliated)
25042 (and (save-excursion
25043 (beginning-of-line)
25044 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25045 (> (point) (match-end 0))
25046 (org--flyspell-object-check-p element)))
25047 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25048 ((let ((log (org-log-into-drawer)))
25049 (and log
25050 (let ((drawer (org-element-lineage element '(drawer))))
25051 (and drawer
25052 (eq (compare-strings
25053 log nil nil
25054 (org-element-property :drawer-name drawer) nil nil t)
25055 t)))))
25056 nil)
25058 (cl-case (org-element-type element)
25059 ((comment quote-section) t)
25060 (comment-block
25061 ;; Allow checks between block markers, not on them.
25062 (and (> (line-beginning-position) post-affiliated)
25063 (save-excursion
25064 (end-of-line)
25065 (skip-chars-forward " \r\t\n")
25066 (< (point) (org-element-property :end element)))))
25067 ;; Arbitrary list of keywords where checks are meaningful.
25068 ;; Make sure point is on the value part of the element.
25069 (keyword
25070 (and (member (org-element-property :key element)
25071 '("DESCRIPTION" "TITLE"))
25072 (save-excursion
25073 (search-backward ":" (line-beginning-position) t))))
25074 ;; Check is globally allowed in paragraphs verse blocks and
25075 ;; table rows (after affiliated keywords) but some objects
25076 ;; must not be affected.
25077 ((paragraph table-row verse-block)
25078 (let ((cbeg (org-element-property :contents-begin element))
25079 (cend (org-element-property :contents-end element)))
25080 (and cbeg (>= (point) cbeg) (< (point) cend)
25081 (org--flyspell-object-check-p element))))))))))
25082 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25084 (defun org-remove-flyspell-overlays-in (beg end)
25085 "Remove flyspell overlays in region."
25086 (and (bound-and-true-p flyspell-mode)
25087 (fboundp 'flyspell-delete-region-overlays)
25088 (flyspell-delete-region-overlays beg end)))
25090 (defvar flyspell-delayed-commands)
25091 (eval-after-load "flyspell"
25092 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25094 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25095 (eval-after-load "bookmark"
25096 '(if (boundp 'bookmark-after-jump-hook)
25097 ;; We can use the hook
25098 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25099 ;; Hook not available, use advice
25100 (defadvice bookmark-jump (after org-make-visible activate)
25101 "Make the position visible."
25102 (org-bookmark-jump-unhide))))
25104 ;; Make sure saveplace shows the location if it was hidden
25105 (eval-after-load "saveplace"
25106 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25107 "Make the position visible."
25108 (org-bookmark-jump-unhide)))
25110 ;; Make sure ecb shows the location if it was hidden
25111 (eval-after-load "ecb"
25112 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25113 "Make hierarchy visible when jumping into location from ECB tree buffer."
25114 (when (derived-mode-p 'org-mode)
25115 (org-show-context))))
25117 (defun org-bookmark-jump-unhide ()
25118 "Unhide the current position, to show the bookmark location."
25119 (and (derived-mode-p 'org-mode)
25120 (or (org-invisible-p)
25121 (save-excursion (goto-char (max (point-min) (1- (point))))
25122 (org-invisible-p)))
25123 (org-show-context 'bookmark-jump)))
25125 (defun org-mark-jump-unhide ()
25126 "Make the point visible with `org-show-context' after jumping to the mark."
25127 (when (and (derived-mode-p 'org-mode)
25128 (org-invisible-p))
25129 (org-show-context 'mark-goto)))
25131 (eval-after-load "simple"
25132 '(defadvice pop-to-mark-command (after org-make-visible activate)
25133 "Make the point visible with `org-show-context'."
25134 (org-mark-jump-unhide)))
25136 (eval-after-load "simple"
25137 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25138 "Make the point visible with `org-show-context'."
25139 (org-mark-jump-unhide)))
25141 (eval-after-load "simple"
25142 '(defadvice pop-global-mark (after org-make-visible activate)
25143 "Make the point visible with `org-show-context'."
25144 (org-mark-jump-unhide)))
25146 ;; Make session.el ignore our circular variable
25147 (defvar session-globals-exclude)
25148 (eval-after-load "session"
25149 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25151 ;;;; Finish up
25153 (provide 'org)
25155 (run-hooks 'org-load-hook)
25157 ;;; org.el ends here